/ / Django UpdateView - Salvar perfil de dados sem trabalho - django, django-class-based-views

Django UpdateView Perfil-Salvar-Dados-No-Trabalho - django, django-class-based-views

Holla ppl. Sou novo no django e estou tentando o meu melhor, mas neste momento estou preso e preciso de ajuda. O problema é: não consigo atualizar meu perfil de usuário via modelo. quando faço algumas alterações --- no console, posso ver o POST, então recebo o redirecionamento por "success_url". nenhum erro é exibido. mas novos dados não são salvos. django 1.11.4

aqui meus códigos:

Modelos:

class Profile(models.Model):
user       = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(blank=True)
location = models.CharField(max_length=30, blank=True)
bio        = models.TextField(max_length=500, blank=True)
active     = models.BooleanField(default=True)
timestamp  = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.user.username

@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()

Visualizações:

class RegisterView(CreateView):
template_name = "registration/register.html"
form_class = RegisterForm
success_url = "/"

def dispatch(self, *args, **kwargs):
# if self.request.user.is_authenticated():
#     return redirect("/logout")
return super(RegisterView, self).dispatch(*args, **kwargs)


class ProfileUpdateView(UpdateView):
model = Profile
form_class = ProfileForm
template_name = "profiles/profile-detail-update.html"
success_url = "/"

def get_object(self, **kwargs):
username = self.kwargs.get("username")
if username is None:
raise Http404
return get_object_or_404(User, username__iexact=username)

Formulários

class RegisterForm(forms.ModelForm):
password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput)

class Meta:
model = User
fields = ("username",)

def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don"t match")
return password2

def save(self, commit=True):
user = super(RegisterForm, self).save(commit=True)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user

class ProfileForm(forms.ModelForm):

class Meta:
model = Profile
fields = ("avatar", "location", "bio", "active",)

URL

url(r"^(?P<username>[w-]+)/$", ProfileUpdateView.as_view(), name="update"),

Modelo:

{% extends "base.html" %}

{% block content %}
<p>name: {{ user.username }}</p>
<p>location: {{ user.profile.location }}</p>
{% if user.profile.avatar %}
<img style="width: 200px" src="/images/{{ user.profile.avatar.url }}"/>
{% endif %}
<hr/>
{% include "snippets/form.html" %}
{% endblock %}

Snippet incluído:

<div class="form pt-2">
{% if form.errors.non_field_errors %}
{{ form.errors.non_field_errors }}
{% endif %}
<form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %}
{{ form.as_p }}
<button class="btn btn-success" type="submit">Save</button>
<button onclick="window.history.back();" class="btn btn-danger" type="button">Go back</button>
</form>
</div>

SOS.

Respostas:

1 para resposta № 1

Na tua ProfileUpdateView você está passando um User instância para o formulário, em vez de um Profile instância:

class ProfileUpdateView(UpdateView):
# ...

def get_object(self, **kwargs):
username = self.kwargs.get("username")
if username is None:
raise Http404
return get_object_or_404(Profile, user__username__iexact=username)