Home python Change Manytomany object in Django

Change Manytomany object in Django




There is a Task model in which there is the essence of Sotry.

When creating a task, employees are specified, followed by this task. But there are cases when more employees need to add to the created task. This can be done by editing an existing task. Filling the appropriate form, substituting Instance = Task, I can add and remove employees. With this scenario, in my form a list of all employees is displayed.
Please tell me how to make it so that when editing a task, in the SELECTMULTIPLE field, not all employees were displayed, but only those that are not involved in the task?

* models.py *
Class Task (Models.Model):
  Sotry = Models.Manytomanyfield (Employee, verbose_name = 'employees', blank = true)
Class Employee (Models.Model):
  SUR_NAME = MODELS.CHARFIELD (max_length = 50, verbose_name = 'surname')
  Name = Models.charfield (max_length = 50, verbose_name = 'name')
  Middle_Name = Models.charfield (max_length = 50, verbose_name = 'Patronymic')
* Forms.py *
Class Addemptask (Forms.Modelform):
  Class Meta:
    Model = Task
    Fields = ('Sotry',)
    widgets = {
      'Sotry': Forms.SelectMultiple (attrs = {'class': 'Form-Control'}),
* Views.py *
Def Add_emptask (Request, PK):
  Task = Task.Objects.get (PK = PK)
  If Request.Method == "POST":
    Form = AddEmptask (Request.post, Instance = Task)
    If form.is_valid ():
       T = Form.Save (Commit = False)
       form.save_m2m ()
       T = Form.Save ()
      Return Redirect ('Task_URL', PK)
    form = AddEmpTask (instance = task)
  return render (request, 'rootApp / employees / add_emptask.html', { 'form': form})

Answer 1, Authority 100%

in the init method of the form can override queryset for the required fields

class AddEmpTask (forms.ModelForm):
  def __init __ (self, * args, ** kwargs):
    super () .__ init __ (* args, ** kwargs)
    self.fields [ "sotry"]. queryset = Employee.objects.exclude (pk__in = [employee.pk for employee in self.instance.sotry.all ()]

But if you want to show the new employees (those that are not tied to the problem), when you save you will need to add those who already have the problem, or a new set of officers will replace the old one. This can be done either in the method save , or in the method clean , adding self.cleaned_data [ "sotry"] of those employees that have been chosen earlier and current selection

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions