Необходимо сделать валидацию формы и выполнить запись в модель на основании данных введенных в HTML форме.
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from RandomQuote.upload.forms import UploadFileForm
from RandomQuote.settings import MEDIA_ROOT
def handle_uploaded_file(f):
destination = open(MEDIA_ROOT+'/images/'+f.name, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
def startUpload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['firstfile'])
form.save()
return HttpResponseRedirect('/')
from django import forms
class UploadFileForm(forms.Form):
author = forms.CharField(required=True)
title = forms.CharField(required=True)
describe = forms.Textarea()
tags = forms.SelectMultiple()
firstfile = forms.ImageField()
def save(self):
author = self.cleaned_data["author"]
title = self.cleaned_data["title"]
describe = self.cleaned_data["describe"]
tags = self.cleaned_data["tags"]
from RandomQuote.quotes.models import Tag, Image
Image(image_author=author,
image_title=title,
image_description=describe,
image_tags=tags
).save()
<form enctype="multipart/form-data" action="upload/" method="post">
{% csrf_token %}
<TABLE cellpadding="0" cellspacing="0" border="0">
<TR><TD><label for="id_author">Автор:</label></TD><TD><input type="text" size=20 name="author" id="id_author" value="{{ user.username }}" /></TD></TR>
<TR><TD><label for="id_title">Название:</label></TD><TD><input type="text" size=20 name="title" id="id_title" /></TD></TR>
<TR><TD><label for="id_describe">Описание:</label></TD><TD><textarea rows="10" cols="20" name="describe" id="id_describe"></textarea> </TD></TR>
<TR><TD>Дата: </TD><TD>{% now "jS F Y H:i" %}</TD></TR>
<TR><TD><label for="id_tags">Выберите теги:</label></TD><TD>
<select multiple="multiple" name="tags" id="id_tags">
{% if tags %}
{% for tag in tags.all %}
<option>{{ tag }}</option>
{% endfor %}
{% endif %}
</select>
</TD></TR>
<TR><TD><label for="id_firstfile">Файл:</label></TD><TD><input type="file" size=20 name="firstfile"
id="id_firstfile" /></TD></TR>
<TR><TD colspan="2" align="right"> <input type="submit" value="Загрузить!" /></TD></TR>
</TABLE>
</form>
from django.db import models
from django.contrib.auth.models import User
class Tag(models.Model):
tag_name = models.CharField(max_length=30)
def __unicode__(self):
return self.tag_name
class Image(models.Model):
image_author = models.ForeignKey(User)
image_title = models.CharField(max_length=30)
image_description = models.TextField(blank=True)
image_pubdate = models.DateTimeField(auto_now_add=True)
image_source = models.ImageField(upload_to='images/')
image_tags = models.ManyToManyField(Tag,blank=True)
def __unicode__(self):
return '%s (%s)' % (self.image_title, self.image_author)
class Comment(models.Model):
comment_author = models.ForeignKey(User)
comment_image = models.ForeignKey(Image)
comment_title = models.CharField(max_length=50)
comment_pubdate = models.DateTimeField(auto_now_add=True)
comment_text = models.TextField()
def __unicode__(self):
return '%s (%s)' % (self.comment_title, self.comment_author)
Ошибка следующая:
KeyError at /upload/
'describe'
Request Method: POST
Request URL: http://localhost/upload/
Django Version: 1.3
Exception Type: KeyError
Exception Value:
'describe'
Почему он ругается на поле describe?
Я знаю, что не очень хорошо развивать два вопроса в одной теме, но все же. Слишком много копи-паст для второго вопроса.
Второй вопрос такой.
В поле tags = forms.SelectMultiple(), файла forms.py мне необходимо записать значения из
<select multiple=“multiple” name=“tags” id=“id_tags”>
</select>
Можно наводку куда копать, что бы это осуществить?