Hiddenguy
Hiddenguy

Reputation: 537

Passing ForeginKey to CreateView from url

I've been using examples from Django documentations, but so far it is not solving my problem: https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#models-and-request-user

So basicly I have this model:

models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Trip, on_delete=models.CASCADE)

urls.py

path('trip/<int:pk>/discussion/', PostCreate.as_view(), name='trip-detail-discussion'),

views.py

# 1st attempt
class PostCreate(CreateView):
    model = Post
    template_name = 'tripplanner/postcreate.html'
    fields = ['title', 'content']
    success_url = '/'

    def form_valid(self, form, **kwargs):
        context = super(PostCreate, self).get_context_data(**kwargs)
        context['pk'] = self.kwargs['pk']
        form.instance.author = self.request.user
        form.instance.group = context.get('pk')
        # print(self.trip)
        print(form.instance.group)
        return super(PostCreate, self).form_valid(form)

# 2nd attempt
class PostCreate(CreateView):
    model = Post
    template_name = 'tripplanner/postcreate.html'
    fields = ['title', 'content']
    success_url = '/'

    def dispatch(self, request, *args, **kwargs):
        self.trip = get_object_or_404(Trip, pk=kwargs['pk'])
        return super(PostCreate, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.instance.group = self.trip.id
        print(form.instance.group)
        return super(PostCreate, self).form_valid(form)

Both attempts give me this error:

Cannot assign "1": "Post.group" must be a "Trip" instance.

Any ideas how to pass this to db?

Upvotes: 0

Views: 41

Answers (1)

Hari
Hari

Reputation: 1623

The group should be Type instance not an integer.

 form.instance.group = self.trip

Upvotes: 2

Related Questions