This is not a technical question, but the question "I am doing it right."
I have several models defined
class Style(models.Model): tag_xml = models.TextField() image = models.ImageField(upload_to="styles") user = models.ForeignKey(User) uploaded = models.DateField() class StyleMatch(models.Model): style = models.ForeignKey(Style) item = models.ForeignKey(FashionItem)
they cannot be filled in via html forms simply because of the nature of the task, therefore, to fill them in, I have an html page with jquery and many event functions and other javascript goodies. When the save button is pressed, I call .ajax () and pass all the collected variables
var saveRequest= $.ajax({ url: "/save_style/", type: "POST", data: "selection="+s+"&user="+user+"&src="+image_src, dataType: "text" });
My save_style mode then saves the values ββin the model
def save_style(request): if request.method == 'POST': selection = request.POST['selection'].rsplit("|") user = request.POST['user'] src = request.POST['src'] f = open(MEDIA_ROOT+src) image_file = File(f) u = User.objects.get(id=user) style = Style(tag_xml = "", image = image_file, user = u, uploaded = date.today()) style.save() for s in selection: if (s != ''): match = FashionItem.objects.get(id=s) styleMatch = StyleMatch(style = style, item = match) styleMatch.save() i = StyleMatch.objects.filter(style=style) items = FashionItem.objects.filter(id__in=i) return render_to_response('style_saved.html', dict(image=src, items=items, media_url = MEDIA_URL), context_instance=RequestContext(request))
After that, I really want to go to the success page and display the entries that I just added to the model, however, if I use render_to_response
and pass the details of the model, I need to rebuild the entire page in javascript, it seems better to redirect to a new template, but if I am using HttpResponseRedirect
a) I cannot pass values ββand b) it does not seem to be redirected quite correctly (I think because the message comes from my javascript).
So finally my questions
- Is this really how I should do it? The django dossiers don't really seem to cover these somewhat more complex areas, so I'm a little unsure.
- Should I use render_to_response or HttpResponseRedirect above? Or perhaps the third option that I do not know about.
Any suggestions appreciated.
FYI I know that the code above is not perfect, i.e. missing verification, comments ... etc., it was simply provided for demonstration purposes. Feel free to point out any serious issues.