如何将用户注册表添加到我的django应用程序中



根据本教程,我已经能够创建一个表单,用户可以在其中输入用户名和密码。

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

如果有区别的话,我会使用windows和atom代码编辑器。请有人帮我编码一下。

你可以学习这个youtube教程,它确实对我有帮助,如果你完全学习它,你会更熟悉django配置。

更新

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

  • 1.-在应用程序目录中创建一个forms.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'}),
            }
    
  • 2.-然后你必须在应用程序目录中创建view.py文件(如果没有创建)

    
        # 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})
    
    • 3.-在urls.py文件中添加路由

      
      from django.conf.urls import url
      from . import views
      urlpatterns = [
          url(r'^add/', views.UserFormView.as_view(), name='users-add'),
          # dont forget to add the .as_view() because our view is a class and not a function
      ]
      
  • 4.-最后只需将表单添加到您的html文件中即可

    <form action="" method="post">
        <div class="panel panel-default">
          <div class="panel-body">
            {% csrf_token %}
            {% if messages %}
              {% for msg in messages %}
                <div class="alert alert-{{msg.level_tag}} alert-dismissible" role="alert">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>
                  {% autoescape off %}
                    {{ msg.message }}
                  {% endautoescape %}
                </div>
              {% endfor %}
            {% endif %}
            {% if form.errors %}
              <div class="alert alert-danger alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>
                  <i class="fa fa-bug"></i> Oops, algo salió mal.
              </div>
            {% endif %}
            <div class="col-lg-6">
              <div class="form-group {% if form.first_name.errors %} has-error {% endif %}">
                <label class="control-label" for="first_name">Nombre</label>
                {{ form.first_name }}
                <p class="help-block">{{ form.first_name.errors.as_text }}</p>
              </div>
              <div class="form-group {% if form.last_name.errors %} has-error {% endif %}">
                <label class="control-label" for="last_name">Apellido</label>
                {{ form.last_name }}
                <p class="help-block">{{ form.last_name.errors.as_text }}</p>
              </div>
              <div class="form-group {% if form.username.errors %} has-error {% endif %}">
                <label class="control-label" for="username">Nombre de Usuario</label>
                {{ form.username }}
                <p class="help-block">{{ form.username.errors.as_text }}</p>
              </div>
              <div class="form-group {% if form.email.errors %} has-error {% endif %}">
                <label class="control-label" for="email">Correo Electronico</label>
                {{ form.email }}
                <p class="help-block">{{ form.email.errors.as_text }}</p>
              </div>
              <div class="form-group {% if form.is_staff.errors %} has-error {% endif %}">
                <label class="control-label" for="is_staff">Administrador</label>
                {{ form.is_staff }}
                <p class="help-block">{{ form.is_staff.errors.as_text }}</p>
              </div>
            </div>
          </div> <!-- panel-body -->
          <div class="panel-footer">
            <input class="btn btn-success btn-sm" type="submit" value="Registrar">
          </div> <!-- panel-footer -->
        </div> <!-- panel -->
      </form>
    

希望这对你有用。

相关内容

最新更新