Amend the data introduced through the form



  • I have a model that makes staff information.

    class Employee(models.Model):
    name = models.CharField(max_length=50, verbose_name="ФИО")
    date_of_start = models.DateField(verbose_name="Дата оформления")
    position = models.ForeignKey("Position", on_delete=models.PROTECT, verbose_name="Должность")
    department = models.ForeignKey("Department", on_delete=models.PROTECT, verbose_name="Подразделение")
    

    def str(self):
    return self.name

    @property
    def days_worked(self):
    days_worked = datetime.now().date() - self.date_of_start
    return days_worked.days
    days_worked.fget.short_description = 'Сколько работает'

    And there's a voiché who, through the form, allows new staff to be loaded.

    class Employee_Add(LoginRequiredMixin, FormView):
    template_name = 'manager_employees/employee_add.html'
    form_class = EmployeeAddForm

    def post(self, request, *args, **kwargs):

    form = self.form_class(request.POST)
    if form.is_valid():
        messages.success(request, 'Сотрудник загружен успешно')
        Employee.objects.create(**form.cleaned_data)
        return redirect("base", )
    else:
        messages.success(request, 'Заполните форму корректно')
        form = EmployeeAddForm()
    return render(request, self.template_name, {'form': form})
    

    forms.py

    class EmployeeAddForm(forms.ModelForm):
    def init(self, *args, **kwargs):
    super().init(*args, **kwargs)
    self.fields['position'].empty_label = "Выберите должность"
    self.fields['department'].empty_label = "Выберите подразделение"

    class Meta:
    model = Employee
    fields = ["name", "date_of_start", "position", "department"]
    widgets = {
    "name": forms.TextInput(attrs={"class": "form-control"}),
    "date_of_start": SelectDateWidget(years=range(2000, 2022)),
    "position": forms.Select(attrs={"class": "form-control"}),
    "department": forms.Select(attrs={"class": "form-control"}),
    }

    def clean_title(self):
    title = self.cleaned_data["name"]
    if re.match(r'\d', title):
    raise ValidationError("Имя не должно начинаться с цифры")
    return title

    The front looks the following.
    Выглядит фронт следующим образом

    The question is: how do I realize that, when a staff member is called, a page with the possibility of altering his data. I'll be very grateful for your help.



  • form = self.form_class(request.POST, instance=obj)
    

    Instead of obj, write your object.

    I'd like to rewrite the wig through UpdateView.

    class Employee_Add(LoginRequiredMixin, UpdateView):
    model = Employee
    template_name = 'manager_employees/employee_add.html'
    form_class = EmployeeAddForm

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, instance=self.get_object())
        if form.is_valid():
            messages.success(request, 'Сотрудник загружен успешно')
            form.save()
            return redirect("base", )
        else:
            messages.success(request, 'Заполните форму корректно')
            form = EmployeeAddForm(instance=self.get_object())
        return render(request, self.template_name, {'form': form})
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2