FAQ Database Discussion Community


Django Model field calculated from other fields

python,django,django-models,django-admin
There are quite a few other questions here around this but none of them have helped. I would like a yield field to be calculated by yield = starts / finishes fields. I'd like to graph it using Highcharts. However when I add an object via Admin portal - it's...

get Foreign Key field name by which inline form is related

django,django-admin
In django admin I have a ModelForm and an inline form. I need the name of the foreign key field in save_formset method by which model of inline form is related to model of main (parent) form. class Author(models.Model): name=models.CharField(max_length=30) class Article(models.Model): writer=models.ForeignKey(Author) I need the field name ('writer' in...

How refresh django admin form when a value change in the browser?

ajax,django,python-3.x,django-admin
I have a Choice Field that when changed to another value it must change other fields in the form. So I need to refresh the form, or update in place the fields with a ajax call. Is this possible with the admin forms?...

Django-admin-bootstapped and summernote in admin.py

twitter-bootstrap,django-admin,summernote
I've just installed django-summernote and wish to add it on one of my admin page. I've followed the installation guide but their is no summernote display. I didn't found anything related to this. Here is my code : In admin.py (event_app): class StaticEventAdmin(SummernoteModelAdmin): fieldsets = ( (_('Event informations'), { 'fields':...

Django Admin change_list forcing search_form to reject given seach keywords

django,database,django-templates,django-admin
Problem: I'd like to enforce the change_list_view when opening the page with "?q=" (that is with no value or whitespace) and simply load the page by not executing queries at all. Possible ways: My question is how can I do that by overriding the queryset, get_queryset, or get_search_results methods ?...

How to detect when admin modifies User in Django

python,django,django-admin
I use Django's User models for both admins and normal users. Sometimes admins need to do manual modifications to user accounts, for example change e-mail or disable some account. These modifications are done from the basic admin panel that comes with Django. The question is, how can I detect these...

How can I find the highest value in a django admin queryset?

python,django,django-admin
I would like to find out what the highest value in a specific field is within a queryset, how can I go about this? I have a list of people who are in certain groups and i want to find out basically how many groups are there, I figured running...

Django restrict input in the admin

django,django-admin
I'm wondering how can I retrict the input of a field in the admin to only numbers and a max of 10 digits. The "max of 10 digits" part is confusing. The model field is this one: id_student = models.PositiveIntegerField(primary_key=True) How can I make sure that in the admin it...

ImageKit does not show thumbnail on Django Admin

django,nginx,django-admin,django-imagekit,imagekit
I have deployed an ubuntu server running Django. For image thumbnailing am using PILLOW and ImageKit. When I try to save an entry the main ImageFile is saved and the thumbnail is created aswell but once I save I get a server error 500. Once I reload the same page...

Link in django admin to foreign key object

django,django-admin,foreign-key-relationship
I have a model A with a ForeignKey to a model B. In Django admin, how can I add a link in the admin page of model A next to the ForeignKey field which open the admin page of the model B ?

Django Grappelli style is missing [Digital Ocean Setup]

python,django,django-admin,django-grappelli
I deployed a digital ocean droplet with Django admin installed. When I installed Django Grappelli and tried to load the admin the css and js files from Django-grappelli are missing which result on a page showing Plain HTML. When I inspect element all the necessary grappelli files are missing with...

How to filter by field of field (multi level relationship) in django admin?

python,django,django-models,django-admin
With models design like this: class School(models.Model): name = models.CharField(max_length=50) class Grade(models.Model): name = models.CharField(max_length=10) school = models.ForeignKey(School) class Student(models.Model): name = models.CharField(max_length=100) grade = models.ForeignKey(Grade) Since Student object doens't have direct relation with School object, How can I filter django-admin to only display students from selected school?...

How to filter objects for django admin panel?

django,django-admin
I am trying to integrate this simple django forum to an existing project. In admin.py I have class TopicAdmin(admin.ModelAdmin): list_display = ["title", "forum", "creator", "created"] list_filter = ["forum"] ... The problem is that since there are +100K users, when I try to add a topic from admin panel, browser just...

Django admin filter urls for not-equals

django,django-admin,django-modeltranslation
I've created a custom FieldListFilter for my site's admin for whether modeltranslation translations are available for a field. It creates a filter that currently looks like this on the sidebar: The "Lacks English" option adds vt_title_en__exact= to the query string. I would like to also implement a "Has English" which...

Customize change_list.html in django admin

python,django,django-admin
change_list.html has Action part where a user selects an action and applies it on the selected items(queryset). What I am trying to do is the following: 1. Add an additional <select> box near Action select box 2. Add an additional action which will use the value of the added select...

Django-admin list_editable enable/disable on the fly (edit/view mode check)

django,django-admin,django-modeladmin
I want to change edit/view mode of the page by button (or something like it). Edit mode is equal to list_editable specified in EntityModelAdmin body. View mode is equal to empty list_editable. @admin.register(models.EntityModel) class EntityModelAdmin(admin.ModelAdmin): list_display = ('name', 'barcode', 'short_code', ) list_editable = ('barcode', 'short_code', ) How to achieve this?...

django admin filter data after selection

django,django-forms,django-admin
In the admin, would it be possible to filter selection from a live input in a field: class ReadtToday(models.Model): author = models.ForeignKey(Authors) # field 1) book = models.OneToOneField(Books, related_name='bookofday') # field 2) Now in the admin for 1) and 2) got a list of all of them, how I should...

How can I automatically create list_filters for all my models in a django admin page?

python,django,django-admin,django-admin-filters
I have a Django site, using admin to manage the models. Currently, I am using from django.db.models.base import ModelBase for name, var in databuild_models.__dict__.items(): if type(var) is ModelBase: admin.site.register(var) To register all the models in the module with the admin module. However, I want to automatically add list_filters for every...

How to create objects inline for many to many relationships in Django?

python,django,django-models,django-admin,inline-formset
I have defined such a relation between questions and tags : (is this correct?) myproject/myapp/models.py : from django.db import models from django.contrib.auth.models import User from vote.managers import VotableManager from django.utils import timezone from datetime import datetime, timedelta class Tag(models.Model): text = models.CharField(max_length = 20) user = models.ForeignKey(User) class Question(models.Model): text...

join two tables using another relation table in Django

django,django-models,django-admin
I am having a problem with list_display in admin panel. class Categories(models.Model): cat_id = models.IntegerField(primary_key=True) cat_name = models.CharField(_('category name'), max_length=50) def __unicode__(self): return self.cat_name class Stories(models.Model): story_id = models.IntegerField(primary_key=True) story_title = models.CharField(max_length=500) story_desc = models.TextField() cover_image = models.CharField(max_length=500) date_of_creation = models.DateTimeField(auto_now_add=True) date_of_publish =...

Django admin with inlines, 1 model with 2 foreigns keys to 2 different models

django,django-models,foreign-keys,django-admin
I have 3 models total. My main model has 2 foreign keys to 2 different models. So the relationships are setup as a many-to-one. When I try to customize the admin, I cannot get it to simply allow me to edit the main character model and have the 2 inlines...

django-admin-bootstrapped messing with DateField, TimeField and PointField

javascript,python,twitter-bootstrap,django-admin,postgis
I've just added django-admin-bootstrapped to my project. Almost everything is fine. Actually there are two little bug whitch i'm wondering how to resolve. The first one is about DateField and TimeField : There is no date/time picker when i'm under django-admin-bootstrapped. When i check the source code, there is no...

Django DateTimeField show Date and Time input in the same line in admin

django,django-admin
Suppose I have a model with DateTimeField. And for DateTimeField, currently admin input is: Is it possible to customize it to Thanks for suggestion....

Replace ArrayField for several fields from other models in django-admin

django,django-models,django-forms,django-admin
I want to store model fields as array of foreign keys to other atomic-Models. It makes model more flexible: I can add/remove/inherit(if it's tree node) any of predefined properties without programming. Let's start with atomic-Models. It contain some classified properties. class Liquid(models.Model): volume = models.DecimalField(max_digits=12, decimal_places=6) class Granular(models.Model): weight =...

Limit inlines to edit mode in Django's ModelAdmin

django,django-admin
How can you limit Django's ModelAdmin inlines to edit mode. This is what I tried but it does not work: class PageAdmin(admin.ModelAdmin): form = PageModelForm def __init__(self, *args, **kwargs): super(PageAdmin, self).__init__(*args, **kwargs) if self.instance.pk: self.inlines = (FileInLine, ) In other word, I would like to access the instance in the...

Django admin filters on remote field via get_list_filter

django,django-models,django-admin
I have 3 models, linked by FKs in a chain like this: class Customer(models.Model): name = models.CharField(max_length=100) class Order(models.Model): name = models.CharField(max_length=100) customer = models.ForeignKey( 'customer.Customer', on_delete=models.PROTECT) class Task(models.Model): name = models.CharField(max_length=100) order = models.ForeignKey( 'order.Order', on_delete=models.PROTECT) Now, if within my TaskAdmin, I use: list_filter = ('order__customer', ) everything works...

Display a custom link in Django Admin edit item view?

django,django-admin
Here's a piece of Django admin interface's instance edition form: How should I change the underlying admin.ModelAdmin instance to make it contain an URL, like this? ...

create_user() takes at least 3 arguments (2 given) Django Social Auth use Costom User Model

django,django-models,django-admin,django-authentication,django-custom-user
i want to make login social auth and i use userprofile to login, but i getting error. This is error: Exception Type: TypeError at /complete/facebook/ Exception Value: create_user() takes at least 3 arguments (2 given) this is my admin.py code class CustomUserCreationForm(UserCreationForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password Confirmation',...

Does Django implement user permissions in databases with models?

python,django,orm,django-admin
In a typical database, admin can assign users and can create tables which can be accessed by only a particular set of users or groups. One can also create queries that can be made by certain users in a database like MySQL. Does Django provide any such functionality or is...

Creating Custom Actions for Admin Panel sets displayed values to (None)

django,django-models,django-admin
I am working on creating some custom actions to perform on my data from the django admin panel. I have defined the actions in models.py like so: EX_MODERATION_CHOICES = ( ('c', 'Check'), ('d', 'Display'), ('p', 'Pending'), ) and added the following to the appropriate model field: class Experience(models.Model): ... ex_moderationstatus...

How do you load a custom field in django

python,django,django-models,django-forms,django-admin
note : This is closely related to the answer in this question : django admin - add custom form fields that are not part of the model In Django it is possible to create custom ModelForms that have "rouge" fields that don't pertain to a specific database field in any...

Using the tables defined in the same models.py for list_display and populating the manyToMany fields of that table in admin forms

django,django-models,django-forms,django-admin,manytomanyfield
I am using Django 1.7, python 3.4 one of my models contains one class named Enterprise along with five other classes(Type, Products, etc.) each of which have a ManyToMany relation with Enterprise. class Enterprise(models.Model): enterprise = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) is_active = models.BooleanField(default=True) types = models.ManyToManyField(Type) products = models.ManyToManyField(Product)...

Django admin.py readonly_fields not working

python,django,django-admin
I need to show on Django administration the date the object was created, but date field should be disabled of modification. here is my model on Models.py from django.db import models from django.utils import timezone class MyModel(models.Model): name = models.CharField(max_length=200) date_of_creation = models.DateField(default=timezone.now) here is my admin.py from django.contrib import...

Django admin site : Help needed

python,django,django-admin
I was trying to customize the djando admin.py.I wanted to register a model Contribution in a class ContributionAdmin.In the admin interface,I needed to print a field application_number number from another model Subscriber.There is a Foreign key relationship with the models.How to do this? admin.py class ContributionAdmin(admin.ModelAdmin): list_display = ('id','nlcc','subscriber','date','receipt_number','amount', 'status')...

Could not map model object to admin

django,django-models,django-admin
I am trying to add model objects to admin panel but I a'm getting "TypeError: 'DeclarativeFieldsMetaclass' object is not iterable" Here's models.py from django.db import models from django import forms from django.forms.widgets import * from django.core.mail import send_mail, BadHeaderError class ContactForm(forms.Form): email = forms.EmailField(required=True) name = forms.CharField(required=True) topic = forms.CharField()...

Auto increament the invoice number in django backend for new invoice

python,django,django-admin,django-admin-filters,django-admin-tools
I want to auto increament the invoice number which is 3 digits char and 4 digits number. class Invoice: invoice_no = models.CharField(max_length=500, null=True, blank=True, validators=[RegexValidator(regex='^[a-zA-Z0-9]*$',message='Invoice must be Alphanumeric',code='invalid_invoice number'),]) I register this model in backend. But now when i click on create invoice in admin the invoice should be auto...

Adding custom fields to Django admin

python,django,django-admin
I have defined my model with various fields. Some of these are custom fields, which I am using to validate credit card data, using the fields.py file of my app. Source is here. class Transaction(models.Model): card_name = models.CharField() card_number = CreditCardField(required=True) security_code = VerificationValueField(required=True) expiry_date = ExpiryDateField(required=True) I have defined...

Django very large reverse ForeignKey query

python,django,sqlite,django-admin,django-admin-filters
I am using Django admin to filter objects on their reverse ForeignKey objects field value. The App has a ForeignKey to Contact and I am trying to filter Contacts by Apps category in Django admin. The problem is that the query is very large and I am getting a timeout...

Django admin: add widget link broken

python,django-admin
Not sure how I did this and have searched everywhere for a solution, but can not find one. I have managed to either install incorrectly or break my installation of a default Django 1.3.1 admin project so that the add widget is rendered with a broken link. The above link...

Proper way to handle custom submit button at django custom model admin add page

python,django,django-admin
I want to add an extra button at submit_line.html that does exactly the same thing as submit but it sets certain field to something else while sending post request to server. Say I have a blog as model, I want to add "save as draft" as button. My submit_line.html looks...

In Django-admin, how to add filter or search for foreign key select box?

python,django,django-models,django-forms,django-admin
I got a foreign key model with about 100,000 date. It's too difficult to select the wanted data. So I'm wondering if there is a humanized way to add foreign key in django admin. I have tried the raw_id_fields, it's useless. this don't work....

How can I count the number of instances per a queryset? Django

python,django,django-admin
I'm writing an action to set one field equal to the number of instances attached to it via a foreign key (see below) Models.py class competition(models): competition_name = models.CharField(max_length = 50) class people(models): competition = models.ForeignKey(competition) fullname = models.CharField(max_length = 100) Admin.py def people_in_competition: for X in queryset: X.number_of_people =...

Create a dynamic admin site

python,django,django-models,django-admin,exclude
I want to create a dynamic admin site, that based on if the field is blank or not will show that field. So I have a model that has a set number of fields, but for each individual entry will not contain all of the fields in my model and...

Django admin custom CSV report

django,csv,django-admin,django-admin-actions
I have a django project with 3 models. The user, the project (in which he works on) and the Change (which logs start and finish working time as well as the project and user). I want to export a custom CSV report. Ex: total working hours of users per project,...

Adding context variable into change_view not possible because extra_context not a dictionary

django,django-admin,django-1.7
I would like to add a field on the ModelAdmin.change_view() to filter my inline objects. Based on this solution I tried to inject extra_context into it: class ProcessAdmin(admin.ModelAdmin): inlines = [StepInline,] exclude = ('steps',) prepopulated_fields = {'name_slug': ('name',)} def change_view(self, request, extra_context=None): print(extra_context) extra = extra_context or {} extra['filter_form'] =...

How to show subclass model in Django-admin inline form?

python,django,django-models,django-admin
I got some models in models.py like this: class QuestionPackage(models.Model): """Question Package""" class Question(models.Model): question_package = models.ManyToManyField(QuestionPackage, blank=True) name = models.CharField(max_length=128) answer = models.TextField() class Reading(Question): """Reading Question""" class Writing(Question): """Writing Question""" (There are some differences between reading and writing ,but I omit that.) and in admin.py: class ReadingInline(admin.TabularInline): model...

Admin view give a Value Error: Cannot assign “'Intelligence'”: “CharacterAttributeLink.attribute” must be a “Attribute” instance

django,django-forms,django-admin
My admin page currently give me this: ValueError at /admin/characters/mage/add/ Cannot assign "'Intelligence'": "CharacterAttributeLink.attribute" must be a "Attribute" instance. And looking at my models.py: class Skill(models.Model): name = models.CharField(max_length=50, choices=SKILL_CHOICES) class Attribute(models.Model): name = models.CharField(max_length=50, choices=ATTRIBUTE_CHOICES) class SkillLink(models.Model): skill = models.ForeignKey('Skill', choices=SKILL_CHOICES) class Meta: abstract = True class AttributeLink(models.Model):...

django custom admin pages

django,django-admin
I'd like my model has multiple list view endpoints in django admin. For instance, I'd like to view all the blogs with more than 5 comments all the blogs that has been shared How do you make multiple endpoints in django admin? (basically multiple querysets for one model class) Sure...

django 1.7 admin: 'ModelMultipleChoiceField' object has no attribute 'limit_choices_to'

python,django,django-admin,django-users
I'm working on a legacy django 1.4 project, porting it to django 1.7. When accessing the django admin interface, in order to show user data I get the aforementioned error. Environment: Request Method: GET Request URL: http://localhost:8000/admin/auth/user/1/ Django Version: 1.7.4 Python Version: 2.7.8 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',...

Django/jQuery Cascading Select Boxes in Admin

javascript,jquery,ajax,django,django-admin
I have a Contract class where contract_mod allows to extend a contract from a previous one. contract_mod should only show contracts related with the person that we selected previously. The Contract class returns the field person. As I've never work with AJAX/jQuery I don't know where to start. So, my...

Django administration panel filter list

django,django-forms,django-admin,django-filter
I have my django model: Post Any Post has an author (User|Admin) I would to add post's administration in my Django administration panel but I would to show in Posts list ONLY posts with author=Admin. Is possible this?...

Django::OperationalError at /admin/login/ unable to open database file

django,django-admin,django-permissions,django-wsgi
I know there's already a same question, i too tried the solutions given their but it dint work for me hence i am writing my own question. Hii all, i am deploying django server using apache2 server and when i tried my host Ip address it works fine as it...

Problems extend change_form.html in django admin

django,templates,django-admin,customization
I'm trying to extend the change_form.html template of one of my models to include some information on the page. I've read the django documentation in https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#overriding-vs-replacing-an-admin-template The problem is that is occurring: NoReverseMatch at /contas_pagar/pagamento/2/ Reverse for 'app_list' with arguments '()' and keyword arguments '{u'app_label': ''}' not found. 1 pattern(s)...

Custom Authentication for Admin in Django

django,django-admin
I'm writing a custom Django admin site for my vendors to log into. This is to be separate from the regular Django admin site. My question: How do I override the admin authentication to also look from users from a vendor's table?

Django: Grappelli custom dashboard

django,django-admin,django-grappelli
I'm having problems with the Dashboard of Grappelli because I cannot see any change in my admin interface. What I'm trying to do is to show my models in different boxes. This is my configuration: myproj ├── myproj │ ├──url.py │ ├──settings.py ├── manage.py ├── db_personal #myapp │ ├── admin.py...

django admin fails using TabularInline

python,django,django-admin
I built a simple django application and now have a really confusing error message. I think it's because of Tabularinline, but I use it properly according to this documentation. models.py from django.db import models class Person(models.Model): company = models.CharField(max_length=120) name = models.CharField(max_length=120) birthday = models.DateField(null=True, blank=True) def __unicode__(self): return self.name...

InlineModelAdmin not showing up on admin page

django,django-models,django-admin
I have from django.db import models from django.contrib import admin # Create your models here. class Author(models.Model): name = models.CharField(max_length=10) class Book(models.Model): author = models.ForeignKey(Author, null=True, blank=True) title = models.CharField(max_length=10) class BookInline(admin.TabularInline): model = Book class AuthorAdmin(admin.ModelAdmin): inlines = [ BookInline, ] registered on my admin page, however books are...

Cannot create super user use custom user model in django 1.8

python,django,django-models,django-admin,django-custom-user
i try to make custom user model and i want to make super user but i am getting error like this Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File...

django multiple foreignkeys to the same parent class

django,django-models,django-admin
I am quite new to Django and I am creating an app which stores unit conversion tables for an application on a mobile device. Each UnitCategory can have multiple Units, each of which have a multiplication factor to use to convert values between them. The current model could be simplified...

How to reactivate user django

python,django,django-models,django-admin
I'm currently having troubles in setting is_active field from False back to True in Django. I have a custom Account model which is inhereted from AbstractBaseUser and is managed by class AccountManager(BaseUserManager). By default, I override the is_active field to be False. However, when I try to reactivate the field...

Django Dynamic Admin Site

python,django,django-models,django-admin,exclude
I want to create a dynamic admin site, that based on if the field is blank or not will show that field. So I have a model that has a set number of fields, but for each individual entry will not contain all of the fields in my model and...

Saving OnetoOne field manually in django

django,django-models,django-forms,django-admin
I have following models: class Person(User): first_name = models.CharField(verbose_name=_('first name'), max_length=30) last_name = models.CharField(verbose_name=_('last name'), max_length=30) class Service(models.Model): person = models.ForeignKey(Person, related_name='services') price_from = models.DecimalField(_('price form'), max_digits=10, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))]) price_to = models.DecimalField(_('price to'), max_digits=10, decimal_places=2,...

Add link button between inline

django,django-admin
I want to add a button, that link to another place of the app, between an inline in the admin interface. I mean, after the main class and before the inline class....

In Django-admin, how to show foreignkey's foreignkey in the same page?

python,django,django-models,django-forms,django-admin
I got a Paper and its foreignkey ChoiceQuestion model, and its foreignkey Choices model. I'm wondering if django-admin show Choices in the change-form page of Paper. class Paper(models.Model): """pagers""" # ... class ChoiceQuestion(models.Model): paper = models.ForeignKey(Paper) name = models.CharField(max_length=256) class Choice(models.Model): choice_question = models.ForeignKey(ChoiceQuestion) text = models.CharField(max_length=256) normally we can...

Need to add view list anchor tag for another model in django admin

python,django,django-admin
I have a two models question and answers. I am now able to show both the models in django admin. But i need to show a link for View Answers in question listing page in django admin. And this link should only show the answers of related question. For example...

django admin navigation from model to model

python,django,django-models,django-admin
got 4 tables: main. got a foreign key to A. got a foreign key to B. got a foreign key to C. I've setup models and can see and edit them after registering in Admin, but all they go their own way. What should I do to access model 2....

admin registered staff user can't login django admin, form registered staff user can't

python,django,django-forms,django-admin,django-authentication
When I create a user via django admin panel, and mark it staff it can login django admin page as it should, but when I create user vie UserForm and mark it as staff it can not login. It says invalid username password for staff and so on. I suspect...

Django Admin - custom create user form

django,django-admin
On Django Admin, the default create user form form have 3 fields: username, password and confirm password. I need to customize the create user form. I want to add the firstname and lastname fields, and autofill the username field with firstname.lastname. How can I do this? Thank you....

Accessing extended User class fields

python,django,django-admin
I created my own UserProfile by extending the default User class provided by Django: class UserProfile(models.Model): user = models.OneToOneField(User) # extended fields here bio = models.TextField(max_length=1024, null=True, blank=True) I have within my users/admin.py: class UserProfileAdmin(admin.ModelAdmin): search_fields = ["user"] list_display = ('email', 'first_name', 'last_name') admin.site.unregister(User) admin.site.register(User, UserProfileAdmin) # admin.site.register(UserProfile, UserProfileAdmin) I...

Keep User and Group in same section in Django admin panel

python,django,django-admin
I have made my own User model in Django 1.8 with from django.contrib.auth.models import AbstractUser, Group, Permission class MyUser(AbstractUser): pass But it does not figure in admin any longer. I have tried adding it to the admin page with from django.contrib.auth import get_user_model, models as auth_models from django.contrib.auth.admin import UserAdmin...

Override django admin landing page and pass variables to template

python,django,django-admin
I am new to use python and django. I want to override django admin landing page. So i am able to do this with creating template base_site.html and index.html in templates/admin/ folder. Now, i am able to display static content on /admin (django admin landing) page in index.html. I searched...

Django - Copying a model instance with 2 nested foreignkeys

python,django,django-admin
I am new to django and I have an Survey app in which the admin creates surveys which have questions, the questions have choices... I have added the save_as = True to my survey admin, however when I copy a survey, the questions are present in the copy, but not...

Django custom command error: unrecognized arguments

python,django,django-admin
I'm trying to create a command similar to createsuperuser which will take two arguments (username and password) Its working fine in django 1.7 but not in 1.8. (I'm also using python3.4) this is the code I wrote myapp/management/commands/createmysuperuser.py from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User class Command(BaseCommand): help...

unregister or register models conditionally in django admin

python,django,django-models,django-admin,django-admin-tools
Is it possible to conditionally register or unregister models in django admin? I want some models to appear in django admin, only if request satisfies some conditions. In my specific case I only need to check if the logged in user belongs to a particular group, and not show the...

Is it possible to extend Django admin with views not related to the database tables content?

python,django,django-admin
I work on a simple app with two basic models, Document and Word. The user uploads a document, and each word from the Document is extracted in a Word entry. The user should be able to view, add, edit and remove the documents and the words, so I thought it...

In django admin how do you access a function in a child model?

django,django-admin
I would like to access the thumbnail function of my Image model for preview in my tabularInline. In admin.py class BlogWidgetCarouselInline(admin.TabularInline): model = BlogWidgetCarousel extra = 0 readonly_fields = ('display_as', 'thumb', 'print_thumbs',) def display_as(self, instance): return instance.display() display_as.allow_tags = True def thumb(self, instance): return instance.Image.thumb() #Does not work def print_thumbs(self,...

Callable in model field not called upon adding new object through Django admin

django,django-models,django-admin
In https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.Field.default we read that the callable of a default field value is called, every time a new object is created. In my model I have: when_first_upload = models.DateTimeField(default=datetime.datetime.now()) When in the admin page I create a new object I always get the same datetime, as if the callable is...

Django : possible to override Admin sort action?

django,django-admin
I feel like this should be possible but I can't work out how. I have a model : class ModelClass (models.Model): name = models.CharField(max_length=100) email = models.EmailField() nickname = models.CharField(max_length=32) Within a Django Admin list screen is there any way to, when the user clicks on the top of the...

Django model with editable=False and filter that field in Admin

python,django,django-models,django-admin
I have this model: class Values(models.Model): ip_given = models.CharField(max_length=250, null=True, blank=True) ip_discovered = models.CharField(max_length=250, null=True, blank=True, editable=False) time = models.DateTimeField() poi = models.ForeignKey(POI, editable=False) sensor = models.ForeignKey(Sensor, editable=False) value = models.FloatField() created_at = models.DateTimeField(auto_now_add=True) The fields poi and sensor are editable=False because I set them automatically when creates the object....

How do I customize a slug field in Django?

python,django,django-models,django-admin
I've checked this but i need to concatenate contents in two fields okay, here's the question. I have two models, brand and product which looks something like this: Brand Model class Brand(models.Model): name = models.CharField(max_length=29) website = models.URLField() def __unicode__(self): return self.name Product Model class Product(models.Model): brand = models.ForeignKey(Brand) name...

Django: How to add a new button in admin/index.html for specific model

django,django-admin
I am overriding the admin/index.html content block. I have this inside: {% for model in app.models %} <tr class="model-{{ model.object_name|lower }}"> {% if model.admin_url %} <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th> {% else %} <th scope="row">{{ model.name }}</th> {% endif %} {% if model.add_url %} <td><a href="{{ model.add_url }}"...

How to display some objects of model B that has a ForeignKey pointing to model A,in Django admin?

python,django,django-admin,foreign-keys
Here's my models: class Person(models.Model): name = models.CharField(max_length = 10) class Book(models.Model): title = models.CharField(max_length = 10) auther = models.ForeignKey("Person") When I'm in a certain Person in django admin,I want to see all the Books written by this Person.How can this be achieved? Thanks in adv....

Django 1.4 SimpleListfilter sorts wrong

python,django,django-admin
I just implemented a simple listfilter for my Django App, to catch up only active entries like so: class ActiveAircraftsFilter(SimpleListFilter): title = _('aircraft') parameter_name = 'aircraft__ac_registration' def lookups(self, request, model_admin): qs = Aircraft.objects.filter(active=True) act = set([ac.ac_registration for ac in qs]) return [(ac, ac) for ac in act] def queryset(self, request,...

No such table as django_site

django,django-admin,django-settings
I am following from the docs of django-disqus to use it in my project. I have installed it in my settings, with other needed settings (API key and short name). But when I try to run these commands: >>> from django.contrib.sites.models import Site >>> Site.objects.all() I am getting an error:...

Can't run django-admin startproject mysite (ubuntu, django.core.exceptions.ImproperlyConfigured)

python,django,ubuntu,django-admin
When I try to run "django-admin startproject mysite" an error appears: django-admin startprojekt mysite Traceback (most recent call last): File "/usr/local/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv)...

Django-admin validation on Foreign object

python,django,python-2.7,django-admin
I have a Team model and Staff model (foreign to Team). Each Team Object can related to 1 - 10 Staff objects. Each staff object have a boolean field to indicate if he/she is team coordinator. How can I, in django admin page, ensure when admin users are entering team...

Use multiwidget for many to many field with readonly additional data

django,django-admin,many-to-many,django-multiwidget
I've the following models: class Exam(models.Model): participants = models.ManyToMany(settings.AUTH_USER_MODEL, through='Participation') class Participation(models.Model) user = models.OneToOneField(settings.AUTH_USER_MODEL) exam = models.ForeignKey('Exam') specific_number = models.PositiveIntegerField(editable=False) As you can see, the data I'm storing in intermediary model is readonly. It's generated automatically by the system when an instance is created. So I'd like to be...

Django FieldError at /admin/app/modelClass/

python,django,django-models,django-admin
I think I'm not repeating the question as I couldn't find an answer to my question. My Model class in models.py is as follows: class UserDetail(models.Model): user = models.OneToOneField(User) users = User.objects.all() Instance_ID = models.CharField(max_length=10, unique=True) Service_ID = models.CharField(max_length=15, unique=True) Reference_ID = models.CharField(max_length=15, unique=True) and the admin.py is as follows:...

In the Django admin changelist, how do I display a blank space instead of the default “(None)”?

django,null,django-admin,changelist
When a field is null in the database, Django inserts "(None)" to hold the place of the null when displaying a changelist. While descriptive, when there are lots of fields on a changelist, it makes everything very busy to look at, where as a blank field would be just as...

Importing UserAdmin raise AppRegistryNotReady(“Models aren't loaded yet.”)

python,django,django-models,django-admin
So I am trying to extend the user model with a OneToOneField but also modify the UserAdmin to show the correct information which is where I am facing my error cause any time I import from django.contrib.auth.admin import UserAdmin I receive this error: Traceback (most recent call last): File "C:\Program...

How to dynamically initialise FilteredSelectMultiple in django

jquery,django,django-forms,django-admin
I am trying to use the FilteredSelectMultiple widget on a custom non-admin site with a dynamic formset. I have gotten the widget to display properly for the existing entries in the formset by including: <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/admin/jsi18n"></script> However, when I add another entry in...

make django model field read only or disable in admin while saving the object first time

python,django,django-admin,django-admin-actions
I want to disable the few fields from model in django admin while saving initially. "<input type="text" id="disabledTextInput" class="form-control" placeholder="Disabled input">" like this. My model is: class Blogmodel(models.Model): tag = models.ForeignKey(Tag) headline = models.CharField(max_length=255) image=models.ImageField(upload_to=get_photo_storage_path, null=True, blank=False) body_text = models.TextField() pub_date = models.DateField() authors = models.ForeignKey(Author) n_comments = models.IntegerField() i...

Django. How to customize the raw_id_field to add many related object in one go?

django,django-admin
Actually, the raw_id_field option gives you a magnifying glass button next to the field which allows users to search for and select a value. You are obliged to select only one value at time. There is no way to select more than one values before adding. Is there any way...

Django pass TemplateView to ModelAdmin.add_view

python,django,angularjs,django-admin
Base on Django Admin site docs... I can override ModelAdmin.add_view to inject one custom view. My need is to inject a TemplateView to override one model change/add admin page. This custom view will contains an AngularJS app to manage, inside admin, one complex model of my application. admin.py class ContractAdmin(admin.ModelAdmin):...

Search Django Objects order_by(child_model_field)

django,django-models,django-admin,django-views
I have two models in my Django application. The first one is Journey and Second is Schedule. The Schedule models has a foreign key of Journey model. the schema of these models is as follow. class Journey(models.Model): pass class Schedule(models.Model): journey=models.ForeignKey(Journey) day=models.CharField(max_lenth=3, choices=days) start_time=models.TimeField() def __unicode__(self): return self.day What I...

Django Admin stylesheets won't load on production server

django,nginx,static,django-templates,django-admin
Django's stylesheets for it's built-in Admin site aren't being loaded on my production server which runs Django 1.6. I can see that many other people have encountered this problem and I've tried all the solutions that have been provided to them but none work. My Django site runs on top...

What to use django user object or create a user model?

django,django-admin,django-users,user-object
I want to create a user for my website that can submit a request form but I'm wondering which is suitable choice : To use a user object that already created Create a user model from scratch Note: I will let the users to login in my website from the...

How to use ModelMultipleChoiceField in django-admin and django-form for SelectMultiple widget

django,django-forms,django-admin
I need to use SelectMultiple widget with ModelMultipleChoiceField in Django-admin. It's not selecting proper value in django-admin at the time of editing. Please share a working example if possible. Thanks in advance!!! In this issue I was not getting desired result and there was no error in my project, so...

Preferred way to make django-parler fields sortable in admin

django,sorting,django-admin
I'm using django-parler on several models. Usually, you apply parler to fields like title, name etc and of course you would want to be able to sort these in the Django admin. The closest I've come to do this is by overriding the queryset method on the ModelAdmin, but it...

Django adding url.py with Django-batchimport 404 error

python,django-admin
I have created a very basic Djangodb where I am trying to do a batch import of several thousand excel files that I have. In the process of researching the best way to database all of these files I found this: https://github.com/pstch/django-batchimport I have read through the installation documentations, and...