K1m
K1m

Reputation: 69

Adding foreign key to form

I have this model:

class Post(models.Model):
    thread = models.ForeignKey(Thread)
    post_title = models.CharField(max_length=50, blank=True)
    # other attributes

And I have a view:

class ThreadView(CreateView):
    model = models.Post
    template_name = 'forum/thread.html'
    fields = ['post_title', 'author', 'post_text']

When I try to send the form I get IntegrityError: NOT NULL constraint failed: forum_post.thread_id. I think, it's because I foreign key remains empty, but I don't know how to add it automatically.

Upvotes: 0

Views: 99

Answers (3)

Jed Fox
Jed Fox

Reputation: 3025

Try adding this to your view:

def post(self, *args, **kwargs):
    self.t_id = kwargs["t_id"]
    return super(ThreadView, self).post(*args, **kwargs)

def form_valid(self, form):
    self.object = form.save(commit=False)
    self.object.thread = Thread.objects.get(pk=self.t_id)
    form.save_m2m()
    return super(ModelFormMixin, self).form_valid(form)

Upvotes: 0

chem1st
chem1st

Reputation: 1634

First, the name of the view you have is not quiet obvious, cause you are trying to create an instance of a Post not of a Thread. Won't it be better to rename it to PostCreateView?

Speaking about the error you get, you are right about foreign key - it is empty. After all, you do not set it anywhere. You should either send it in the form or assign it on validation. The second way is what you are looking for:

class ThreadView(CreateView):
    model = models.Post
    template_name = 'forum/thread.html'
    fields = ['post_title', 'author', 'post_text']

    def dispatch(self, *args, **kwargs):
        self.thread = get_object_or_404(Thread, pk=kwargs['thread_id'])
        return super(ThreadView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
            form.instance.thread = self.thread
            return super(ThreadView, self).form_valid(form)

Upvotes: 1

Alwerdani
Alwerdani

Reputation: 111

I think you must add ForeginKey Feild into Views Feilds

fields = ['thread', 'post_title', 'author', 'post_text']

and be sure there is a data in thread model

Upvotes: 0

Related Questions