我想讓我的用戶能夠上傳個人資料圖片到他們的帳戶。問題是我使用的Django用戶模型,所以我沒有我自己的模型,我可以添加image = models.ImageField()
Django上傳圖像使用內置用戶模型
這是我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是空的。
他們大部分的解決方案都是關於擁有自己的模型。
非常感謝你我嘗試了其中一個提供的答案,很少有研究我能夠做到這一點:) – aamurad