I’m not really too sure how to title this question, but I’m trying to develop a simple webapp with Django. What I’m trying to do is that the user will manually tag each image, and each tag will have a foreign key to a specific image (but each image can have multiple tags). The index page is supposed to display the actual image, but I haven’t figured that out yet…
Pretty much the problem is, I’m not sure how to implement it so for each page, the index page will show a picture and a box for the image tag. After the user submits, it will go to the next untagged image / image with the least number of tags. Right now, the user can submit a tag (and the data is written correctly), but it still stays on the same image. I’m a Python / Django noob, so forgive me 😛
Here is the relevant source code:
forms.py:
class InputForm(forms.ModelForm):
image = forms.ModelChoiceField(queryset=Image.objects.all(),
widget=forms.HiddenInput())
class Meta:
model = Tag
models.py:
class Image(models.Model):
image_location = models.CharField(max_length=200)
num_tags = models.IntegerField(default=0)
image_score = models.FloatField()
def __unicode__(self):
return u'%d' % self.id
class Tag(models.Model):
image = models.ForeignKey(Image)
tag_text = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return self.tag_text
views.py:
def index(request):
if request.method == 'POST':
return HttpResponse(request.POST['image'])
image = Image.objects.all()[0]
form = InputForm(initial={'image': image})
return render_to_response('imageSite/index.html',
{
'form':form,
},
context_instance=RequestContext(request))
def submit(request):
form = InputForm(request.POST)
if(form.is_valid()):
image = form.cleaned_data['image'];
image.num_tags = image.num_tags + 1
image.save()
model = form.save()
model.save()
return redirect(index)
index.html:
<ul>
<form action="/imageSite/submit/" method="post">
{%csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit" />
</form>
</ul>
The code
return redirect(index)won’t work. You’ll need to return a redirect response with the proper URL to which it should redirect. For example:See this example in the Django documentation for a full example. Note that the value for
redirect_urlneeds to be computed in your view: you’ll need to compute theImageobject with the least number of tags and use Django’sreverseto cleanly compute the URL of thatImageobject. If the form is invalid then you should not perform a redirect.