EzDevInfo.com

django-admin interview questions

Top django-admin frequently asked interview questions

Django drop all tables from database

How can I drop all tables from a database using manage.py and command line? Is there any way to do that executing manage.py with appropriate parameters so I can execute it from a .NET application?


Source: (StackOverflow)

Default value for field in Django model

Suppose I have a model:

class SomeModel(models.Model):
    id = models.AutoField(primary_key=True)
    a = models.CharField(max_length=10)
    b = models.CharField(max_length=7)

Currently I am using the default admin to create/edit objects of this type. How do I remove the field b from the admin so that each object cannot be created with a value, and rather will receive a default value of 0000000?


Source: (StackOverflow)

Advertisements

Django-Admin: CharField as TextArea

I have

class Cab(models.Model):
    name  = models.CharField( max_length=20 )
    descr = models.CharField( max_length=2000 )

class Cab_Admin(admin.ModelAdmin):
    ordering     = ('name',)
    list_display = ('name','descr', )
    # what to write here to make descr using TextArea?

admin.site.register( Cab, Cab_Admin )

how to assign TextArea widget to 'descr' field in admin interface?

upd:
In Admin interface only!

Good idea to use ModelForm.


Source: (StackOverflow)

Tying in to Django Admin's Model History

The Setup:

  • I'm working on a Django application which allows users to create an object in the database and then go back and edit it as much as they desire.
  • Django's admin site keeps a history of the changes made to objects through the admin site.

The Question:

  • How do I hook my application in to the admin site's change history so that I can see the history of changes users make to their "content"?

Source: (StackOverflow)

Django auto_now and auto_now_add

For Django 1.1.

I have this in my models.py:

class User(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

When updating a row I get:

[Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base.py:84: Warning: Column 'created' cannot be null
[Sun Nov 15 02:18:12 2009] [error]   return self.cursor.execute(query, args)

The relevant part of my database is:

  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,

Is this cause for concern?

Side question: in my admin tool, those two fields aren't showing up. Is that expected?


Source: (StackOverflow)

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).

With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?

class PersonAdmin(admin.ModelAdmin):
  list_display = ['book.author',]

Source: (StackOverflow)

Django Admin: Using a custom widget for only one model field

I have a DateTimeField field in my model. I wanted to display it as a checkbox widget in the Django admin site. To do this, I created a custom form widget. However, I do not know how to use my custom widget for only this one field.

The Django documentation explains how to use a custom widget for all fields of a certain type:

class StopAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.DateTimeField: {'widget': ApproveStopWidget }
    }

This is not granular enough though. I want to change it for only one field.


Source: (StackOverflow)

Using Django auth UserAdmin for a custom user model

From the Django.Contrib.Auth docs:

Extending Django’s default User If you’re entirely happy with Django’s User model and you just want to add some additional profile information, you can simply subclass django.contrib.auth.models.AbstractUser and add your custom profile fields. This class provides the full implementation of the default User as an abstract model.

Said and done. I created a new model like below:

class MyUser(AbstractUser):
  some_extra_data = models.CharField(max_length=100, blank=True)

This shows up in admin almost like Django's standard User. However, the most important difference in admin is that the password-(re)set field is not present, but a normal CharField is displayed instead. Do I really have to override stuff in the admin-config to get this to work? If so, how can I do that in somewhat DRY way (i.e. without copying stuff from the Django source... eww...)?


Source: (StackOverflow)

Django - Overriding the Model.create() method?

The Django docs only list examples for overriding save() and delete(). However, I'd like to define some extra processing for my models only when they are created. For anyone familiar with Rails, it would be the equivalent to creating a :before_create filter. Is this possible?


Source: (StackOverflow)

Django admin, hide a model

Hello At the root page of the admin site where registered models appear, I want to hide several models that are registered to the Django admin.

If I directly unregister those, I am not able to add new records as the add new symbol "+" dissapears.

How can this be done ?


Source: (StackOverflow)

Django admin and showing thumbnail images

I'm trying to show thumbnail images in Django admin, but I can only see the path to the images, but not the rendered images. I don't know what I'm doing wrong.

Server media URL:

from django.conf import settings
(r'^public/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),

Function model:

def image_img(self):
        if self.image:
            return u'<img src="%s" />' % self.image.url_125x125
        else:
            return '(Sin imagen)'
        image_img.short_description = 'Thumb'
        image_img.allow_tags = True

admin.py:

class ImagesAdmin(admin.ModelAdmin):

    list_display= ('image_img','product',)

And the result:

<img src="http://127.0.0.1:8000/public/product_images/6a00d8341c630a53ef0120a556b3b4970c.125x125.jpg" />

Source: (StackOverflow)

django admin make a field read-only when modifying obj but required when adding new obj

In admin I would like to disable a field when modifying object, but make it required when adding new object.

Whats the django way to go about this one?


Source: (StackOverflow)

How to override and extend basic Django admin templates?

How do I override an admin template (e.g. admin/index.html) while at the same time extending it (see https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template)?

First - I know that this question has been asked and answered before (see Django: Overriding AND extending an app template) but as the answer says it isn't directly applicable if you're using the app_directories template loader (which is most of the time).

My current workaround is to make copies and extend from them instead of extending directly from the admin templates. This works great but it's really confusing and adds extra work when the admin templates change.

It could think of some custom extend-tag for the templates but I don't want to reinvent the wheel if there already exists a solution.

On a side note: Does anybody know if this problem will be addressed by Django itself?


Source: (StackOverflow)

Overriding the save method in Django ModelForm

I'm having trouble overriding a ModelForm save method. This is the error I'm receiving:

Exception Type:     TypeError  
Exception Value:    save() got an unexpected keyword argument 'commit'

My intentions are to have a form submit many values for 3 fields, to then create an object for each combination of those fields, and to save each of those objects. Helpful nudge in the right direction would be ace.

File models.py

class CallResultType(models.Model):
    id = models.AutoField(db_column='icontact_result_code_type_id', primary_key=True)
    callResult = models.ForeignKey('CallResult', db_column='icontact_result_code_id')
    campaign = models.ForeignKey('Campaign', db_column='icampaign_id')
    callType = models.ForeignKey('CallType', db_column='icall_type_id')
    agent = models.BooleanField(db_column='bagent', default=True)
    teamLeader = models.BooleanField(db_column='bTeamLeader', default=True)
    active = models.BooleanField(db_column='bactive', default=True)

File forms.py

from django.forms import ModelForm, ModelMultipleChoiceField
from callresults.models import *

class CallResultTypeForm(ModelForm):
    callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all())
    campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all())
    callType = ModelMultipleChoiceField(queryset=CallType.objects.all())

    def save(self, force_insert=False, force_update=False):
        for cr in self.callResult:
            for c in self.campain:
                for ct in self.callType:
                    m = CallResultType(self) # this line is probably wrong
                    m.callResult = cr
                    m.campaign = c
                    m.calltype = ct
                    m.save()

    class Meta:
        model = CallResultType

File admin.py

class CallResultTypeAdmin(admin.ModelAdmin):
    form = CallResultTypeForm

Source: (StackOverflow)

Unique BooleanField value in Django?

Suppose my models.py is like so:

class Character(models.Model):
    name = models.CharField(max_length=255)
    is_the_chosen_one = models.BooleanField()

I want only one of my Character instances to have is_the_chosen_one == True and all others to have is_the_chosen_one == False . How can I best ensure this uniqueness constraint is respected?

Top marks to answers that take into account the importance of respecting the constraint at the database, model and (admin) form levels!


Source: (StackOverflow)