V
V
Vladislav2014-09-18 17:06:10
Django
Vladislav, 2014-09-18 17:06:10

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

But when I run the migration, it gives
ValueError: Lookup failed for model referenced by field recipe.Recipe.author: auth.User

I register like this:
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

2 answer(s)
A
Alexey, 2014-09-18
@MAKAPOH

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)

You can read more here . I don't know if this fixes your error, it might help.

A
alternativshik, 2014-09-18
@alternativshik

stackoverflow.com/questions/23523533/django-valueee...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question