Django使用内置用户模型上传图像

时间:2017-06-17 12:03:16

标签: python django

我试图让我的用户能够将个人资料图片上传到他们的帐户。问题是我使用的是Django用户模型,所以我没有自己的模型可以添加image = models.ImageField()

这是我的forms.py

from django import forms
from django.contrib.auth import authenticate, get_user_model,


class UserRegisterForm(forms.ModelForm):
    confirm_email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)
    image = forms.ImageField(required=False)

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

    def clean_confirm_email(self):
        email = self.cleaned_data.get("email")
        confirm_email = self.cleaned_data.get("confirm_email")
        if email != confirm_email:
            raise forms.ValidationError("Emails do not match")

        email_qs = User.objects.filter(email=email)
        if email_qs.exists():
            raise forms.ValidationError("Email already used")
        return email

    def clean_confirm_password(self):
        password = self.cleaned_data.get("password")
        confirm_password = self.cleaned_data.get("confirm_password")
        if password != confirm_password:
            raise forms.ValidationError("Passwords do not match")

        return password

在我的注册页面中显示图像按钮,我不知道如何保存图像并将其链接到用户。

这是我的views.py

from django.shortcuts import render, redirect
from django.contrib.auth import (authenticate, get_user_model, login, logout)
from .forms import UserLoginForm, UserRegisterForm

# Create your views here.


def login_view(request):
    login_form = UserLoginForm(request.POST or None)
    if login_form.is_valid():
        username = login_form.cleaned_data.get("username")
        password = login_form.cleaned_data.get("password")
        user = authenticate(username=username,password=password)
        login(request, user)
        return redirect('/')
    context = {
        "login_form": login_form
    }
    return render(request, 'login.html', context)


def register_view(request):
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=False)
        password = form.cleaned_data.get("password")
        user.set_password(password)
        user.save()
        new_user = authenticate(username=user.username,password=password)
        login(request, new_user)
        return redirect('/')
    context = {
        'form': form,

    }
    return render(request, 'signup.html', context)


def logout_view(request):
    logout(request)
    return redirect('/')

因为你可以看到我正在使用Django用户模型,所以我的models.py和admin.py是空的。

大多数解决方案都是关于拥有自己的模型。

2 个答案:

答案 0 :(得分:0)

您需要将用户模型扩展为个人资料。使用下面的链接exame来扩展它。  Add image/avatar to users in django

答案 1 :(得分:0)

所以对于那些稍后会看到这个的人来说,这就是我解决它的方式。

我创建了一个UserProfile模型,并将其与来自

的用户链接
  

来自django.contrib.auth.models导入用户

使用models.OneToOneField( 用户

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

# Create your models here.


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField() # or whatever

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

然后使用正确的网址代码配置我的url.py

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

和我的setting.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

STATICFILES_DIRS = (
  os.path.join(BASE_DIR, 'static/'),
)

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

admin.py

from django.contrib import admin
from .models import UserProfile
# Register your models here.

admin.site.register(UserProfile)

我可以使用管理面板中的上传图片,并使用<img src="{{ user.userprofile.avatar.url }}">

在我的模板中显示这些图片

我希望我足够清楚,并且我可以帮助别人:)