Creating a chained drop down following a tutorial. Everything works fine but it is throwing an unnecessary validation error.
It is a basic 3 field form creating a person object with name, country and city.
Views.py
from django.shortcuts import render, redirect, get_object_or_404
from .forms import CustomerForm
from .forms import PersonCreationForm
from .models import Person, City
def store(request):
form = CustomerForm()
context = {'form': form}
return render(request, 'store/store.html', context)
def cart(request):
form = CustomerForm()
context = {'form': form}
return render (request, 'store/cart.html', context)
def checkout(request):
form = CustomerForm()
context = {'form': form}
return render(request, 'store/checkout.html', context)
def signup(request):
context = {}
return render(request, 'store/signup.html', context)
def home(request):
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
pass # does nothing, just trigger the validation
else:
form = CustomerForm()
return render(request, 'shop.html', {'form': form})
def person_create_view(request):
form = PersonCreationForm()
if request.method =='POST':
form = PersonCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('person_add')
return render(request, 'store/ho.html', {'form': form})
def person_update_view(request, pk):
person = get_object_or_404(Person, pk = pk)
form = PersonCreationForm(instance = person)
if request.method == 'POST':
form = PersonCreationForm(request.POST, instance=person)
if form.is_valid():
form.save()
return redirect('person_change', pk = pk)
return render(request, 'store/ho.html', {'form': form})
#ajax
def load_cities(request):
country_id = request.GET.get('country_id')
cities = City.objects.filter(country_id = country_id)
return render(request, 'store/city_dropdown_list_options.html',{'cities':cities})
Forms.py
from django.forms import ModelForm
from .models import Customer, Person, City
from django import forms
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = '__all__'
class PersonCreationForm(forms.ModelForm):
class Meta:
model = Person
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['city'].queryset = City.objects.none()
if 'country' in self.data:
try:
country_id = int(self.data.get('country'))
self.fields['city'].queryset = City.objects.filter(country_id = country_id)
except(ValueError, TypeError):
pass
elif self.instance.pk:
self.fields['city'].queryset = self.instance.country.city_set.order_by('name')
In forms.py line 14 where it says-
self.fields['city'].queryset = City.objects.none()
this line is throwing a validation error when I try to submit the form. In the tutorial they add the if/else argument and that solves the problem and error goes away.
error: "Select a valid choice. That choice is not one of the available choices"
In my case the error still shows up. If I ignore it and re select the city and submit, it works just fine.
It is almost like having a pause at that line and the system suddenly realizes that there is more code.
How do I fix this problem. Appreciate any help.
Related
from django import forms
from .models import Blog
I just rewrite code this point,
from ↓:
# class BlogPost(forms.ModelForm):
# class Meta:
# model = Blog
# fields = ['title', 'body']
to ↓:
class BlogPost(forms.Form):
email = forms.EmailField()
files = forms.FileField()
url = forms.URLField()
words = forms.CharField(max_length=200)
max_number = forms.ChoiceField(choices=[('1','one'), ('2','two'),('3','three')])
and views.py file is here ↓:
from django.shortcuts import render, get_object_or_404, redirect
from .models import Blog
from django.utils import timezone
from .form import BlogPost
from django.views.decorators.http import require_http_methods
# Create your views here.
def home(request):
blogs = Blog.objects #쿼리셋
return render(request, 'home.html', {'blogs'`enter code here`:blogs})
def detail(request, blog_id):
details = get_object_or_404(Blog, pk=blog_id)
return render(request, 'detail.html', {'details':details})
def new(request):
return render(request, 'new.html')
def create(request):
blog = Blog()
blog.title = request.GET['title']
blog.body = request.GET['body']
blog.pub_date = timezone.datetime.now()
blog.save()
return redirect('/blog/'+str(blog.id)) #이 URL로 넘기세요 처리된 정보를
def blogpost(request):
if request.method =='POST':
form = BlogPost(request.POST)
if form.is_valid():
post = form.save(commit=False)
# post.pub_date = timezone.now()
post.save()
return redirect('home')
else:
form = BlogPost()
return render(request, 'newblog.html',{'form':form})
I don't know why I only rewrite 'form.py' file, but vscode program says "The view blogapp.views.blogpost didn't return an HttpResponse object. It returned None instead."
what should I do?? help..
def blogpost(request):
if request.method =='POST':
form = BlogPost(request.POST)
if form.is_valid():
post = form.save(commit=False)
# post.pub_date = timezone.now()
post.save()
return redirect('home')
else:
form = BlogPost()
return render(request, 'newblog.html',{'form':form})
You don't have a return statement on here due to your if statement and indentation.
Write it like:
def blogpost(request):
if request.method =='POST':
form = BlogPost(request.POST)
if form.is_valid():
post = form.save(commit=False)
# post.pub_date = timezone.now()
post.save()
return redirect('home')
else:
form = BlogPost()
return render(request, 'newblog.html',{'form':form})
And it should work.
I'm making a registration system for students in Django
When the user enters the student number, the system retrieves all the student data.
How can I work in this
def search(request):
if request.method== 'POST':
srch = request.POST['srh']
if srch:
match = Regiest_Form.objects.filter(Q(std_name__iexact=srch))
if match:
return render(request, 'Regiest_app/search.html', {'sr':match})
else:
messages.error(request,'no result')
else:
return HttpResponseRedirect('/search/')
else:
return render(request, 'Regiest_app/search.html')
Wow, you're missing a whole part of django's purpose.
Using django's form, you can delegate all your validation to your form.
If no results are found, your access errors using 'form.errors' and 'form.non_field_errors` within your template.
In forms.py
from django import forms
from .models import Regiest_Form
class RegisterSearchForm(forms.Form):
search=forms.Charfield(required=True)
def clean(self):
qs=Regiest_Form.objects.filter(Q(std_name__iexact=self.cleaned_data.get('search'))
if qs.exists():
self.add_error(field=None,error=forms.ValidationError("No results found"))
else:
return self.cleaned_data
#property
def results(self):
return Regiest_Form.objects.filter(Q(std_name__iexact=self.cleaned_data.get('search'))
In your views.py
from .forms import RegisterSearchForm
def search(request):
form = RegisterSearchForm(request.POST) if request.method== 'POST' else RegisterSearchForm()
if request.method== 'POST' and form.is_valid():
return render(request, 'Regiest_app/search.html',{'sr':forms.results, 'form':form})
return render(request, 'Regiest_app/search.html',{'form':form})
I have my response form and view like this
class ResponseForm(ModelForm):
class Meta:
model = ResponseModel
exclude = ('author', 'title','submit_count')
# help_texts = {
# 'ans1': user.q1.value,
# }
#login_required
def ResponseFormView(request):
if request.method == "POST":
form = ResponseForm(request.POST)
if form.is_valid():
submission = form.save(commit=False)
submission.author = request.user
submission.save()
return render(request, 'thanks.html', {})
else:
form = ResponseForm()
return render(request, 'response_tem.html', {'form': form})
I want the help text for 'ans1' field to be the value of q1 field of request.user. How do I do it?
You can do it like this:
class ResponseForm(ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None) # popping user from known arguments
super(ResponseForm, self).__init__(*args, **kwargs)
if user:
self.fields['ans1'].help_text = "Help Text for {}".format(user.username)
class Meta:
model = ResponseModel
exclude = ('author', 'title','submit_count')
#login_required
def ResponseFormView(request):
if request.method == "POST":
form = ResponseForm(request.POST)
if form.is_valid():
submission = form.save(commit=False)
submission.author = request.user
submission.save()
return render(request, 'thanks.html', {})
else:
form = ResponseForm(user=request.user) # passing user as known argument
return render(request, 'response_tem.html', {'form': form})
Here, in the view I am passing the request.user as known argument when I am initiating Form Class's Object (marked with comment). Then in the Form, I am catching the user sent from view and updating the field's help text.
I am making a form using Django 2.0.x and Python 3.6 and I am getting an error
I'm not sure what's going on, can someone help me out? Thanks!
Product/forms.py
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
title = forms.CharField(label='',
widget=forms.TextInput(attrs={"placeholder": "Your title"}))
description = forms.CharField(
required=False,
widget=forms.Textarea())
class Meta:
model = Product
fields = [
'title',
'description',
]
Product/views.py
from django.shortcuts import *
from django.http import *
from .models import Product
from .forms import ProductForm
import hashlib
# Create your views here.
def home_view(request,slug,*args,**kwargs):
form= ProductForm(request.POST or None)
try:
productobject=Product.objects.get(id=1)
except Product.DoesNotExist:
raise Http404
if form.is_valid():
newProduct=Product.objects.create(
title = "jose",
description=ProductForm.cleaned_data.get["description"]
)
if newProduct:
return HttpResponseRedirect("/)
else:
newProduct = ProductForm()
context= {
"sampletext": "text",
"form": form,
"productobject":productobject,
}
return render(request, "home.html",context)
The code is giving me this error
type object 'ProductForm' has no attribute 'cleaned_data'
You fetch the cleaned_data from the ProductForm class, not from the form object that is an instance of ProductForm.
You can thus fix it by using form instead, like:
def home_view(request,slug,*args,**kwargs):
form= ProductForm(request.POST or None)
try:
productobject=Product.objects.get(id=1)
except Product.DoesNotExist:
raise Http404
if form.is_valid():
newProduct=Product.objects.create(
title = "jose",
description=form.cleaned_data.get["description"]
)
if newProduct:
return HttpResponseRedirect("/")
else:
newProduct = ProductForm()
context= {
"sampletext": "text",
"form": form,
"productobject":productobject,
}
return render(request, "home.html",context)
But that being said, the workflow is not idiomatic. For example if newProduct will always succeed, regardless whether this is a valid newProduct or not. The Product.objects.create(..) however can raise an exception. A more idiomatic workflow is:
def home_view(request,slug,*args,**kwargs):
try:
productobject=Product.objects.get(id=1)
except Product.DoesNotExist:
raise Http404
if request.method = 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.instance.title = "jose"
form.save()
return redirect('home') # name of the view
else:
form = ProductForm()
context= {
"sampletext": "text",
"form": form,
"productobject":productobject,
}
return render(request, "home.html",context)
Django form validation is not working. It only prints the following message:
form is not valid!
I am a Django beginner and I am having trouble figuring out why this is happening.
mycode in form.py:
efrom django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.forms.widgets import CheckboxSelectMultiple
from blog.models import Category
from wsgiref.validate import validator
class PostForm(forms.Form):
title = forms.CharField(max_length = 100, min_length= 1,)
slug = forms.SlugField(allow_unicode=True)
message = forms.CharField(widget = forms.Textarea)
banner = forms.ImageField()
category = forms.ModelChoiceField(queryset=Category.objects)
authors = forms.ModelChoiceField(queryset=User.objects,
widget=CheckboxSelectMultiple)
def clean(self):
cleaned_data = super(PostForm, self).clean()
slug = cleaned_data['slug']
if not "sepehr" in slug:
raise forms.ValidationError("here we have some errors !")
return cleaned_data
and my code in views:
class HoemView(generic.TemplateView):
template_name = 'blog2/create.html'
def get(self, request):
form = PostForm()
context = {
'form':form
}
return render(request, self.template_name, context)
def post(self, request):
form = PostForm(request.POST, request.FILES)
if form.is_valid():
return HttpResponse('form is valid!')
return HttpResponse('form is not valid!')
All you are seeing is 'form is not valid!' because that is all your view is returning in the HttpResponse.
Change the last line from:
return HttpResponse('form is not valid!')
to:
return HttpResponse(form.errors)
That should show you what your errors are.