ChoiceField in Django Forms using Python

Hello guys, now we are going to learn ChoiceField in Django Forms using Python. If you are here, then you are moving in the right direction looking for the solution. let me first explain how to write ChoiceField.

I know you are here just because you are in need of this awesome trick to learn about ChoiceField. If you don’t know about ChoiceField then you are in the right place. Because in this tutorial we gonna learn how to include ChoiceField.

ChoiceField in Django Forms

Let’s learn this with some easy examples.
At first, I am creating a blog of articles using Django. For all the codes you may refer this :
https://github.com/uday9866/django.git

Now go-to models.py in the above link and include ChoiceField.

  1. models.py :

    from django.db import models
    from django.contrib.auth.models import User
    
    # Create your models here.
    class Article(models.Model):
        title = models.CharField(max_length=100)
        slug = models.SlugField()
        body = models.TextField()
        date = models.DateTimeField(auto_now_add=True)
        thumb = models.ImageField(default='default.png',blank=True)
        author = models.ForeignKey(User,default=None,on_delete=models.CASCADE)
        choice = models.ChoiceField(choices = articles)
    
    
    
        def __str__(self):
            return self.title
        def snippet(self):
            return self.body[:50]+'...'
  2. forms.py :

    from django import forms
    from . import models
    
    class CreateArticle(forms.ModelForm):
        class Meta:
            model = models.Article
            fields = ['title','body','slug','thumb','author','choice']

Now  we have to do migrations and there are some commands we need to run in command prompt for windows :
Syntax :

Windows -> cmd
python manage.py makemigrations

Now the above command creates a new python file in the migrations. Still, we have to run some more commands.

Syntax :

python manage.py migrate
python manage.py runserver

After running the above command, we are going to get the output as follows :

Output :

System check identified some issues:
April 27, 2020 - 16:56:26
Django version 3.0.5, using settings 'djangonautic.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Now go to the browser and enter localhost:8000, then you will get the output. I hope you enjoyed it.

Leave a Reply

Your email address will not be published. Required fields are marked *