Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将用户注册表添加到我的django应用程序?_Django_Authentication_Authorization_Django 1.9 - Fatal编程技术网

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

如何将用户注册表添加到我的django应用程序?,django,authentication,authorization,django-1.9,Django,Authentication,Authorization,Django 1.9,我已经能够创建一个表单,用户可以在其中输入他们的用户名和密码 我希望能够创建一个用户帐户:按下一个按钮,将用户转移到另一个页面,在那里他们将填写一个表单,并将详细信息保存到数据库中。我还想确保没有重复的用户名。然而,我不知道如何编码它。我对django很陌生,所以我很挣扎 我正在使用windows和atom代码编辑器,如果这有区别的话。请有人帮我编码 您可以理解,它确实帮助了我,如果您完全理解它,您将更加熟悉django配置 更新 此外,您还可以按照以下步骤操作: 1.-使用以下代码在应用程序

我已经能够创建一个表单,用户可以在其中输入他们的用户名和密码

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

我正在使用windows和atom代码编辑器,如果这有区别的话。请有人帮我编码

您可以理解,它确实帮助了我,如果您完全理解它,您将更加熟悉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文件(如果未创建)

  • 4.-最后只需在html文件中添加表单

    
    {%csrf_令牌%}
    {%if消息%}
    {消息%中的msg为%0}
    x
    {%autoescape off%}
    {{msg.message}}
    {%endautoescape%}
    {%endfor%}
    {%endif%}
    {%if form.errors%}
    x
    哎呀,阿尔戈·萨利奥马尔。
    {%endif%}
    名义
    {{form.first_name}
    

    {{form.first\u name.errors.as\u text}

    阿佩利多 {{form.last_name}

    {{form.last\u name.errors.as\u text}

    名为乌萨里奥 {{form.username}

    {{form.username.errors.as_text}

    科雷奥电子公司 {{form.email}

    {{form.email.errors.as_text}

    管理员 {{form.is_staff}

    {{form.is\u staff.errors.as\u text}


  • 希望这对您有用。

    虽然此链接可以回答问题,但最好在此处包含答案的基本部分,并提供链接供参考。如果链接页面发生更改,仅链接的答案可能无效。-@techspider,thanx对于反馈,我将编辑答案。
    
        # 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})
    
    
    
    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
    ]
    
    
    <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>