Я использовал примеры из документации Django, но пока это не решает мою проблему: https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#models-and-request-user
Итак, в основном у меня есть эта модель:
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)
Обе попытки дают мне эту ошибку:
Cannot assign "1": "Post.group" must be a "Trip" instance.
Есть идеи, как передать это в БД?