Чтобы добавить больше функций в модель по умолчанию, я использовал один к одному, поданный в Django. Затем я хочу настроить мою страницу обновления / редактирования Userprofile.
Я переписываю форму обновления примерно так:
{% load static %}
...
<div id="block-center" class="col-md-6 col-md-offset-3">
<form method="post">
{% csrf_token %}
...
<div class="form-group">
<p>
<label for="id_location">Location:</label> <input class="form-control" placeholder="Location"type="text" name="location" value="{{user.profile.location}}"maxlength="30" id="id_location" />
</p>
</div>
<div class="form-group">
{% if user.profile.upload.url%}
<p class="file-upload">Currently: <img src="{{user.profile.upload.url}}" alt="Avatar" class="avatar"><br></p>
<label for="id_upload">Change:</label> <input type="file" name="upload" value="{{user.profile.upload}}" id="id_upload" />
{% else%}
<label for="id_upload">Avator:</label> <input type="file" name="upload" value="{{user.profile.upload}}" id="id_upload" />
{% endif %}
</div>
<button class="btn btn-primary" type="submit">Save changes</button>
</form>
</div>
Мой models.py :
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
upload = models.FileField()
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
My views.py:
from django.db import models
from django.contrib.auth.models import User
from users.forms import UserForm,ProfileForm
from django.contrib import messages
from django.shortcuts import render,redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.utils.translation import gettext as _
@login_required
@transaction.atomic
def update_profile(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.profile)
profile = request.user.profile
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, _('Your profile was successfully updated!'))
return redirect('blog:index')
else:
messages.error(request, _('Please correct the error below.'))
else:
user_form = UserForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.profile)
user = User.objects.get(id=request.user.id)
profile = request.user.profile
return render(request, 'profiles/profile.html', {
'user_form': user_form,
'profile_form': profile_form,
'profile':profile
})
Все остальные поля работают хорошо, кроме загрузки файлового поля в модели Userprofile. Я не знаю почему. Кто-нибудь может мне помочь?