B
B
blackbb2016-03-20 03:36:38
Django
blackbb, 2016-03-20 03:36:38

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)

There is a form:
class AddResponseForm(forms.ModelForm):
    class Meta:
        model = Response
        fields = ('body',)

Those. when filling out a response to a project by a user, it is necessary that the user and project fields are filled in secretly from the user, automatically, so to speak (the current user and project to which I write the response). I solved the problem with user
form.instance.user = self.request.user
, but I can't do it with project. Please help with advice.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
blackbb, 2016-03-20
@blackbb

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)

S
Sergey Gornostaev, 2016-03-20
@sergey-gornostaev

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()}

And then in views.py:
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 question

Ask a Question

731 491 924 answers to any question