EzDevInfo.com

django interview questions

Top django frequently asked interview questions

Capturing url parameters in request.GET

I am currently defining regular expressions in order to capture parameters in a url, as described in the tutorial. How do I access parameters from the url as part the HttpRequest object? My HttpRequest.GET currently returns an empty QueryDict object.

I'd like to learn how to do this without a library so I can get to know Django better.


Source: (StackOverflow)

In a django form, How to make a field readonly (or disabled) so that it cannot be edited?

In a django form, how do I make a field read-only (or disabled)?

When the form is being used to create a new entry, all fields should be enabled - but when the record is in update mode some fields need to be read-only.

For example, when creating a new Item model, all fields must be editable, but while updating the record, is there a way to disable sku field so that it is visible but cannot be edited?

class Item(models.Model):
    sku = models.CharField(max_length=50)
    description = models.CharField(max_length=200)    
    added_by = models.ForeignKey(User)    


class ItemForm(ModelForm):
    class Meta:
        model = Item
        exclude = ('added_by')      

def new_item_view(request):     
    if request.method == 'POST':
        form = ItemForm(request.POST)
        #validate and save
    else:
            form = ItemForm()       
    #render the view

Can class ItemForm be reused? What changes would be required in ItemForm or Item model class? Would I need to write another class, "ItemUpdateForm", for updating the item?

def update_item_view(request):      
    if request.method == 'POST':
        form = ItemUpdateForm(request.POST)
        #validate and save
    else:
        form = ItemUpdateForm()

Source: (StackOverflow)

Advertisements

What is a "slug" in Django?

When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used?

(I have read its definition in this glossary.)


Source: (StackOverflow)

How can I get the full/absolute URL (with domain) in Django?

Exactly the same as this question, but there must be a way to do it without the Sites module. That's just silly... I shouldn't need to query my DB to snag the URL!

I want to use it with reverse().


Source: (StackOverflow)

differentiate null=True, blank=True in django

When we add a database field in django we generally write models.CharField(max_length=100, null=True, blank=True). The same is done with ForeignKey, DecimalField etc. What is the basic difference in having

  1. null=True only
  2. blank=True only
  3. null=True, blank=True

in respect to different (CharField, ForeignKey, ManyToManyField, DateTimeField) fields. What are the advantages/disadvantages of using 1/2/3?


Source: (StackOverflow)

Need a minimal Django file upload example [closed]

As a newbie to Django, I am having difficulty making an upload app in Django 1.3. I could not find any up-to-date example/snippets. May someone post a minimal but complete (Model, View, Template) example code to do so?


Source: (StackOverflow)

How do I do a not equal in Django queryset filtering?

In Django model QuerySets, I see that there is a __gt and __lt for comparitive values, but is there a __ne/!=/<> (not equals?)

I want to filter out using a not equals:

Example:

Model:
    bool a;
    int x;

I want

results = Model.objects.exclude(a=true, x!=5)

The != is not correct syntax. I tried __ne, <>.

I ended up using:

results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5)

Source: (StackOverflow)

Creating a JSON response using Django and Python

I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.

This is the server-side script:

/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];

/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$arrayToJs[1] = $validateError;

if($validateValue =="Testuser"){  // Validate??
    $arrayToJs[2] = "true";       // RETURN TRUE
    echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';  // RETURN ARRAY WITH success
}
else{
    for($x=0;$x<1000000;$x++){
        if($x == 990000){
            $arrayToJs[2] = "false";
            echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';   // RETURNS ARRAY WITH ERROR.
        }
    }
}

And this is the converted code

def validate_user(request):
    if request.method == 'POST':
        vld_value = request.POST.get('validateValue')
        vld_id = request.POST.get('validateId')
        vld_error = request.POST.get('validateError')

        array_to_js = [vld_id, vld_error, False]

        if vld_value == "TestUser":
            array_to_js[2] = True
            x = simplejson.dumps(array_to_js)
            return HttpResponse(x)
        else:
            array_to_js[2] = False
            x = simplejson.dumps(array_to_js)
            error = 'Error'
            return render_to_response('index.html',{'error':error},context_instance=RequestContext(request))
    return render_to_response('index.html',context_instance=RequestContext(request))

I'm using simplejson to encode the Python list (so it will return a JSON array). I couldn't figure out the problem yet. But I think that I did something wrong about the 'echo'.


Source: (StackOverflow)

What is setup.py?

Can anyone please explain, what is setup.py and how can it be configured or used?


Source: (StackOverflow)

Converting string into datetime

Short and simple. I've got a huge list of date-times like this as strings:

Jun 1 2005  1:33PM
Aug 28 1999 12:00AM

I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.

Any help (even if it's just a kick in the right direction) would be appreciated.

Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.


Source: (StackOverflow)

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Whats the difference (in language a python/django noob can understand) in a view between render(), render_to_response() and direct_to_template()?

e.g. from Nathan Borror's basic apps examples

def comment_edit(request, object_id, template_name='comments/edit.html'):
    comment = get_object_or_404(Comment, pk=object_id, user=request.user)
    # ...
    return render(request, template_name, {
        'form': form,
        'comment': comment,
    })

But I've also seen

    return render_to_response(template_name, my_data_dictionary,
              context_instance=RequestContext(request))

And

    return direct_to_template(request, template_name, my_data_dictionary)

Whats the difference, what to use in any particular situation?


Source: (StackOverflow)

AngularJS with Django - Conflicting template tags

I want to use AngularJS with Django however they both use {{ }} as their template tags. Is there an easy way to change one of the two to use some other custom templating tag?


Source: (StackOverflow)

What's the best solution for OpenID with Django? [closed]

Please note: this is an ancient question with ancient answers. Most of the linked apps are now unmaintained. These days, most people seem to use django-allauth or python-social-auth. I'll leave the original question intact below for posterity's sake.


There are at least half a dozen Django apps that provide OpenID authentication for Django:

I played around with a couple of them. Simon Willison's django-openid made a good impression, but as he is at the forefront of trendsetting in Djangoland, I sometimes have difficulties wrapping my head around his trends (e.g. the whole dynamic urlpatterns system in django-openid). What's more, I couldn't get login to work with Google.

django-authopenid made a good impression, and it seems to have good integration with django-registration. django-socialauth and django-socialregistration have support for Twitter and Facebook, which is definitely a plus. Who knows if and when Facebook will start to be an OpenID provider...? socialauth seems to have its share of problems, though.

So, what is the best OpenID app out there? Please share any positive (and negative) experience. Thanks!


Source: (StackOverflow)

Django - Set Up A Scheduled Job?

I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically.

Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this.

Does anyone know how to set this up?

To clarify: I know I can set up a cron job to do this, but I'm curious if there is some feature in Django that provides this functionality. I'd like people to be able to deploy this app themselves without having to do much config (preferably zero).

I've considered triggering these actions "retroactively" by simply checking if a job should have been run since the last time a request was sent to the site, but I'm hoping for something a bit cleaner.


Source: (StackOverflow)

How to combine 2 or more querysets in a Django view?

I am trying to build the search for a Django site I am building, and in the search I am searching in 3 different models. And to get pagination on the search result list I would like to use a generic object_list view to display the results. But to do that i have to merge 3 querysets into one.

How can i do that? I've tried this:

result_list = []            
page_list = Page.objects.filter(Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term))
article_list = Article.objects.filter(Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term))
post_list = Post.objects.filter(Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term))

for x in page_list:
    result_list.append(x)
for x in article_list:
    result_list.append(x)
for x in post_list:
    result_list.append(x)

return object_list(request, queryset=result_list, template_object_name='result',
                   paginate_by=10, extra_context={'search_term': search_term},
                   template_name="search/result_list.html")

But this doesn't work I get an error when I try to use that list in the generic view. The list is missing the clone attribute.

Anybody know how I can merge the three lists, page_list, article_list and post_list?


Source: (StackOverflow)