提问者:小点点

django中的扩展用户模型不保存配置文件图像


我试图创建一个在姜戈的聊天论坛。但要做到这一点,我需要扩展用户模型,但扩展后,配置文件图像不保存这是我的模型

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.EmailField()
img = models.FileField(upload_to='media/', blank=True, null=True)

def __str__(self):
    return self.user.username
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
    Profile.objects.create(user=instance)
instance.profile.save()

我的观点:

def signup(request):
if request.method == 'POST':
    form = SignUpForm(request.POST)
    if form.is_valid():
        user = form.save()
        user.refresh_from_db()  # load the profile instance created by the signal
        user.profile.email = form.cleaned_data.get('email')
        user.profile.img = form.cleaned_data.get('img')
        user.save()
        raw_password = form.cleaned_data.get('password1')
        user = authenticate(username=user.username, password=raw_password)
        login(request, user)
        return redirect('home')
else:
    form = SignUpForm()
return render(request, 'tforum/signup.html', {'form': form})

我的表单.py

class SignUpForm(UserCreationForm):
email = forms.EmailField(help_text='Required.')
img = forms.FileField(help_text='Upload Image')
class Meta:
    model = User
    fields = ('username', 'email', 'img', 'password1', 'password2', )

signup.html

 <form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
  <p>
    {{ field.label_tag }}<br>
    {{ field }}
    {% if field.help_text %}
      <small style="color: grey">{{ field.help_text }}</small>
    {% endif %}
    {% for error in field.errors %}
      <p style="color: red">{{ error }}</p>
    {% endfor %}
  </p>
{% endfor %}
<button type="submit">Sign up</button>

null

设置.py

STATIC_URL=“/static/”

MEDIA_URL='/media/'MEDIA_ROOT=os.path.join(BASE_DIR,'media')

问题是没有创建用户。如果我从用户保存的代码中删除img。

我已经去掉了大部分的造型


共1个答案

匿名用户

您应该创建profileForm

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('email', 'img')

并更新您的signup.py

    def update_signup(request):
      if request.method == 'POST':
        form = SignUpForm(request.POST)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if form.is_valid() and profile_form.is_valid():
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.profile.email = form.cleaned_data.get('email')
            user.profile.img = form.cleaned_data.get('img')
            profile_form.save()
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'tforum/signup.html', {'form': form})