Mohammed Baashar
Mohammed Baashar

Reputation: 547

How to retrive ChoiceField value from a form?

I want to get the selected choice from a ChoiceField in a view. When I submit the form, I process it in a view:

views.py

def myFormSubmitView(request):

...
        if form.is_valid():
            print("valid form")
            post = Post()
            post.title = form.cleaned_data["title"]
            post.body = form.cleaned_data["body"]

            **>>>>post.choice_test = form.cleaned_data["choice_test"]**

            post.save()
            return HttpResponseRedirect(request.path_info)

I want to get the value of choice_test. How can I do that ?

=========EDIT:========

This is the code of forms.py and models.py:

forms.py

from blog.models import Post
from django.forms import ModelForm

class NewBlogForm(ModelForm):
    title = models.CharField(max_length=100)
    section_ids =(
        ("1", "sec1"),
        ("2", "sec2"),)
    section = forms.ChoiceField(choices=section_ids)
    body = models.CharField(max_length=255)
    image = models.ImageField(upload_to='static/.../', error_messages = {'invalid':("Image files only")},)
    class Meta:
        model = Post 
        fields = ['title','section','body','image']
    def __str__(self):
        return self.title

models.py

class Post(models.Model):
    title = models.CharField(max_length=255)
    author = models.ForeignKey(xxx,on_delete=models.CASCADE)
    image = models.ImageField(null=True,upload_to='static/xyz')
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField("Category", related_name="posts")
    likes = models.IntegerField(default=0,null=False)
    shares = models.IntegerField(default=0,null=False)
    def __str__(self):
        return self.title

Post() is a model not the request.POST.

Upvotes: -2

Views: 79

Answers (2)

white.seolpyo.com
white.seolpyo.com

Reputation: 404

try this, or you can include choice value in form.cleand_data with use forms.clean() method.

if form.is_valid():
  section = form.cleaned_data['section']
  choice = [i[1] for i in NewBlogForm.section_ids if i[0] == section][0]

Upvotes: 1

Tanmeet Singh Chhabra
Tanmeet Singh Chhabra

Reputation: 61

I might be wrong about this, but I think you can access the ChoiceField just like any other field by doing

form.cleaned_data["section"]

since "section" is the name of the ChoiceField.

Upvotes: 1

Related Questions