I’m trying to link a “normal” model field with an admin model field, for example I have a table “Post” and I want to add the admin username as a ForeignKey to the field “Author” of the table Post.
I mean :
class Post(models.Model): title = models.CharField(max_length=50) body = RichTextField(blank=True, null=True) date = models.DateTimeField('date_posted') username = models.ForeignKey(admin.username, on_delete=models.CASCADE)
Where admin.username refers the username of auth_user
admin model
Thanks for your help
Advertisement
Answer
As the referencing the user model section of the documentation says, you can make use of settings.AUTH_USER_MODEL
to obtain a reference to the user model that is used. You can use the to_field=…
[Django-doc] to specify to what field of the model it should refer, so:
from django.conf import settings class Post(models.Model): title = models.CharField(max_length=50) body = RichTextField(blank=True, null=True) date = models.DateTimeField('date_posted') author = models.ForeignKey( settings.AUTH_USER_MODEL, to_field='username' on_delete=models.CASCADE, editable=False )
By specifying editable=False
[Django-doc] it will not automatically show up in ModelForm
s.
In views, you can then set the logged in user as author by specifing the author attribute. For example:
from django.contrib.auth.decorators import login_required from django.shortcuts import redirect @login_required def some_view(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.instance.author = request.user form.save() return redirect('name-of-some-view') else: form = PostForm() return render(request, 'some_template.html', {'form': form})
Note: A
ForeignKey
does not store the string representation (or name) of the referenced object in the column, it stores the primary key of the record it references in a column with an_id
suffix to aForeignKey
field. ThereforeForeignKey
s usually do not end with a_name
suffix. You might want to consider renaming thefield tousername
author
.