Python ( I need answer in two hours)

Compose a function odd() that takes three bool arguments and returns True if an odd
number of arguments are True, and False otherwise.

I need this question in two hours, otherwise I won't be able to send it to teacher.

If possible, you can help me on q3 too.

I need your help, I have to pass this lesson.

Guest April 17, 2018, 1:45 p.m. 0 Answer 

Django admin codeless edit

Is there a way to edit the functionality of my admin panel without tampering with the code. I.e. a drag-and-drop editor, modular editor, etc?

As you can guess i am a novice and only need to make a few light/medium changes to my panel from time to time. 

Thanks in advance. 

Guest Nov. 16, 2017, 5:08 p.m. 0 Answer 

How to load multiple models in views via using ModelForm? from django.db import models from django.contrib.auth.models import User class UserDetails(models.Model): mobile_no = models.BigIntegerField(unique = True) flat_no = models.TextField(max_length = 7, verbose_name = "Flat No./ Room No.") area = models.TextField(max_length = 15) state = models.TextField(max_length = 50) country = models.TextField(max_length = 50) city = models.TextField(max_length = 50) near_by = models.TextField(max_length = 50, null = True, blank = True, verbose_name = "Landmark") aadhaar_no = models.BigIntegerField(unique = True) locality = models.TextField(max_length = 50) pincode = models.PositiveIntegerField() user = models.ForeignKey(User) def __unicode__(self): return self.mobile_no RegisterUser.html {{ form.non_field_errors }}

{% csrf_token %} {{ form.as_p }} {{ second_form.as_p }} from django.views.generic.edit import FormView from app.forms import UserDetailsForm, UserForm class RegisterUserView(FormView): form_class = UserDetailsForm template_name = 'app/RegisterUser.html' from django import forms from app.models.UserDetailsModel import * from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] class UserDetailsForm(forms.ModelForm): class Meta: model = UserDetails fields = ['mobile_no', 'flat_no', 'area', 'state', 'country', 'city', 'near_by', 'aadhaar_no', 'locality', 'pincode', 'user'] def get_second_form(self): if self.request.method == 'POST': return UserForm(self.request.POST) else: return UserForm() def form_valid(self, form): print self.request.POST self.second_form = self.get_second_form() if self.second_form.is_valid(): return super(UserDetailsForm, self).form_valid(form) else: return super(UserDetailsForm, self).form_invalid(form) def form_invalid(self, form): self.second_form = self.get_second_form() self.second_form.is_valid() return super(UserDetailsForm, self).form_invalid(form) def get_context_data(self, **kwargs): context = super(UserDetailsForm, self).get_context_data(**kwargs) context['second_form'] = getattr(self, 'second_form', self.get_second_form()) return context I want to load User and UserDetails model in single html and validate via ModelForm. Nov. 1, 2017, 5:33 a.m. 0 Answer 

Django translations - when, how

When django ugettext_lazy search for PO files? when app start? or when request is processed?

Do splitting PO files across folders impact performance?

Guest Sept. 11, 2017, 6:33 a.m. 0 Answer 

How Do to create a Filing system using Django.

Hello Django Tuts Team.

I am developing a website for file and data storage using Django, where I want the Users to be able to upload their files to and also manage content on those files with different levels of security. I want them to be able to create folders to sstore said files and delete them. Example: Dropbox.

I want to use MySQL to save the files, please how do i go about doing this. July 19, 2017, 10:44 a.m. 0 Answer 

Is it possible add fields to the model from another app?

Hi all,

I used to Odoo (OpenERP) for some times. It provide a function "_inherit" that can add fields to the model from another module (app). Is it possible to do it in Django? Since I want to create a plugin to add some fields into the models instead of edit the original app inside.






Guest June 28, 2017, 4:48 a.m. 1 Answer 

Django keep me login feature is not working

I want a solution if any anyone can assist me.
When customer will login with Keep me logged in checked then session will not be expire, But if Keep me logged in is not checked then should expire as per bellow mentioned variable value.

So Now login without checked keep me logged in is working fine as we have set SESSION_SECURITY_WARN_AFTER and SESSION_SECURITY_EXPIRE_AFTER. And if keep me login is checked, I tried to disable by overriding above variable value or increase expire time using request.session.set_expiry(24*30*3600). But it is not working. Can you anyone advice how can I disable this expire time if keep me login is checked.

SESSION_SECURITY_EXPIRE_AFTER = EXPIRE_TIME + 180 June 7, 2017, 5:19 a.m. 0 Answer 

save the variation of radio buttons django

Hello i have a form with three radio buttons they aren't a part of But when the user click on radio buttons i want to save their value in a variable called strategy in I defined in views : request.Post.get ('tabs') the name of radio buttons. But the error was **('WSGIRequest' object has no attribute 'Post')** Everything is saved excluding the value of radio buttons.

    class Parameters(models.Model):
    MARKET= ((1,'Nasdaq'),(2, 'Nyse'),(3,'Amex'),)  
    SECTOR_CHOICES = ((1,'Utilities'),(2, 'Basic Materials'),(3,'Healthcare'), (4,'Services'),(5,'Financial'),)

    user         = models.ForeignKey(User)
    title         = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters')
    type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest")
    strategy = models.CharField('Strategy', choices=STRATEGY_CHOICES, max_length=20,default="Long")

    #input characteristics
    price_1_min                = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
    price_1_max                = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
    stocks_num_2_min            = models.IntegerField('2. Number of selected stock, min', default=3, validators=[MinValueValidator(0), MaxValueValidator(100)])
    stocks_num_2_max            = models.IntegerField('2. Number of selected stock, max', default=7, validators=[MinValueValidator(1),])
    holding_period                          = models.IntegerField('3. Holding Period', default=1, validators=[MinValueValidator(1),])
    volume                                  = models.IntegerField('4. Volume', default=0, validators=[MinValueValidator(0),])
    market = models.CharField('Market', max_length=30, null=True)
    sector= models.CharField('Sector', max_length=30, null=True)

    class BacktestForm(forms.ModelForm):

    period_start = forms.DateField( - datetime.timedelta(days=365+16), widget=forms.widgets.DateInput(format="%Y/%m/%d"), input_formats=["%Y/%m/%d"])
    period_end     = forms.DateField( - datetime.timedelta(days=16), widget=forms.widgets.DateInput(format="%Y/%m/%d"), input_formats=["%Y/%m/%d"])
        market = forms.MultipleChoiceField(label='Market', choices=Parameters.MARKET, widget=forms.CheckboxSelectMultiple)
        sector = forms.MultipleChoiceField(label='Sector', choices=Parameters.SECTOR_CHOICES, widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = Parameters
        exclude = [
            'title': forms.TextInput(attrs={'placeholder':'for ex. highLimitLowPrice'}),
                        'sector': forms.CheckboxSelectMultiple(),


     <div class="row">
        <div class='col-md-9'> 
                  <div id="tabs">

                   <input type="radio" name="tabs" id="toggle-tab1"  checked="checked" />
                   <label for="toggle-tab1">Long</label>

                   <input type="radio" name="tabs" id="toggle-tab2"    />
                   <label for="toggle-tab2">Short</label>

                   <input type="radio" name="tabs" id="toggle-tab3"   />
                   <label for="toggle-tab3">Long and Short</label>
                   <div id="tab1" class="tab"  >
            <form action="{% url "backtest" %}" method='POST' role='form' id='form'>
                {% csrf_token %}
                {% include 'tags/parameters_form.html' %}
                <br />
                {% include 'tags/parameters_backtest_form.html' %}
                                {% if user.is_authenticated %}
                                <input type='submit' id='run' value='Run' class='btn btn-default'>
                    {% if user.profile.is_active %}
                        Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
                    {% else %}
                        Expired account! you need to reactivate in order to save parameters.
                    {% endif %}
                {% else %}
                                         Please <a href="{% url 'auth_login' %}">login</a> in order to Run backtesting!
                     Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).   
                                  {% endif %}                        

                        </form> (for the save function):

    def backtest(request, pk=None):

    if pk is not None:
        param = get_object_or_404(Parameters, pk=pk, user=request.user)
        form = BacktestForm(request.POST or None, instance=param)
        form = BacktestForm(request.POST or None)
        if request.method == 'POST':
        if form.is_valid():
            if 'save' in request.POST:
                                obj = False)
                                obj.user = request.user
                obj.type = "backtest"
          , 'Saved!')
                return redirect(obj.get_backtest_url())

 June 7, 2017, 3:50 a.m. 0 Answer 

Fetching API data in json format and inserting it into the django local database.

Hi i am new to Django, can you please guide me as to how i can fetch data from a companies database and insert it into my database. I have been reading about and and all tutorials and readings i came accross has online shown be how to display the database data onto the html and how to export data already in the database as json data.

Guest June 5, 2017, 2:21 a.m. 1 Answer 

django mongodg and pymongo

i am working on django mongodg and pymongo. i was wondering if someone has a django project (with mongodb and pymongo)  . I can't do  connect them. i will be grateful

Guest May 30, 2017, 7:54 a.m. 1 Answer 

Django Custom Field cleaning for Integer

I have this puzzling django form

Here is part of my handling the POST request

def getUpdataBet(request, name):


    elif request.method == 'POST':

         Bound_form = form_Net(request.POST, instance=obj)

         if Bound_form.is_valid():

                new_tag =

                return render(request, 'Account\Sucess.html', .........)


                 render(request, ......)


And my has this custom cleaning for the form page.


def clean_BetAccountBalance(self):

       Data = self.cleaned_data.get(BetAccountBalance)

       If Data > 800:

             raise forms.ValidationError("Value too Large")


               return data


My question is that, In my form page when i give a value greater than 800, it returns the validation error as usual. But when i input a value lesser than 800, the form page acts as bound_form.is_valid() is false

The most puzzling thing is that when i comment out the if and else statement, it works perfectly fine and returns the cleaned_data perfectly. Is it that you dont use an if statement in a custom clean method.? May 25, 2017, 2:51 p.m. 0 Answer 

Validation issue with my Form

 I have this puzzling issue with my forms. Here is my part of my handling the POST request.

elif request.method == 'POST':
        obj.BetAccountBalance += int(request.POST['BetAccountBalance'])
        bound_form = form_Net({'BetAccountBalance':obj.BetAccountBalance}, instance=obj)

        if bound_form.is_valid():
            new_tag =
            NetObj.AccountBal -= int(request.POST['BetAccountBalance'])
            return render(request, 'Account/Success.html', {'value':'Bet'})
            bound_form = form_Net(request.POST, instance=obj)
            context = {'NetObj':NetObj.AccountBal, 'form':bound_form, 'email':name}
            return render(request, template_name, context)


And here is my and it has a custom clean method for my IntegerField in my form

class TransferToMyBet(forms.ModelForm):
    class Meta:
        model = BetDetails
        fields = ['BetAccountBalance']

    def clean_BetAccountBalance(self):
        data = self.cleaned_data.get('BetAccountBalance')
        if data > 800:
              raise forms.ValidationError('Not Enough Money')
            return data

In my form page in the browser, when i give a value greater than 800, it raises the Validation error as expected. But when i give a value less than 800, the form page doesnt save. Infact it purely acts as if Bound_form.is_valid() is false.


Another thing is that, when i comment out the if statement in the custom clean method, It works perfectly fine. Does that mean that, if statement doesnt work well with an Integer custom field cleaning?


Guest May 25, 2017, 4:26 a.m. 0 Answer 

Django 1.5 + gunicorn - No module named website.wsgi?

I am taking over this django legacy project which was built on **1.5.12**. I have no idea why they decided to remove from the project. So I am trying to put it back it.

    import os
    # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
    # if running multiple sites in the same mod_wsgi process. To fix this, use
    # mod_wsgi daemon mode with each site in its own daemon process, or use
    # os.environ["DJANGO_SETTINGS_MODULE"] = "website.settings"
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings")
    # This application object is used by any WSGI server configured to use this
    # file. This includes Django's development server, if the WSGI_APPLICATION
    # setting points here.
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()

        from local_settings import *
    except ImportError:
        from default_settings import *

    ROOT_URLCONF = 'website.urls'
    # Python dotted path to the WSGI application used by Django's runserver.
    WSGI_APPLICATION = 'website.wsgi.application'

Then I compile the project with:

    $ python runserver

    Validating models...
    0 errors found
    May 20, 2017 - 07:47:34
    Django version 1.5.12, using settings 'website.settings'
    Development server is running at
    Quit the server with CONTROL-C.

It works fine and I can see `wsgi.pyc` is generated.

But when I run it with `gunicorn`, I get this error:

    No module named website.wsgi

Details output:

    $ gunicorn website.wsgi:application                 
    2017-05-20 07:50:00 [4552] [INFO] Starting gunicorn 18.0
    2017-05-20 07:50:00 [4552] [INFO] Listening at: (4552)
    2017-05-20 07:50:00 [4552] [INFO] Using worker: sync
    2017-05-20 07:50:00 [4556] [INFO] Booting worker with pid: 4556
    2017-05-20 07:50:00 [4556] [ERROR] Exception in worker process:
    Traceback (most recent call last):
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/", line 495, in spawn_worker
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/workers/", line 106, in init_process
        self.wsgi =
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/", line 114, in wsgi
        self.callable = self.load()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/", line 62, in load
        return self.load_wsgiapp()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/", line 49, in load_wsgiapp
        return util.import_app(self.app_uri)
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/", line 354, in import_app
    ImportError: No module named website.wsgi
    Traceback (most recent call last):
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/", line 495, in spawn_worker
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/workers/", line 106, in init_process
        self.wsgi =
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/", line 114, in wsgi
        self.callable = self.load()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/", line 62, in load
        return self.load_wsgiapp()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/", line 49, in load_wsgiapp
        return util.import_app(self.app_uri)
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/", line 354, in import_app
    ImportError: No module named website.wsgi
    2017-05-20 07:50:00 [4556] [INFO] Worker exiting (pid: 4556)
    2017-05-20 07:50:00 [4552] [INFO] Shutting down: Master
    2017-05-20 07:50:00 [4552] [INFO] Reason: Worker failed to boot.

Why? What have I missed?

Guest May 20, 2017, 8:10 a.m. 2 Answer 
Load More Questions

Codility : Nesting

Determine whether given string of parentheses is properly nested. April 21, 2016, 9:03 a.m.

Codility : Brackets

Determine whether a given string of parentheses is properly nested. April 18, 2016, 2:31 a.m.

Bubble sort in Python

In this article you can see how to use Bubble sort in python April 16, 2016, 9:36 a.m.

Codility : Triangle

Determine whether a triangle can be built from a given set of edges. April 6, 2016, 8:23 a.m.

Codility : Distinct

Compute number of distinct values in an array. April 6, 2016, 7:53 a.m.

Codility : MinAvgTwoSlice

Find the minimal average of any slice containing at least two elements. April 5, 2016, 2:12 p.m.

Codility : PassingCars

Count the number of passing cars on the road. March 29, 2016, 3:49 a.m.

How to add custom django manager

In this article I'll show you how to create custom django manager. A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application. Jan. 5, 2015, 8:42 a.m.