我一直在努力创建一个照片上传系统,允许用户上传图片,然后写入标题并对该图片发表评论。我在创建图像上传功能时最初使用的是ModelForm,但是切换到了一个表单向导以进行上传和放大。评论功能基于以前的stackoverflow答案。我真的很困惑让我的网站的用户ID系统使用这种方法(当我试图上传图片时我不断得到错误用户ID不能为空)并且找不到任何好的资源 - 是否有任何建议方法是有效的,我如何解决user_id问题?
Views.py:
def showScrapbookPage(request,userID):
if request.method == 'POST':
image = ImageUploadForm(request.POST, request.FILES)
user = User.objects.get(pk=userID)
if image.is_valid():
image.save()
scrapbook_gen = Pictures.objects
url = Pictures.objects.filter(user=User.objects.get(pk=userID))
return render(request, 'scrapbook/scrapbook.html', {'scrapbook_gen':scrapbook_gen, 'url':url, 'form': ImageUploadForm(),'userID':userID})
class PhotoWizard(SessionWizardView):
file_storage = FileSystemStorage(location = os.path.join(settings.MEDIA_ROOT, ''))
def done(self, form_list, **kwargs):
do_something_with_the_form_data(form_list)
return HttpResponseRedirect('/page-to-redirect-to-when-done/')
Models.py:
class Pictures(models.Model):
user = models.ForeignKey(User)
picture = models.ImageField(upload_to = 'scrapbook_uploads', default = 'static/scrapbook/images/no_pic_uploaded.jpg');
date = models.DateTimeField('date published', auto_now=True)
caption = models.TextField(blank = True)
title = models.CharField(max_length = 100, blank = True) #New
def __unicode__(self):
return self.caption
Forms.py:
class ImageUploadForm(ModelForm):
class Meta:
model = Pictures
fields = ['picture']
user = ['userID']
class TitleCommentForm(ModelForm):
class Meta:
model = Pictures
field = ["caption", "title"]
网址:
url(r'^(?P<userID>[-\w]+)/scrapbook/',views.showScrapbookPage, name='showScrapbook'),
url(r'^contact/$', PhotoWizard.as_view([ImageUploadForm, TitleCommentForm])),
模板中的相关部分:
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
<input type="submit" value="{% trans "submit" %}"/>
</form>
{% endblock %}
<!--Grid -->
<div id='frame'>
<table id = "frame-table">
<tr>
<td id = "left">
<span class="glyphicon glyphicon-chevron-left" alt = "left"></span>
</td>
<td id = "right">
<span class = "glyphicon glyphicon-chevron-right" alt = "right"/>
</td>
</tr>
</table>
<img id = "main" src="" alt=""/>
</div>
<div id = "wrapper" class="showpiece">
<ul id = "portfolio">
{% for x in url %}
{{ x.picture }}
<li><img src = '{{ MEDIA_URL }}{{ x.picture }}' ></li>
{% endfor %}
</ul>
</div>
谢谢!
答案 0 :(得分:0)
完全删除已添加的UserID
内容,并在您的观看中使用user = request.user
。