Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Saving to DB from form example

It seems I had difficulty finding a good source/tutorial about saving data to the DB from a form. And as it progresses, I am slowly getting lost. I am new to Django, and please guide me. I am getting error

local variable 'store' referenced before assignment

Here are my relevant codes,

models.py

from django.db import models

# Create your models here.
class Store(models.Model):
    store_name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.store_name

class Feedback(models.Model):
    store = models.ForeignKey(Store)
    username = models.CharField(max_length=100)
    comment = models.CharField(max_length=1000)
    date = models.DateTimeField("comment_date")

    def __unicode__(self):
        return self.username

views.py

def add(request, store_name):
    if request.method == "POST":
        store = Store.objects.get(store_name=store_name)
        saved_username = request.POST.get("username", "")
        saved_feedback = request.POST.get("feedback", "")
        feedback = Feedback(username=saved_username, comment=saved_feedback, date=timezone.now())
        feedback.save()
    return HttpResponseRedirect(reverse("view", args=(store.id,)))

addfeedback.html(the one that calls add in views.py)

<html>
<head><title>Add Feedback</title>
<link rel="stylesheet" type="text/css" href={{ STATIC_URL }}styles.css>
</head>

<body>
    <div class="form">
    <form action="{% url add store.store_name %}" method="post">
    {% csrf_token %}
        <input type="text" name="username" size="20"><br />
        <textarea name="feedback" cols="50" rows="10"></textarea><br />
        <input type="submit" value="Add" />
    </form>
</body>
</html>
like image 530
Lawrence Gimenez Avatar asked Dec 03 '12 07:12

Lawrence Gimenez


2 Answers

Use django.forms for the job. Don't put data straight from POST to db. See the related documentation.

local variable 'store' referenced before assignment

The error is obvious – you're referencing store even if the request isn't POST.

like image 116
Krzysztof Szularz Avatar answered Sep 24 '22 01:09

Krzysztof Szularz


Here is a pretty good tutorial on ModelForms. Although it's for Django 1.3, so it's slowly becoming obsolete.

You should only receive the local variable 'store' referenced before assignment error when you access the form submission url directly. If a form has been posted to the url, store should be assigned.

You are trying to create a form based on a model, so I'll explain how you could use a ModelForm.

Your feedback model has a DateTimeField and you are storing the timestamp of when the feedback was submitted. You can automate this by setting auto_now_add to true

date = models.DateTimeField("comment_date", auto_now_add=True)

Then create a forms.py in your app folder with the following

from django.forms import ModelForm
from your_app.models import Feedback
...
class FeedbackForm(ModelForm):
    class Meta:
        model = Feedback
        exclude = ('store',)

Your views.py should contain one function that displays and processes the submitted form

from your_app.forms import FeedbackForm
... 
def add(request, store_name):
    form = FeedbackForm(request.POST or None)
    if form.is_valid():
        feedback = form.save(commit=False)
        store = Store.objects.get(store_name=store_name)
        feedback.store = store
        feedback.save()
like image 41
Enrico Avatar answered Sep 24 '22 01:09

Enrico