我对Django和一般的web开发都比较陌生。我正试图建立一个有两种类型的用户,客户和供应商的网站。我需要能够显示这两种类型的客户在网站上不同的东西。例如,标题部分中针对供应商的不同链接。
我的印象是,最好的方法是在我的/管理员中创建两个用户组(“供应商”和“客户”),创建两个不同的注册表(一个为供应商,一个为客户),并在提交注册表时将每个注册表发送给各自的用户组。从那里,我可以根据用户组决定用户看到了什么。对的
不幸的是,我对此几乎不知所措!我已经创建了用户组,创建了不同的注册表单,但在过去的两天里,我一直在试图找出如何将注册发送到各自的组,我就是无法做到这一点!我上下搜索了所有我能找到的建议代码:运气不好。
我试过的大部分东西都是这样的:
意见。py公司
from __future__ import unicode_literals
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
from django.contrib.auth.models import User, Group
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render, get_object_or_404
from .forms import SupplierRegisterForm
def supplier_signup_view(request):
form = SupplierRegisterForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
user.groups.add(Group.objects.get(name='suppliers'))
password = form.cleaned_data.get('password')
user.set_password(password)
user.save()
new_user = authenticate(username=user.username, password=password)
login(request, new_user)
if next:
return redirect(next)
return redirect("/")
context = {
"form": form,
"title": title,
}
return render (request, "supplier_signup.html", context)
形式。py公司
from django import forms
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
from django.contrib.auth.models import User, Group
User = get_user_model()
class SupplierRegisterForm(forms.ModelForm):
username = forms.CharField()
email = forms.EmailField(label="Email Address")
email2 = forms.EmailField(label="Confirm Email", widget=forms.TextInput(attrs={'autocomplete':'false'}))
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'email',
'email2',
'password',
]
def clean_email2(self):
email = self.cleaned_data.get('email')
email2 = self.cleaned_data.get('email2')
if email != email2:
raise forms.ValidationError("Emails must match")
email_qs = User.objects.filter(email=email)
if email_qs.exists():
raise forms.ValidationError("This email has already been registered")
return email
如果有人能给我一个初学者演练,告诉我如何在表单提交时自动将用户发送到用户组,我将不胜感激。请包括我需要使用的所有代码,无论是在设置,网址。py,型号。py,表单。py,视图。py或模板(包括导入等),以及我需要执行的任何命令和时间(例如迁移)。
非常感谢!