I have a model created in Django 1.5 as below:
class Number(models.Model):
phone_number = models.CharField("Phone Number", max_length=10, unique=True)
I set up Django admin as below:
from django.contrib import admin
from demo.models import Message, Number, Relationship, SmsLog
class NumberAdmin(admin.ModelAdmin):
search_fields = ['phone_number']
admin.site.register(Number, NumberAdmin)
I believe Django add "date_created" column to the database automatically (because I know it sorts the data entries by creation time in admin console). Is there a way to view those time/dates in admin console? The closest I have go to is Django tutorial and StackOverflow ,but I do not want to create another column on my own (pub_date in Django official tutorial's example) and add it if possible. Is there a way to do it and if so, could someone show me how to? Thank you!
Django does not automatically add a date_created column. If you want to track the creation date, you have to declare it in your model.
You may be getting the illusion that it does because if you do not specify a sort order in the model or in the admin class for the model, it will default to sorting by primary key, which will increase according to the order the model instances were created.
Related
I'm currently building a Django website where staff has control over users, and, within those powers, I'd like to add one where the staff members can add private comments on users so that they can be read by whoever has the power to do so.
So I started building the user models.py here what I did:
class user(models.Model):
name = models.CharField(max_length=30)
comments = models.TextField()
date = models.DateField(default=datetime.now())
def __str__(self):
return self.name
My question: how can I add a comment field every time a staff member wants to? Like, with the above code, I can only have one comment per user.
Everything is appreciated.
Thanks!
There are a few ways to do this.
1. ForeignKey
Make a separate model for the comments and have a ForeignKey to the User model. That way, multiple comments can be linked to the same user.
2. ArrayField
If you're using Postgres database, you can use the ArrayField.
Cons: Editing in the admin panel is not very user friendly.
3. JSONField
You can also keep multiple comments in a JSON array.
Cons: Editing in the admin panel is not user friendly.
P.S.: If you decide to use either ArrayField or JSONField, check out an app I've made called django-jsonform. This will make editing JSON and ArrayField nice and user-friendly.
I've extended the standard User with a Profile model using a one-to-one relationship:
class Profile(models.Model):
user = models.OneToOneField(User, primary_key=True, editable=False)
# Additional user information fields
This is in an app called account_custom. The issue is that in the admin site, I would like this model to show up along with User under "Authentication and Authorization".
I was able to make this show up in the right place in the admin by setting Meta.app_label:
class Profile(models.Model):
class Meta:
app_label = 'auth'
db_table = 'account_custom_profile'
I set Meta.db_table so this uses the existing database table, and everything seems to function properly.
The problem is that Django wants to generate migrations for this, one in account_custom to delete the table and one in auth to create it again. I'm guessing this would either fail or wipe out the data depending on the order the migrations are run, but the deeper problem is that it's trying to create a migration in auth which isn't part of my code base.
Is there a way around this, or is there some better way to control where a ModelAdmin shows up in the admin site?
Is there a way to save my user registration in another table from the database?
I don't want to mix AdminUsers with CommonUsers (All the tutorials I've seen, they save the registration inside auth_user)
The reasons:
CommonUsers have different columns and informations
CommonUsers can upload content
AdminUsers verify the content uploaded by the CommonUsers and make sure there is nothing inappropriate
What do I need to use? models? modelform? forms?
The best solution for you is to subclass the User model and add the extra columns you need for your CommonUsers. Your code will probably end up looking something like this:
models.py
from django.contrib.auth import models
from django.db.models import *
class CommonUser(models.User):
custom_field1 = CharField(max_length=255, null=True)
custom_field2 = CharField(max_length=255, null=True)
Link to docs
My model looks like this:
class Asset(models.Model):
serial_number = models.CharField(max_length=100, unique=True)
asset_tag = models.CharField(max_length=100, unique=True)
class WorkOrder(models.Model):
asset = models.ForeignKey(Asset)
Essentially, a work order is submitted and then an admin assigns an asset to the work order. The asset_tag field is a barcode that we can scan in. When editing the work order in the Django admin, by default the asset field is displayed as a <select> widget. What we want to be able to do is have a search field so that we can scan the asset tag and then search for the right asset in the DB to associate with the work order.
I know you can customize the Django admin foreign key to a hard coded query, but I can't figure out how to get it so it does a search based on a field on the admin page.
Did you take a look at raw_id_fields?
It should be pretty to close to what you're after.
If you are using Django >= 2.0, you can take advantage of a feature called autocomplete_fields. You must define search_fields on the related object’s ModelAdmin because the autocomplete search uses it.
Since you have a ForeignKey relationship to Asset in WorkOrder, in the admin.py of your app add the following:
from django.contrib import admin
#admin.register(Asset)
class AssetAdmin(admin.ModelAdmin):
search_fields = ["serial_number", "asset_tag"]
#admin.register(WorkOrder)
class WorkOrderAdmin(admin.ModelAdmin):
autocomplete_fields = ["asset"]
Add the fields you want to use for searching to search_fields, and add define autocomplete_fields as shown in the code above.
Now you can use the autocomplete_fields from django 2.0.
It's quite neat.
edit: I wasn't clear before, I am saving my object in the django admin panel, not in a view. Even when I save the object with no many-to-many relationships I still get the error.
I have a model called TogglDetails that has a ForeignKey relationship with the standard django User model and a MayToManyField relationship with a model named Tag. I have registered my models with django admin but when I try to save a TogglDetails instance I get the error in the title.
Here are my models:
class Tag(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class TogglDetails(models.Model):
token = models.CharField(max_length=100)
user = models.ForeignKey(User)
tags = models.ManyToManyField(Tag, blank=True, null=True)
def __unicode__(self):
return self.user.username
class Meta:
verbose_name_plural = "toggl details"
As far as I can tell, there should be no issues with my models and django admin should just save the instance without any issues. Is there something obvious that I have missed?
I am using Django 1.3
The answer to my question was this: Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db.
As stated by other users:
Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db
In addition:
This is most likely caused by a backwards incompatible change that renders some primary key types in custom models beyond reach for Django 1.3. See Django trac tickets https://code.djangoproject.com/ticket/13295 and http://code.djangoproject.com/ticket/15682 for more information.
I solved the problem by running the follow commands for the affected tables/sequences.
Specifically running the command:
manage.py dbshell
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
change tablename_colname_seq and tablename.colname
Don't let us guess and add the Error message to your question, this gives most information about where it fails.
Have you imported the User model?
from django.contrib.auth.models import User
I've had this problem as well and the only thing I could do was make the M2M fields blank and not set them until I hit Save and Continue Editing.
I think this just may be a framework wart, as you will notice the User section of the Admin site also has a very strict "You can only edit these fields until you save the model".
So my recommendation is to adopt that scheme, and hide the M2M form field until the model has a Primary Key.
I tried Django 1.3 using CPython, with different database setups. I copy-pasted the models from the question, and did some changes: first I added
from django.contrib.auth.models import User
at the top of the file and I put the reference to Tag between quotes. That shouldn't make any difference. Further, I created the following admin.py:
from django.contrib import admin
import models
admin.site.register(models.Tag)
admin.site.register(models.TogglDetails)
For Sqlite3, the problem described doesn't occur, neither for MySQL. So I tried PostgreSQL, with the postgresql_psycopg2 back end. Same thing: I can't reproduce the error.
So as far as I can figure, there's nothing wrong with the code in the question. The problem must be elsewhere.