问题描述
我正在尝试为通过OAuth注册的用户制作“上传头像”表格。如果我仅使用“头像”作为表单的字段选择,则每次都会得到“此字段为必填”作为响应。我需要一种获取当前登录用户并在上传的头像旁边提交其ID的方法。
forms.py
from django import forms
from django.core.files.images import get_image_dimensions
from soc_auth.models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
#fields = '__all__'
fields = ['avatar']
#def __init__(self,user,*args,**kwargs):
#self.user = user
#super(UserProfileForm,self).__init__(*args,**kwargs)
def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
w,h = get_image_dimensions(avatar)
#validate dimensions
max_width = max_height = 1000
if w > max_width or h > max_height:
raise forms.ValidationError(
u'Please use an image that is '
'%s x %s pixels or smaller.' % (max_width,max_height))
#validate content type
main,sub = avatar.content_type.split('/')
if not (main == 'image' and sub in ['jpeg','pjpeg','gif','png']):
raise forms.ValidationError(u'Please use a JPEG,'
'GIF or PNG image.')
#validate file size
if len(avatar) > (20 * 1024):
raise forms.ValidationError(
u'Avatar file size may not exceed 20k.')
except AttributeError:
"""
Handles case when we are updating the user profile
and do not supply a new avatar
"""
pass
return avatar
models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
class Meta:
app_label = "soc_auth"
user = models.OnetoOneField(User,on_delete=models.CASCADE,blank = True,null = True)
avatar = models.ImageField(upload_to = "images/")
views.py
from django.shortcuts import render
from .forms import UserProfileForm
def index(request):
if request.method == "POST":
form = UserProfileForm(request.POST,request.FILES)
if form.is_valid():
#form.user = request.user
form.save()
#current_user.avatar = form.instance
img_obj = form.instance
return render(request,'soc_auth/index.html',{'form': form,'img_obj' : img_obj})
else:
form = UserProfileForm()
return render(request,{'form': form})
index.html
<!doctype html>
<html lang="en">
<head>
<Meta charset="utf-8">
<title>My fake blog!</title>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4"
crossorigin="anonymous">
</head>
<body>
<div class="jumbotron">
<h1>My fake blog!</h1>
{% if user.is_authenticated %}
<p>Logged as {{ user.username }}</p>
<a class="btn btn-primary" href="{% url 'logout' %}">logout</a>
<form method = "POST" enctype="multipart/form-data" class = "post-form">{% csrf_token %}
{{form.as_p}}
<button type = "submit" class = "save btn btn-default">Save</button>
</form>
{% if img_obj %}
<h3>Succesfully uploaded : {{img_obj.title}}</h3>
<img src="{{img_obj.image.url}}" alt="connect" style="max-height:300px">
{% endif %}
{% else %}
<a class="btn btn-primary" href="{% url 'social:begin' 'google-oauth2' %}">
Login
</a>
{% endif %}
</div>
<div class = "user-forms">
</div>
<div class="container-fluid">
{% for post in posts %}
<div>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<p>Posted by {{ post.user.username }} | {{ post.date }}</p>
</div>
{% endfor %}
</div>
</body>
</html>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)