如何从表单中捕获first_name? [英] How can I capture first_name from a form?

查看:74
本文介绍了如何从表单中捕获first_name?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将first_name放入上下文中.

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

下面的表格

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'}),
        }

我的兴趣和愿望是对 username password

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

推荐答案

而不是尝试覆盖 get_context_data ,您应该覆盖 form_valid ,如果表单是有效并保存对象:

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

这篇关于如何从表单中捕获first_name?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆