Question - How to assign a value in the view field at_project? When editing the field should be filled automatically. We went to the project - created a task, the task should be attached to this project.

There are models

class Task(models.Model): name = models.CharField('Название', max_length=50, default='') period = models.DateTimeField('Срок', blank=True, null=True) responsible = models.ForeignKey(CustomUser, verbose_name='Ответственный', blank=True, related_name='task_responsible') at_project = models.ForeignKey(Project, verbose_name='Относится к', related_name='at_project') class Project(models.Model): name = models.CharField('Название проекта', max_length=100) create_date = models.DateField('Дата создания', blank=True, null=True) start_date = models.DateField('Дата начала проекта', blank=True, null=True) end_date = models.DateField('Дата окончания', blank=True, null=True) description = models.CharField('Описание', max_length=200, blank=True) income = models.IntegerField('Доход', blank=True, null=True) costs = models.IntegerField('Трудозатраты', blank=True, null=True) total = models.IntegerField('Итого', blank=True, null=True) responsible = models.ManyToManyField(CustomUser, verbose_name='Назначеные сотрудники', blank=True, related_name='project_responsible') tasks = models.ManyToManyField('Task', verbose_name='Задачи по проекту', blank=True, related_name='project_tasks') created_by = models.CharField('Кем создано', max_length=100, blank=True) 

And there is such a view:

 args['task'] = Task.objects.get(pk=task_id) args['form'] = EditTaskForm(request.POST, instance=args['task']) args['task_id'] = task_id args['project_id'] = project_id if request.POST: form = EditTaskForm(request.POST, instance=args['task']) if form.is_valid(): new_at_project = form.save(commit=False) new_at_project.at_project = Project.objects.get(pk=args['project_id']) new_at_project.save() form.save_m2m() return redirect('/project/{0}/task/{1}'.format(args['project_id'], args['task_id'])) else: args['error'] = form.errors args['form'] = form 

When you save the form is issued

 at_project Обязательное поле. 

Update: done so, and suspect wrong:

 class EditTaskForm(forms.ModelForm): class Meta: model = Task fields = ('name', 'period', 'responsible') exclude = ('at_project', ) def __init__(self): super(EditTaskForm, self).__init__() self.at_project = Project def save(self, **kwargs): task = super(EditTaskForm, self).save() task.at_project = self.project task.save() 

page gives out

 TypeError __init__() takes exactly 1 argument (2 given) 

    1 answer 1

    1. Overload the __init__ EditTaskForm method to accept the project .
    2. at_project add to exclude :
    3. Overload the save method to set the project instance passed to __init__ .

       class EditTaskForm(ModelForm): class Meta: model = Task exclude = ('at_project',) def save(*args, **kwargs): task = super(EditTaskForm, self).save(*args, **kwargs) task = self.project task.save() 

    PS it is not clear why you use dict args, instead of just local variables.

    • Can you tell me more about 2 and 3 points? Recently I just started learning jungle - Firik
    • @Firik added an example - dizballanze
    • Added example from above - Firik
    • hm, now tried to add a task. The at_project field is empty ( - Firik