mark
mark

Reputation: 673

Field in the model does not change in django app

I'm working on a django 1.4.5. I added to the model, select the size of T-shirts.

Field in my model

tshirt_size = models.CharField(choices=TSHIRT_SIZE_CHOICES, default="s", blank=True, null=True, max_length=24)

My form

class SubscriberForm(forms.ModelForm):
    class Meta():
        model = Subscriber
        exclude = ['event', 'is_active']
        widgets = {
            'name': TextInput(),
            'last_name': TextInput(),
            'email': TextInput(),
            'tshirt_size': Select(choices=TSHIRT_SIZE_CHOICES)
        }

In view, I get data in this way:

tshirt_size = request.POST.get('tshirt_size')

Part of html code

<label for="id_tshirt_size">T-Shirt Size (Unisex):</label>
{{ form.tshirt_size }}

And when I execute save on form I get in admin panel None value for tshirt_size.

Upvotes: 0

Views: 52

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77952

Here's the canonical way to use a ModelForm to create or update a model instance:

def myview(request, pk=None):
    if pk:
        instance = get_object_or_404(Subscriber, pk=pk)
    else:
        instance = None
    if request.method == "POST":
        form = SubscriberForm(request.POST, instance=instance)
        if form.is_valid():
            instance = form.save()
            # do whatever with instance or just ignore it
            return redirect(some return url)
    else:
        form = SubscriberForm(instance=instance)
    context = {"form":form}
    return render(request, "path/to/your/template.html", context)

If your view doesn't look something like it then you're very probably doing it wrong. Your mention of a tshirt_size = request.POST.get('tshirt_size') in your view is a sure smell you're doing it wrong FWIW.

Upvotes: 1

Related Questions