I’m facing 2 problems when creating Form in Django:
- Problem on redirect after submitting Form
- Model object is not iterable
Specifically, I’m creating feedback form and all my code is as below. There are 4 files and using crispy_form
to show the form in html file. Everything works fine except after I click on submit button. It cannot return to the same feedback form with blank fields, and it shows the error 'BugTypes' object is not iterable
Please check and help. Thank you!
# models.py
from django.db import models
# Create your models here.
class BugTypes(models.Model):
bugType = models.CharField(max_length=100)
def __str__(self):
return self.bugType
class UserFeedback(models.Model):
username = models.CharField(max_length=100)
problem = models.CharField(max_length=255)
bugType = models.ManyToManyField("BugTypes", related_name='userFeedBack')
feedback = models.TextField()
def __str__(self):
return self. Problem
# forms.py
from django import forms
from survey.models import UserFeedback, BugTypes
class FeedbackForm(forms.ModelForm):
username = forms.CharField(
widget = forms.TextInput(
attrs={'class': 'form-control'}
)
)
problem = forms.CharField(
widget = forms.TextInput(
attrs = {'class': 'form-control'}
)
)
bugType = forms.ModelChoiceField(
queryset = BugTypes.objects.all(),
widget = forms.Select(
attrs={'class': 'form-control'}
))
feedback = forms.CharField(
widget = forms.Textarea(
attrs = {'class': 'form-control'}
))
class Meta:
model = UserFeedback
fields = "__all__"
# views.py
from django.shortcuts import render
from django.urls import reverse
from django.views.generic.edit import CreateView
from survey.forms import FeedbackForm
from survey.models import UserFeedback
# Create your views here.
class UserFeedbackView(CreateView):
model = UserFeedback
form_class = FeedbackForm
success_url = '/survey/feedback/'
userFeedback_view = UserFeedbackView.as_view(template_name = "survey/user_feedback.html")
# urls.py
from django.urls import path
from survey.views import userFeedback_view
app_name = 'survey'
urlpatterns = [
path('feedback', view = userFeedback_view, name='userFeedback')
]