Я расширил модель Django User, но у меня возникли проблемы при попытке добавить или отредактировать данные в расширенной модели. Мне потребуется практическая помощь с примерами кода. Вот код ниже.
на models.py
from django.db import models
from django.contrib.auth.models import User
class ExtendUserModel(models.Model):
url = models.URLField(blank=True, null=True, verbose_name='Website')
age = models.PositiveIntegerField(blank=True, null=True)
profile = models.ImageField(blank=True, null=True)
user = models.OneToOneField(User, on_delete=models.CASCADE, default=None)
def __str__(self):
return 'Extend User
на forms.py
from django import forms
from django.contrib.auth.models import User
from backend.models import(
ExtendUserModel)
from django.contrib.auth.forms import(UserChangeForm, UserCreationForm)
class RegisterForm(UserCreationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Username'}))
first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'First Name'}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'}))
email = forms.CharField(widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'}))
password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'}))
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Confirm Password'}))
class Meta():
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
class ExtendUserForm(forms.ModelForm):
url = forms.URLField(label='Website', required=False, widget=forms.URLInput(attrs={'class':'form-control', 'placeholder':'Website'}))
age = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'Age'}))
profile = forms.ImageField(help_text='Image', required=False, widget=forms.ClearableFileInput(attrs={'class':'file-upload-default file-upload-info'}))
class Meta():
model = ExtendUserModel
fields = ('url', 'age', 'profile')
on views.py
from django.shortcuts import render
from backend.forms import(
ChangePasswordForm, EditForm,
RegisterForm, ExtendUserForm)
from django.contrib import messages
def register_view(request):
if request.method == 'POST':
reg = RegisterForm(request.POST)
extend = ExtendUserForm(request.POST)
if reg.is_valid() and extend.is_valid():
user = reg.save()
extended = extend.save(commit=False)
extended.user = user
extended.save()
messages.success(request, 'User Registered')
else:
reg = RegisterForm()
extend = ExtendUserForm()
return render(request, 'backend/admin-register.html', {'reg':reg, 'extend':extend})
def edit_form(request):
if request.method == 'POST':
edit_form = EditForm(request.POST, instance=request.user)
extend = ExtendUserForm(request.POST, request.FILES, instance=request.user.extendusermodel)
if edit_form.is_valid() and extend.is_valid():
edit = edit_form.save()
extended = extend.save(commit=False)
extended.user = edit
extended.save()
else:
edit_form = EditForm(instance=request.user)
extend = ExtendUserForm(request.FILES, instance=request.user.extendusermodel)
return render(request, 'backend/edit-profile.html', {'edit':edit_form, 'ext':extend})
при регистрации администратора. html Этот файл используется для регистрации пользователя
<form class="forms-sample" method="post">
<div class="col-md-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Register User</h4>
<form class="forms-sample" method="post" enctype="multipart/form-data">
{% for field in reg %}
{% if field.errors %}
{% for error in field.errors %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
{% endif %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
{% for field in extend %}
{% if field.errors %}
{% for error in field.errors %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
{% endif %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
<div class="input-group col-xs-12">
{{ field }}
<span class="input-group-append">
<input type="text" class="form-control file-upload-info" disabled placeholder="Upload Image">
<button class="file-upload-browse btn btn-primary" type="button">Upload</button>
</span>
</div>
{% endif %}
</div>
{% endfor %}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-block mr-2">Add User</button>
</form>
в профиле редактирования. html Этот файл отображает данные в моей форме, когда аутентифицированный пользователь хочет изменить свой профиль
<form class="forms-sample" method="post">
<div class="col-md-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Edit Profile</h4>
<form class="forms-sample" method="post" enctype="multipart/form-data">
{% for field in edit %}
{% if field.errors %}
{% for error in field.errors %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
{% endif %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
{% for field in ext %}
{% if field.errors %}
{% for error in field.errors %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
{% endif %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
<div class="input-group col-xs-12">
{{ field }}
<span class="input-group-append">
<input type="text" class="form-control file-upload-info" disabled placeholder="Upload Image">
<button class="file-upload-browse btn btn-primary" type="button">Upload</button>
</span>
</div>
{% endif %}
</div>
{% endfor %}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-block mr-2">Edit Profile</button>
</form>