Django - form field does not pass validation - django

models.py
class Location(models.Model):
name = models.CharField(max_length=100, verbose_name=u"Локация", default=u'')
country = models.ForeignKey("Country")
class Country(models.Model):
name = models.CharField(max_length=50, verbose_name=u"Страна")
class Photo(models.Model):
location = models.ForeignKey(Location, null=True, verbose_name=u'Фото')
photo = models.ImageField(upload_to='photos', null=True)
forms.py
class LocationForm(forms.ModelForm):
class Meta:
model = Location
fields = ['name', 'country']
photos = MultiFileField(min_num=1, max_num=10)
def save(self, commit=True):
instance = super(LocationForm, self).save(commit)
for each in self.cleaned_data['photos']:
Photo.objects.create(photo=each, location=instance)
return instance
views.py
class AddLocationPageView(CreateView):
model = Location
form_class = LocationForm
template_name = 'add_location.html'
class BrowseLocationsPageView(ListView):
model = Country
context_object_name = 'countries'
template_name = "browse_locations.html"
add_location.html
<form action="" method="POST">{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-default" type="submit">Add</button>
</form>
browse_locations.html
{% for country in countries %}
{{ country }}
{% endfor %}
While creating Location object the form field says: "Select a valid choice. That choice is not one of the available choices."
Of course, I do not have any choices, because the design is - if Country is absent in DB, it has to be created during Location creating, and in opposite case (Country is in DB, because someone created it before when he was creating Location) it has to be joined to Location.

Related

Url not being resolved in, 404 error django

I am not able to create an detail and update view using the <pk> and <pk>/update/, this is my url paths.
urlpatterns = [
path('',views.IndexView.as_view(), name='index'),
path('form/',views.CompanyView.as_view(),name='company'),
path('toy/',views.ToyView.as_view(),name='toy'),
path('int:pk>/',views.CompanyDetailView.as_view()),
path('int:pk>/update/',views.CompanyUpdateView.as_view())
]
my views looks like this,
class CompanyUpdateView(generic.UpdateView):
model = Company
fields = '__all__'
success_url = '/company'
class CompanyDetailView(generic.DetailView):
model = Company
fields = '__all__'
class CompanyView(generic.CreateView):
model = Company
template_name = 'company/company.html'
fields = '__all__'
success_url = '/company'
models.py is
class Company(models.Model):
company_name = models.CharField(max_length=50)
location = models.CharField(max_length=50)
email_id = models.EmailField()
def __str__(self):
return self.company_name
class Toys(models.Model):
toy_name = models.CharField(max_length=50)
company = models.ForeignKey(Company,on_delete=models.CASCADE,blank=True,null=True)
price = models.IntegerField()
This is the template used to in the CreateView and UpdateView since I am using a ModelForm
<form method="post">
{% csrf_token %}
<fieldset>
<legend>
<h2> Company Form </h2>
</legend>
{{ form.as_p }}
</fieldset>
<input type="submit" value="Submit" />
</form>
Create view is working. When I got to a url company/1/ or company/1/update I get a 404 error. What would be the reason for it and how to solve this

form not saving data in db

i'm creating a form for product create and i have 5 image fields in product model ,user can upload 5 or 0 images as per requirement , but form is not saving data
python
models.py
class Category(models.Model):
cate_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=45)
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length=45)
product_description = models.CharField(max_length=500, blank=True, null=True)
price = models.IntegerField()
quantity = models.IntegerField()
product_category_fk = models.ForeignKey('Category', on_delete=models.CASCADE,db_column='product_category_fk',related_name='pros')
image1 = models.ImageField(upload_to='chand_imgs',blank=True)
image2 = models.ImageField(upload_to='chand_imgs',blank=True)
image3 = models.ImageField(upload_to='chand_imgs',blank=True)
image4 = models.ImageField(upload_to='chand_imgs',blank=True)
image5 = models.ImageField(upload_to='chand_imgs',blank=True)
#forms.py
class CategoryForm(forms.ModelForm):
category_name = forms.CharField(max_length=50)
class Meta:
model = Category
fields = ('category_name', )
class ProductForm(forms.ModelForm):
class Meta():
model = Product
fields = ('product_category_fk','product_name','product_description','price','quantity','image1','image2','image3','image4','image5',)
#views.py
#login_required
def product_management(request):
form = ProductForm(data=request.POST)
if request.method =='POST':
if form.is_valid():
post=form.save(commit=True)
if 'picture' in request.FILES:
form.picture =request.FILES['picture']
return HttpResponseRedirect(reverse('index'))
else:
return render(request,'chandler/index.html',{'form':form})
else:
form = ProductForm()
return render(request,'chandler/product.html',{'form':form})
#product.html
{% if user.is_authenticated %}
<form method=”post” enctype=”multipart/form-data” action="" >
<h2>New post</h2>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% else %}
<h2>Please login first!!!!</h2>
{% endif %}
form not saving any data i know my view is incorrect ,already tried different methods
change
<form method=”post” enctype=”multipart/form-data” action="" >
to
<form method="post" enctype="multipart/form-data" action="" >

Django Formset issue - POST doesn't seems to work

I'm trying to use django formset for the first time in order to combine both forms on the same page.
My form is well displayed but I don't overvome to save data in my database. When I click on submit button, nothing happens.
This is my model.py file :
class Publication(models.Model):
title = models.CharField(max_length=512, verbose_name=_('title'), null=False)
category = models.ForeignKey(Category, verbose_name=_('category'), null=False)
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False)
modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False)
class Meta:
verbose_name = _('publication')
verbose_name_plural = _('publication')
def __str__(self):
return f"{self.title}"
class Document(models.Model):
FORMAT_CHOICES = (
('pdf', 'pdf'),
('epub', 'epub'),
)
format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False)
title = models.CharField(max_length=512, verbose_name=_('title'), null=False)
publication = models.ForeignKey(Publication, verbose_name=_('publication'), null=False)
upload = models.FileField(upload_to='media/', default="")
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False)
modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False)
class Meta:
verbose_name = _('document')
verbose_name_plural = _('document')
def __str__(self):
return f"{self.age_id} : {self.title}"
My form file is very simple too with defined Formset :
class PublicationForm(forms.ModelForm):
class Meta:
model = Publication
fields = ('title', 'category')
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ['publication', 'format', 'title', 'upload']
DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1)
My view is a bit more complicated :
class PublicationCreateUpdateView(AgePermissionRequiredMixin, UpdateView):
""" Display a form to create or update a publication
Only for age admin.
**Context**
``subtitle``
Title of the page
**Template:**
:template:`app/category_form.html`
"""
model = Publication
form_class = PublicationForm
success_url = reverse_lazy('app:app-publication-list')
template_name = 'app/publication_form.html'
permission_required = 'publication.change_webapplication'
def get_object(self, queryset=None):
try:
return super(PublicationCreateUpdateView, self).get_object(queryset)
except AttributeError:
return None
def get_title(self):
if self.object:
return _('Edit publication: ') + str(self.object)
return _('Add new publication')
def get_context_data(self, **kwargs):
context = super(PublicationCreateUpdateView, self).get_context_data(**kwargs)
if self.request.POST :
context['documents'] = DocumentFormSet(self.request.POST)
else :
context['documents'] = DocumentFormSet()
context.update({
'subtitle': self.get_title(),
})
return context
def form_valid(self, form):
context=self.get_context_data()
documents = context['documents']
with transaction.atomic():
self.object = form.save()
if documents.is_valid():
documents.instance = self.object
documents.save()
return super(DocumentCreateUpdateView, self).form_valid(form)
And finally my template looks like this :
{% extends "publication/base_backend.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block main %}
<form method="post" novalidate>
{% csrf_token %}
{% crispy form %}
{{ documents.management_form }}
{{ documents.non_form_errors }}
{% crispy documents %}
<br>
<input type="submit" class="btn btn-default" value="{% trans 'Save' %}" />
{% trans 'Cancel' %}
</form>
{% endblock main %}
I don't understand where I could make a mistake, furthermore I'm pretty new with Django Class Based View.

NOT NULL constraint failed: cars_car.owner_id

I was able to render the form onto the html, input data and submit it but i got a NOT NULL constraint failure. Isn't the owner assigned to its respective owners when as i have indicated in my views? i do not know what is wrong here please help!
Models
class Car(models.Model):
owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
model = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now_add=False)
mileage = models.IntegerField()
open_market_value = models.DecimalField(max_digits=12, decimal_places=2)
depreciation = models.DecimalField(max_digits=10, decimal_places=2)
down_payment = models.DecimalField(max_digits=10, decimal_places=2)
road_tax = models.DecimalField(max_digits=8, decimal_places=2)
installment = models.DecimalField(max_digits=8, decimal_places=2)
objects = models.Manager()
def __str__(self):
return self.name
Views
class CarCreate(CreateView):
model = Car
fields = [
'name', 'model',
'description', 'image',
'updated', 'mileage',
'open_market_value', 'depreciation',
'down_payment', 'road_tax',
'installment']
template_name = 'cars/create_car.html'
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
HTML
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<!-- Default form contact -->
<form action="{% url 'cars:create' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form | crispy}}
<input type="submit" value="save">
</form>
<!-- Default form contact -->
{% endblock %}
Your model has a foreign key to the User model from 'django.auth'. While you are trying to save the object of 'Car' model as there was no object mentioned for the 'owner' field of the model, it is showing the error. So, you might want to explicitly mention it.
You can do something like this. Assuming that you have 'CarForm', a model form for you 'Car' model.
user = request.user
car_form = CarForm(request.POST)
if car_form.is_valid():
car = car_form.save(False)
car.owner = user
car.save()
This is most likely because owner is a required field in your model Car but you have not included it in the fields in your CreateView.

django form how to render the fields

I'm trying to render a form but the fields are not displayed in the HTML.
views.py
#url(r'^boxes/(?P<pk>[0-9A-Za-z-]+)/$', views.show_form, name='box'),
def show_form(request, pk):
box = Box.objects.get(pk=pk)
form = SuggestionForm()
context = {
'box':box,
'form':form
}
return render(request, 'boxes/detail.html', context)
forms.py
class SuggestionForm(ModelForm):
class Meta:
model = Suggestion
fields = ['comment']
detail.html
<h3>{{box.title}}</h3>
<form action="." method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-info" value="Add suggies" />
</form>
My models.py
#python_2_unicode_compatible
class Suggestion(models.Model):
"""
For adding comments (or suggestions)
"""
def __str__(self):
return self.comment[0:10]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
comment = models.CharField("",max_length=250, blank=True, null=True)
box = models.ForeignKey(Participant, on_delete=models.CASCADE)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
The result HTML.. There is no fields in this form. I want to use a function based view.