通过链接注册新用户时无法自动创建配置文件

时间:2019-01-29 10:53:29

标签: django user-profile

问题:

尚未通过“注册”链接(新用户注册)创建用户个人资料,但只能在管理页面中创建。

view.py

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required

def register_view(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Your account has been created!!!')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register_users.html', {'form': form})

@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!!!')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
    'u_form': u_form,
    'p_form': p_form
    }

    return render(request, 'users/profile_users.html',context)

model.py

from django.db import models
from django.contrib.auth.models import User


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='abc.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile


class UserRegisterForm(UserCreationForm):
    email    = forms.EmailField(max_length=30)

    class Meta:
        model = User
        fields = [
        'username',
        'email',
        'password1',
        'password2',
        ]

class UserUpdateForm(forms.ModelForm):
    email    = forms.EmailField(max_length=30)

    class Meta:
        model = User
        fields = [
        'username',
        'email']

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['image']

signals.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

profile_users.html

{% extends 'postorder/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
  <div class="media">
    <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
    <div class="media-body">
      <h2 class="account-heading">{{ user.username }}</h2>
      <p class="text-secondary">{{ user.email }}</p>
    </div>
  </div>
  <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Profile info!</legend>
            {{ u_form|crispy }}
            {{ p_form|crispy }}
        </fieldset>
        <div class="form-group">
            <button class="btn btn-outline-info" type="submit">Update!</button>
        </div>
 </form>
</div>
{% endblock content %}

register_users.html

{% extends 'postorder/base_postorder.html' %}
{% load crispy_forms_tags %}
{% block content %}
    <div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">SUBMIT NOW!</legend>
                {{ form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Sign Up!</button>
            </div>
        </form>
        <div class="border-top pt-3">
            <small class="text-muted">
                ALready Have an Account? <a class="ml-2" href="{% url 'login' %}">Sign In!</a>
            </small>
        </div>

    </div>
{% endblock content %}
  • app.py施加的信号

代码有什么问题? 提前道歉长代码,因为新手不知道问题出在哪里,因为积累了不同的方法。

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,您必须在 AppConfig 类的 apps.py 中创建一个函数:

class AccountsConfig(AppConfig):
    name = 'accounts'

    # for signals.property
    def ready(self):
        import accounts.signals

答案 1 :(得分:0)

Watch this

我认为您需要删除 form.save()并投放此代码(在 if form.is_valid()之后)

views.py

def register_view(request):
    ....
    <your_field_from_registration> = form.cleaned_data.get('<your_field_from_registration>')
    user = form.save(commit=False)
    user.save()
    profile = user.profile
    ....
    profile.<your_field_from_registration> = <your_field_from_registration>
    ....
    profile.save()
    ....