通过上传表单将图像上传到Django用户个人资料

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过上传表单将图像上传到Django用户个人资料相关的知识,希望对你有一定的参考价值。

我正在尝试创建一个学生注册页面,允许学生上传个人资料照片。我正在使用Django User模型和与StudentProfileOneToOne关系的User模型。这是我的代码:

学生\ models.py:

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


class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,)
    avatar = models.ImageField(upload_to='student_profile/', null=True, blank=True)

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

学生/ form.py:

from django import forms


class ImageUploadForm(forms.Form):
    profile_photo = forms.ImageField()

电子学习/ views.py:

from django.contrib.auth import authenticate, login, get_user_model
from django.http import HttpResponse
from django.shortcuts import render, redirect

from .forms import LoginForm, RegisterForm
from students.forms import ImageUploadForm
from students.models import StudentProfile

User = get_user_model()


def register_page(request):
    register_form = RegisterForm(request.POST or None)
    photo_upload_form = ImageUploadForm(request.POST, request.FILES)

    context = {
        "register_form": register_form,
        "photo_upload form": photo_upload_form
    }
    if register_form.is_valid():
        # print(register_form.cleaned_data)
        username = register_form.cleaned_data.get("username")
        first_name = register_form.cleaned_data.get("first_name")
        last_name = register_form.cleaned_data.get("last_name")
        email = register_form.cleaned_data.get("email")
        password = register_form.cleaned_data.get("password")

        new_user = User.objects.create_user(
            username, email, password,
            first_name=first_name,
            last_name=last_name,
        )

        if photo_upload_form.is_valid():
            user = username
            avatar = photo_upload_form.cleaned_data.get("profile_photo")
            new_user_profile = StudentProfile.objects.create(user, avatar)

        print(new_user)
    return render(request, "auth/register.html", context)

AUTH / register.html:

{% extends "base.html" %}
{% load static %}

{% block content %}

{% load crispy_forms_tags %}

<div class="container">
    <div class="row my-4">
        <div class="col-5">
            <form action="" method="post" class="form-control">
                {% csrf_token %}
                {{ register_form|crispy }}
            <input type="submit" class="btn btn-default" value="Submit">
            </form>
        </div>
        <div class="col-5">
            <form method="post" enctype="multipart/form-data" class="form-control">
                {% csrf_token %}
                 <input id="id_image" type="file" class="my-2" name="image">
                {{ photo_upload_form|crispy }}
            </form>
        </div>
    </div>
</div>
{% endblock %}

我面临两个问题:

1)ImageUploadForm没有渲染到register.html

2)没有创建StudentProfileUser被创造得很好。

我也尝试用ModelFormImageUploadForm替换形式,但我得到NULL constraintstudent_user,因为Django不是什么userStudentProfile

我一直在浏览Stack Overflow。所有解决方案都是关于如何将用户图像上传到Django管理员,但我没有找到任何显示如何在注册过程中将上传的图像与用户模型相关联的方法。如果这是一个重复的问题,请原谅我。谢谢。

答案

在您的eLearning/views.py:中,您传递到html页面的上下文中缺少_

 context = {
        "register_form": register_form,
        "photo_upload form": photo_upload_form
    }

这将是ImageUploadForm未渲染到register.html的原因

应该是这样的

context = {
        "register_form": register_form,
        "photo_upload_form": photo_upload_form
    }
另一答案

所以我明白了。真正的问题在于register.html代码。提交按钮仅适用于register_form,因此照片上传表单未进行验证,因此未创建学生档案条目。这是更新的代码:

电子学习/ views.py:

from students.forms import ImageUploadForm
from students.views import upload_pic

     def register_page(request):
            register_form = RegisterForm(request.POST or None)
            photo_upload_form = ImageUploadForm(request.POST, request.FILES)

            context = {
                "register_form": register_form,
                "photo_upload_form": photo_upload_form
            }
            if register_form.is_valid():
                username = register_form.cleaned_data.get("username")
                first_name = register_form.cleaned_data.get("first_name")
                last_name = register_form.cleaned_data.get("last_name")
                email = register_form.cleaned_data.get("email")
                password = register_form.cleaned_data.get("password")

                new_user = User.objects.create_user(
                    username, email, password,
                    first_name=first_name,
                    last_name=last_name,
                )


                upload_pic(request, photo_upload_form, username=username)

            return render(request, "auth/register.html", context)

学生/ views.py:

from django.contrib.auth import get_user_model
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, HttpResponse

from .models import StudentProfile
from .forms import ImageUploadForm

def upload_pic(request, form, username):
        if request.method == 'POST':
            if form.is_valid():
                User = get_user_model()
                user = User.objects.get(username=username)
                avatar = form.cleaned_data.get('profile_photo')
                new_user_profile = StudentProfile.objects.create(user=user, avatar=avatar)
                new_user_profile.save()

register.html:

{% extends "base.html" %}
{% load static %}

{% block content %}

{% load crispy_forms_tags %}

<div class="container">
    <div class="row my-4">
        <div class="col-5">
            <form action="" method="post" enctype="multipart/form-data" class="form-control">
                {% csrf_token %}
                {{ register_form|crispy }}
                {{ photo_upload_form|crispy }}
                <input type="submit" class="btn btn-default" value="Submit">
            </form>
        </div>
    </div>      
</div>

{% endblock %}

您必须确保enctype="multipart/form-data"位于您的代码中,否则图片上传表单将无法通过验证。我还建议您在form.py中添加图像验证方法。萨钦早些时候指出的东西:image form and validation。希望这可以帮助。

以上是关于通过上传表单将图像上传到Django用户个人资料的主要内容,如果未能解决你的问题,请参考以下文章

无法将图像上传到 Django 项目,获取表单对象没有属性“保存”

如何使用 django-storages 将图像上传到亚马逊 S3?在管理员中上传有效,但在网站表单中无效

(Django)无法为用户头像上传图像

Django:无法将上传的图像绑定到表单 ImageField()

将上传的图像保存到 Flask 上的数据库

在没有 django ModelForm 的情况下从用户上传图像的问题