Answer the question
In order to leave comments, you need to log in
How to create an author field referencing a user in Django?
Guys, tell me how to create an author field that refers to a user. I did this:
from django.db import models
from django.contrib.auth.models import User
class Recipe(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=200)
timestamp = models.DateTimeField(auto_now=True)
text = models.TextField()
def __str__(self):
return self.title
ValueError: Lookup failed for model referenced by field recipe.Recipe.author: auth.User
def register(request):
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
if request.POST:
newuser_form = UserCreationForm(request.POST)
if newuser_form.is_valid():
newuser_form.save()
newuser = auth.authenticate(username=newuser_form.cleaned_data['username'], password=newuser_form.cleaned_data['password2'])
auth.login(request, newuser)
return redirect('/')
else:
args['form'] = newuser_form
return render_to_response('register.html', args)
Answer the question
In order to leave comments, you need to log in
It is better to refer to the User model like this:
from django.db import models
from django.conf import settings
class Recipe(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question