具有额外参数的自定义用户模型的表单和视图[django 2.1]

时间:2018-10-29 12:36:05

标签: python django django-models django-forms

我正在尝试创建一个表格,该表格允许我向自定义User对象添加个人资料图片。我知道有OneToOne方法,尽管我希望它直接存储在User中。

2 个答案:

答案 0 :(得分:2)

您需要像这样扩展默认的用户模型:

from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    """Add more fields to default user model."""

    profile_pic = models.ImageField(upload_to='profile_pics', blank=True, null=True)

现在,您需要编辑settings.py,以将自定义用户模型设为默认身份验证模型。在您的settings.py中添加此行:

AUTH_USER_MODEL = 'myApp.User'

myApp是您在其models.py中创建了自定义用户模型的应用程序的名称。
就是这样,现在默认身份验证模型是您的自定义模型User,它与Django默认身份验证模型完全相同,只是它具有一个用于存储图像的附加字段profile_pic

添加图片的表单应如下所示:

class profilepictureForm(forms.ModelForm):
    """Form to add profile picture to User model."""

    class Meta:
        """Meta class for profilepictureForm."""

        model = User
        fields = ('profile_pic', )

在您看来,您应该使用这种形式:

def add_profile_picture(request):
    if request.method == 'POST':
        form = profilepictureForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = profilepictureForm(instance=request.user)
        return render(request, 'userpanel/profilepicture.html', {'form': form})

答案 1 :(得分:1)

看看下面的代码

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})

有关更多信息,请检查https://docs.djangoproject.com/en/dev/topics/http/file-uploads/