Я не использую панель администратора по умолчанию в django, и я использую свой собственный шаблон для администратора. Но здесь у меня возникли некоторые проблемы при редактировании и обновлении пользователя. Я хочу, чтобы этот код был уникальным для каждого пользователя в базе данных.в моем forms.py довольно хорошо при добавлении пользователя, но при обновлении у меня возникла некоторая проблема с электронной почтой. Так как я сделал электронную почту уникальной в forms.py, она также выдает ошибку при обновлении. Как я могу обновить пользователей такчто отредактированный пользователь может иметь тот же адрес электронной почты, но не тот же, что и адрес электронной почты другого пользователя.
forms.py
class RegisterForm(UserCreationForm):
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise ValidationError('Email Already Exists')
return email
class Meta:
model = User
fields = ['username', "email", "password1", "password2",'is_superuser','is_staff','is_active']
views.py
def register(request):
if not request.user.is_superuser:
messages.warning(request, 'Permission Denied.You have no permission to register users.')
return redirect('students:home')
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
messages.success(request,'user created with username {}'.format(user.username))
return redirect('students:our_users')
else:
form =RegisterForm()
return render(request,'students/register.html',{'form':form})
def editusers(request,id):
if not request.user.is_superuser:
messages.warning(request, 'Permission Denied.You have no permission to perform this action.')
return redirect('students:our_users')
user = User.objects.get(id=id)
return render(request,'students/edit_users.html',{'user':user})
def updateusers(request,id):
if not request.user.is_superuser:
messages.warning(request, 'Permission Denied.You have no permission to perform this action.')
return redirect('students:our_users')
user = User.objects.get(id=id)
form = RegisterForm(request.POST,instance=user)
if form.is_valid():
user = form.save(commit=True)
user.save()
messages.success(request,'{} updated'.format(user.username))
return redirect('students:our_users')
else:
messages.error(request,'Error in Form')
return redirect('students:edit_user',user.id)
шаблон регистра
<form action="" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<div class="text-xs-right">
<button type="submit" class="btn btn-info">Add</button>
</div>
</form>
шаблон Edituser
<form action="{% url 'students:update_user' user.id %}" method="post">
{% csrf_token %}
<div class="form-group"><label for="id_username">Username</label><input type="text" name="username" maxlength="150" autofocus class="form-control" value="{{user.username}}" placeholder="Username" title="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." required id="id_username">
<small class="form-text text-muted">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</small>
</div>
<div class="form-group"><label for="id_email">Email</label><input type="email" name="email" value="{{user.email}}" class="form-control" placeholder="Email" title="" required id="id_email"></div>
<div class="form-group"><label for="id_password1">Password</label><input type="password" name="password1" value="{{user.password}}" class="form-control" placeholder="Password" title="Your password must contain at least 8 characters.Your password can&#39;t be entirely numeric." required id="id_password1">
<small class="form-text text-muted"><ul><li>Your password must contain at least 8 characters.</li><li>Your password can't be entirely numeric.</li></ul></small>
</div>
<div class="form-group"><label for="id_password2">Password confirmation</label><input type="password" name="password2" value="{{user.password}}" class="form-control" placeholder="Password confirmation" title="Enter the same password as before, for verification." required id="id_password2">
<small class="form-text text-muted">Enter the same password as before, for verification.</small>
</div>
<div class="form-group"><div class="form-check"><input type="checkbox" name="is_superuser" {% if user.is_superuser %}checked="checked" {% endif %}
class="form-check-input" id="id_is_superuser"><label class="form-check-label" for="id_is_superuser" title="Designates that this user has all permissions without explicitly assigning them.">Admin status</label>
<small class="form-text text-muted">Designates that this user has all permissions without explicitly assigning them.</small>
</div></div>
<div class="form-group"><div class="form-check"><input type="checkbox" name="is_staff" {% if user.is_staff %}checked="checked" {% endif %} class="form-check-input" id="id_is_staff"><label class="form-check-label" for="id_is_staff" title="Designates whether the user can log into this admin site.">Staff status</label>
<small class="form-text text-muted">Designates whether the user can log into this admin site.</small>
</div></div>
<div class="form-group"><div class="form-check"><input type="checkbox" {% if user.is_active %}checked="checked" {% endif %} name="is_active" class="form-check-input" id="id_is_active"><label class="form-check-label" for="id_is_active" title="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.">Active</label>
<small class="form-text text-muted">Designates whether this user should be treated as active. Unselect this instead of deleting accounts.</small>
</div></div>
<div class="text-xs-right">
<button type="submit" class="btn btn-info">Update</button>
</div>
</form>