Я хочу, чтобы мои пользователи могли изменять свою информацию , когда я нажимаю "Enregistrer" (Сохранить), я перенаправлен, но нет сообщения об успехе и мой информация не меняется . Я думаю, что все настроил правильно, и я посмотрел на похожие вопросы, но это все еще не работает.
models.py:
from django.db import models
from django.contrib.auth.models import User
class Profil(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='defaut.png', upload_to='image_profil')
def __str__(self):
return f'{self.user.username} Profil'
forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profil
class FormulaireModifUtilisateur(forms.ModelForm):
username = forms.CharField(
label = 'Nom de compte',
min_length = 4,
max_length = 150,
initial=User.username,
)
email = forms.EmailField(
label = 'Email',
min_length = 4,
max_length = 150,
)
class Meta:
model = User
fields = ['username', 'email']
class FormulaireModifProfil(forms.ModelForm):
class Meta:
model = Profil
fields = ['image']
views.py:
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import FormulaireModifUtilisateur, FormulaireModifProfil
@login_required
def profil(request):
if request.method == 'POST':
u_form = FormulaireModifUtilisateur(
request.POST,
instance=request.user
)
p_form = FormulaireModifProfil(
request.POST,
request.FILES,
instance=request.user.profil
)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Votre compte a bien été mis à jour !')
return redirect('profil')
else:
u_form = FormulaireModifUtilisateur(instance=request.user)
p_form = FormulaireModifProfil()
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'profil/profils.html', context)
profils. html:
{% extends 'home/index.html' %}
{% block title %}
Profil
{% endblock %}
{% block content %}
<div id='profil'>
<img src='{{ user.profil.image.url }}'>
<form>
{% csrf_token %}
{% for field in u_form %}
<p>
{{ field.label_tag }}<br>
{{ field }<br>
</p>
{% endfor %}
{% for field in p_form %}
<p>
{{ field.label_tag }}<br>
{{ field }}<br>
</p>
{% endfor %}
{% for message in messages %}
<p id="messages">{{message}}</p>
{% endfor %}
<button type="submit">Enregistrer</button>
</form>
</div>
{% endblock %}