开发者

Django: Linking a class to another class with foreign key when created by form

I'll try to give as much info as I can without giving more than I need.

I have a class 'Book' which, among other fields, is linked to another class 'User', like so:

from users.models import User
class Book(models.Model):
    title = models.CharField(max_length=150)    
    owner = models.ForeignKey('users.User')

This 'Book' is created by a form, w开发者_高级运维hich is coded like so:

from django import forms
from books.models import Book
class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ["title"]

And this form is displayed with a template that looks like:

    <form method="post" action="">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" />
    </form>

which is called by the following view:

def create_book(request):
    if request.user is None:
        return redirect("/users/login/")
    if request.method == "POST":
        form = BookForm(request.POST)
        if form.is_valid():
            form.owner = request.user   # FFFFFUUUUUUU
            form.save()
            return redirect("/books/")
    else:
        form = BookForm()
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

When this form is submitted, it should put the new book into the database, but I get an error: IntegrityError at /books/create/ null value in column "owner_id" violates not-null constraint

I imagine I'm not setting the owner properly. In regards to the above, form.owner = request.user, the request.user bit is set up by middleware: from users.models import User

class UserMiddleware(object):
    def process_request(self, request):
        user_id = request.session.get("user_id")
        if user_id is not None:
            request.user = User.objects.get(pk=user_id)
        else:
            request.user = None

So it should be a valid user (I can verify I'm logged in by other functionality in my code). I'm very new to Python/Django and I'm betting that my way of setting the new book's owner is just not correct, but maybe something else is wrong. If more information is needed, please let me know, and I hope this isn't too much!

Thanks for the help.


You need to set the user on the book object that is created by saving the form, not on the form itself. The code should be:

    if form.is_valid():
        book = form.save(commit=False)
        book.owner = request.user
        book.save()

Doing form.save(commit=False) returns an unsaved book instance, which you can modify yourself before saving it to the database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜