EzDevInfo.com

django-views interview questions

Top django-views frequently asked interview questions

How do I use Logging in the Django Debug Toolbar?

I would like to output debug messages in my django app at different points in a view function. The docs for the django-debug-toolbar say it uses the build in python logging but I can't find any more information then that. I don't really want to log to a file but to the info pane on the toolbar. How does this work?


Source: (StackOverflow)

what is the right way to validate if an object exists in a django view without returning 404?

basically just verify if an object exists and return the object. then based on that perform actions. I'm wondering whats the right way to do it without returning a 404?

try:
    listing = RealEstateListing.objects.get(slug_url = slug)
except:
    listing = None

if listing:

Source: (StackOverflow)

Advertisements

What is the equivalent of "none" in django templates?

I want to see if a field/variable is none within a Django template. What is the correct syntax for that?

This is what I currently have:

{% if profile.user.first_name is null %}
  <p> -- </p>
{% elif %}
  {{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}

In the example above, what would I use to replace "null"?


Source: (StackOverflow)

Delete multiple objects in django

I need to select several objects to be deleted from my database in django using a webpage. There is no category to select from so I can't delete from all of them like that. Do I have to implement my own delete form and process it in django or does django have a way to already do this? As its implemented in the admin interface.


Source: (StackOverflow)

In django do models have a default timestamp field?

In django - is there a default timestamp field for all objects? That is, do I have to explicitly declare a 'timestamp' field for 'created on' in my Model - or is there a way to get this automagically?


Source: (StackOverflow)

Can I call a view from within another view?

One of my view needs to add an item, along with other functionality, but I already have another view which specifically adds an item.

Can I do something like:

def specific_add_item_view(request):
    item = Item.objects.create(foo=request.bar)

def big_view(request):
    # ...
    specific_add_item_view(request)

Source: (StackOverflow)

Return results from multiple models with Django REST Framework

I have three models — articles, authors and tweets. I'm ultimately needing to use Django REST Framework to construct a feed that aggregates all the objects using the Article and Tweet models into one reverse chronological feed.

Any idea how I'd do that? I get the feeling I need to create a new serializer, but I'm really not sure.

Thanks!

Edit: Here's what I've done thus far.

app/serializers.py:

class TimelineSerializer(serializers.Serializer):
    pk = serializers.Field()
    title = serializers.CharField()
    author = serializers.RelatedField()
    pub_date = serializers.DateTimeField()

app/views.py:

class TimelineViewSet(viewsets.ModelViewSet):
    """
    API endpoint that lists all tweet/article objects in rev-chrono.
    """
    queryset = itertools.chain(Tweet.objects.all(), Article.objects.all())
    serializer_class = TimelineSerializer

Source: (StackOverflow)

Django check if object in ManyToMany field

I have quite a simple problem to solve. I have Partner model which has >= 0 Users associated with it:

class Partner(models.Model):
    name = models.CharField(db_index=True, max_length=255)
    slug = models.SlugField(db_index=True)
    user = models.ManyToManyField(User)

Now, if I have a User object and I have a Partner object, what is the most Pythonic way of checking if the User is associated with a Partner? I basically want a statement which returns True if the User is associated to the Partner.

I have tried:

users = Partner.objects.values_list('user', flat=True).filter(slug=requested_slug)
if request.user.pk in users:
    # do some private stuff

This works but I have a feeling there is a better way. Additionally, would this be easy to roll into a decorator, baring in mind I need both a named parameter (slug) and a request object (user).

Any help would be much appreciated.


Source: (StackOverflow)

Django: how to get the id of the record just saved?

I'm using Django 1.3 for one of my projects and I need to get the ID of a record just saved in the database.

I have something like the code below to save a record in the database:

n = MyData.objects.create(record_title=title, record_content=content)
n.save()

The id of the record just saved auto-increments. Is there a way to get that id and use it somewhere else in my code?


Source: (StackOverflow)

Django check for any exists for a query

In django how to check whether any entry exists for a query

       sc=scorm.objects.filter(Header__id=qp.id)

This was how it was done in php

     if(mysql_num_rows($resultn))
     {
      }
      else
      {

       }

Source: (StackOverflow)

CSRF verification failed. Request aborted. on django

I am following Django 1.3 Web Development. and for logins, i am getting the following error

Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
    CSRF token missing or incorrect.

This is my settings.py Included APPS. It is exactly how the book says it should be.

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'djangocricket.Cricket',
    'djangocricket.cms'
)

The book says, it should contain, django.contrib.auth.views.login .. and i am including it in

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'djangocricket.Cricket.views.index', name='default'),
    url(r'^user/(\w+)/$', 'djangocricket.Cricket.views.user_home', name='user home'),
    url(r'^login/$', 'django.contrib.auth.views.login'),
    # url(r'^djangocricket/', include('djangocricket.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    #url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^news/', 'djangocricket.cms.views.index', name='index'),
    #url(r'^news/(?P<slug>[^\.]+).html', 'djangocricket.cms.views.detail', name='get_single_news_item'),
    url(r'^admin/', include(admin.site.urls)),
)

and my registration/login.html ... copy pasted from the book. it should do.

<html>
<head>
    <title>Django Bookmarks - User Login</title>
</head>
<h1>User Login</h1>
{% if form.errors %}
    <p>Your username and password didn't match.
        Please try again.</p>
{% endif %}
<form method="post" action=".">
    <p><label for="id_username">Username:</label>
        {{ form.username }}</p>
    <p><label for="id_password">Password:</label>
        {{ form.password }}</p>
    <input type="hidden" name="next" value="/" />
    <input type="submit" value="login" />
</form>
</body>
</html>

what am i missing?


Source: (StackOverflow)

matching query does not exist Error in Django

I have implemented a password recovery functionality in django. With my method the new password will be sent to his email id entered. And its working fine when i give the correct email (e-mail id which exists in the database). But when i give an email id which is not in the database, it gives me this error 'DoesNotExist at /forgotPassword/

UniversityDetails matching query does not exist.'. Can somebody help to solve this. Will paste my code here. Can somebody help me to solve this problem.

forgotPassword.html()

def forgotPassword(request):
    if request.POST:
        email=request.POST.get("email")
        user = UniversityDetails.objects.get(email=email)
        if(not user):
            print "No user"
            return render_to_response("forgotPassword.html")
        else:
            newPassword = user.password
            send_mail('Password Recovery', 'The password for your site is '+ newPassword, 'rv_nair@gmail.com',
    ['rv_ks@gmail.com'], fail_silently=False)   
            return render_to_response("passwordRecovery.html")
    return render_to_response('forgotPassword.html')

html

<form name="forgotPassword" method="POST" id="myFormid" action="http://10.1.0.90:8080/forgotPassword/">
<div style="float:center;width:100%;color:#0000A0">
 Enter your E-mail ID</label><br/> <input type="text" name="email" size="25" /> 
 <input type="submit" value="Submit" />
 </div> 

</form >

Source: (StackOverflow)

Union and Intersect in Django

class Tag(models.Model):
  name = models.CharField(maxlength=100)

class Blog(models.Model):
  name = models.CharField(maxlength=100)
  tags =  models.ManyToManyField(Tag)

Simple models just to ask my question.

I wonder how can i query blogs using tags in two different ways.

  • Blog entries that are tagged with "tag1" or "tag2": Blog.objects.filter(tags_in=[1,2]).distinct()
  • Blog objects that are tagged with "tag1" and "tag2" : ?
  • Blog objects that are tagged with exactly "tag1" and "tag2" and nothing else : ??


Tag and Blog is just used for an example.


Source: (StackOverflow)

Django request to find previous referrer

I am passing the request to the template page.In django template how to pass the last page from which the new page was initialised.Instead of history.go(-1) i need to use this

 {{request.http referer}} ??

 <input type="button" value="Back" /> //onlcick how to call the referrer 

Source: (StackOverflow)

Class Based Views VS Function Based Views

I always use FBVs (Function Based Views) when creating a django app because it's very easy to handle. But most developers said that it's better to use CBVs (Class Based Views) and use only FBVs if it is complicated views that would be a pain to implement with CBVs.

Why? What are the advantages of using CBVs?


Source: (StackOverflow)