Answer the question
In order to leave comments, you need to log in
How to automatically fill in a field in django when creating an object in a form?
There are models:
class Project(models.Model):
title = models.CharField(max_length=200, verbose_name=u'Название')
slug = models.SlugField(unique=True, verbose_name=u'URL')
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'Пользователь')
body = models.TextField(verbose_name=u'Описание проекта')
class Response(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
project = models.ForeignKey(Project)
body = models.TextField()
active = models.BooleanField(default=False)
class AddResponseForm(forms.ModelForm):
class Meta:
model = Response
fields = ('body',)
form.instance.user = self.request.user
Answer the question
In order to leave comments, you need to log in
The question is closed. Understood.
def form_valid(self, form):
form.instance.user = self.request.user
project = Project.objects.get(slug=self.kwargs['project_slug'])
form.instance.project = project
return super(ResponseCreate, self).form_valid(form)
First, it's worth making the project model field a hidden form field:
class AddResponseForm(forms.ModelForm):
class Meta:
model = Response
fields = ('body', 'project')
widgets = {'project': forms.HiddenInput()}
form = AddResponseForm(request.POST)
if form.is_valid():
response = form.save(commit=False)
response.user = request.user
response.save()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question