How can I capture first_name from a form?

How would I be able to get the first_name into the context.

class NewTeacherView(LoginRequiredMixin,CreateView):
    model = TeacherData
    form_class = TeachersForm
    template_name = 'new_teacher.html'
    #template_name = 'new_teacher.html'
    success_url = reverse_lazy('teachers')

    def get_context_data(self, *args, **kwargs):
        context = super(NewTeacherView,self).get_context_data(*args, **kwargs)
        context["user"] = User.objects.create_user(
            username=???????
            password=???????)
        return context

The form is below

class TeachersForm(forms.ModelForm):
    class Meta:
        model = TeacherData
        fields = ("first_name","last_name")
        
        widgets = {
            "first_name":forms.TextInput(attrs={"class":'form-control'}),
            "last_name":forms.TextInput(attrs={"class":'form-control'}),
        }

My interest and desire is to use the first_name for both username and password

1 answer

  • answered 2021-04-21 11:22 Abdul Aziz Barkat

    Instead of trying to override get_context_data, you should instead override form_valid which is called if the form is valid and saves the object:

    class NewTeacherView(LoginRequiredMixin,CreateView):
        model = TeacherData
        form_class = TeachersForm
        template_name = 'new_teacher.html'
        #template_name = 'new_teacher.html'
        success_url = reverse_lazy('teachers')
        
        def form_valid(self, form):
            response = super().form_valid(form)
            teacher_data = self.object
            first_name = teacher_data.first_name
            # Best normalize this using:
            # first_name = User.normalize_username(first_name)
            # Also first names are not guaranteed to be unique, you should write some code for that case
            user = User.objects.create_user(username=first_name, password=first_name)
            return response