如何在我的django应用程序中添加用户注册表单?

时间:2016-03-29 21:19:20

标签: django authentication authorization django-1.9

我已经能够创建一个表单,用户可以在tutorial之后输入用户名和密码。

我希望能够通过以下方式创建用户帐户:按下一个按钮,将用户转移到另一个页面,在那里他们将填写表格并将详细信息保存到数据库中。我还想确保不重复用户名。但是,我不知道如何编码。我对django很新,因此我为什么要挣扎。

我正在使用Windows和原子代码编辑器,如果这有所不同。请有人帮我编码。

1 个答案:

答案 0 :(得分:1)

你可以关注this youtube tutorial,这对我很有帮助,如果你完全遵循它,你会更熟悉django配置。

<强>更新

此外,您可以按照以下步骤操作:

  • 1.-使用以下代码

    在app目录中创建forms.py文件
    BufferedIOBase
  • 2.-然后你必须在app目录中创建view.py文件(如果没有创建)

    
    
    
    # we import the django default user model
    from django.contrib.auth.models import User
    # also, import the forms to create em
    from django import forms
    
    # define a class for your form, it can be anithing you want
    class UserForm(forms.ModelForm):
        # password = forms.CharField(widget=forms.PasswordInput)
        # this Meta class is the way we send information for our form
        class Meta:
            # define the model
            model = User
            # define the fields you need (note that username and password are required)
            fields = [
                'password',
                'username',
                'first_name',
                'last_name',
                'is_staff',
                'email',
            ]
            # then, in widgets you can define the input type of the field and give
            # attributes to each one
            widgets = {
                'password': forms.PasswordInput(attrs={'class': 'form-control', 'name': 'username'}),
                'username': forms.TextInput(attrs={'class': 'form-control', 'name': 'username', 'placeholder': 'username'}),
                'first_name': forms.TextInput(attrs={'class': 'form-control', 'name': 'first_name', 'placeholder': 'First Name'}),
                'last_name': forms.TextInput(attrs={'class': 'form-control', 'name': 'last_name', 'placeholder': 'Last Name'}),
                'is_staff': forms.CheckboxInput(attrs={'class': 'form-control', 'name': 'is_staff'}),
                'email': forms.TextInput(attrs={'class': 'form-control', 'name': 'email', 'placeholder': 'email'}),
            }
    
    • 3.-在urls.py文件中添加路径

      # we import the django default user model
      from django.contrib.auth.models import User
      # also, import the forms to create em
      from django import forms
      
      # define a class for your form, it can be anithing you want
      class UserForm(forms.ModelForm):
          # password = forms.CharField(widget=forms.PasswordInput)
          # this Meta class is the way we send information for our form
          class Meta:
              # define the model
              model = User
              # define the fields you need (note that username and password are required)
              fields = [
                  'password',
                  'username',
                  'first_name',
                  'last_name',
                  'is_staff',
                  'email',
              ]
              # then, in widgets you can define the input type of the field and give
              # attributes to each one
              widgets = {
                  'password': forms.PasswordInput(attrs={'class': 'form-control', 'name': 'username'}),
                  'username': forms.TextInput(attrs={'class': 'form-control', 'name': 'username', 'placeholder': 'username'}),
                  'first_name': forms.TextInput(attrs={'class': 'form-control', 'name': 'first_name', 'placeholder': 'First Name'}),
                  'last_name': forms.TextInput(attrs={'class': 'form-control', 'name': 'last_name', 'placeholder': 'Last Name'}),
                  'is_staff': forms.CheckboxInput(attrs={'class': 'form-control', 'name': 'is_staff'}),
                  'email': forms.TextInput(attrs={'class': 'form-control', 'name': 'email', 'placeholder': 'email'}),
              }
      
  • 4.-最后只需在html文件中添加表单

    
        # import the View form django and the UserForm we created on step 1
        from django.views.generic import View
        from .forms import UserForm
        # And some other things we need
        from django.core.urlresolvers import reverse_lazy
        from django.http import HttpResponseRedirect
        from django.contrib.auth.models import User # we also need this one
        from django.shortcuts import render
        from django.contrib import messages
        from django.views import generic
    
    
    # create the class view, named as you need
    class UserFormView(View):
        # define the form to use, in this case the form we created
        form_class = UserForm
        # define the template_name, your main html file wher your are goin to use the form
        template_name = 'usersControll/add.html'
        # and the reverse_lazy is helpfull when the user succesfully added a new user
        # replace 'users-add' with the name of your rute 
        success_url = reverse_lazy('users-add')
    
        def get(self, request):
            form = self.form_class(None)
            return render(request, self.template_name, {'form': form})
    
        def post(self, request):
            form = self.form_class(request.POST)
    
            if form.is_valid():
                return self.form_valid(form)
            else:
                return self.form_invalid(form, request)
    
        def form_valid(self, form):
            # when the info the user gave us is valid, stop the commit 
            # so we can give some nice format to this info
            user = form.save(commit=False)
            # the "form.cleaned_data" help us to give a standar format to the info
            username = form.cleaned_data['username']
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            password = 'tempPass'
            user.set_password(password)
            # aaand we save it to the database
            user.save()
    
            # in my case a send a succesfull massage to the user indicating that
            # went fine
            messages.add_message(self.request, messages.SUCCESS, "El usuario <b>form.cleaned_data['first_name']</b> fue registrado exitosamente.")
            return super(UserFormView, self).form_valid(form)
    
        def form_invalid(self, form, request):
            return render(request, self.template_name, {'form': form})
    

希望这对你有用。