Forms Class widget and interacting with database

Posted under » Django on 17 Jun 2021

From intro to Django Forms class.

If you want choices in radio button.

from django import forms

VOTE_CHOICES= [(1,'Agree'), (2,'Disagree'), ]

class VoteForm(forms.Form):
    q_id = forms.CharField(label='Question code', max_length=2)
    rating = forms.IntegerField(label='How do you feels',
    widget=forms.RadioSelect(choices=VOTE_CHOICES))

If you want a hidden field

from django import forms

class VoteForm(forms.Form):
    q_id = forms.CharField(label='Question code', widget=forms.HiddenInput())

When you have to deal with database, for example, Questionnaire.

from django import forms
from .models import Questionnaire

class VoteForm(forms.ModelForm):
    class Meta:
            model = Questionnaire
            fields = ('q_id', 'rating' )

    q_id = forms.CharField(label='Question code', max_length=2)
    rating = forms.IntegerField(label='How do you feels')

Note, you have to import Questionnaire. Then "(forms.ModelForm):" and the "class Meta:". Here is another example

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
 class Meta:
   model = Comment
   fields = ('comment_text',)

 comment_text = forms.CharField(widget=forms.Textarea)

If you get "Meta.fields cannot be a string. Did you mean to type: ('comment_text',)?" error, it is because you did not put the comma at the end of comment_text.

The final step is to create the CGI for storing the POST request to the database.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data