Django ModelForm non-required CharField giving errors - python

I have a ModelForm for a model that has a couple of files and with every file, a type description (what kind of file it is). This description field on the model has CHOICES. I have set these file uploads and description uploads as hidden fields on my form, and not required. Now the file upload is working, but the description is giving field errors, the placeholder in the dropdown is not a valid choice, it says. That's true, but since it is not required, I would like it to just be left out of the validation and I am stuck on how.
My codes, shortened them up a bit to keep it concise.
models.py
class Dog(models.Model):
FILE_TYPE_CHOICES = [
('SB', 'Stamboom'),
('RB', 'Registratiebewijs'),
('SJP', 'SJP-diploma'),
('CDD', 'CDD-diploma'),
('WT', 'Workingtestdiploma'),
('MISC', 'Overig'),
]
dog_id = models.UUIDField(unique=True, default=uuid.uuid4)
file_1 = models.FileField(upload_to=user_directory_path, blank=True, validators=[extension_validator])
desc_1 = models.CharField(choices=FILE_TYPE_CHOICES, blank=True, max_length=5)
forms.py (I excluded all these fields from the model-code above to keep it more clear, but this is to demonstrate that these fields are not required. If I print the required attribute of 'desc_1' in the view, it also says false
class DogForm(ModelForm):
class Meta:
model = Dog
fields = ('stamboomnummer', 'stamboomnaam', 'date_of_birth', 'breed',
'sex', 'sire', 'dam', 'microchip', 'breeder', 'owner',
'file_1', 'desc_1')
required = ('stamboomnummer', 'stamboomnaam', 'date_of_birth', 'breed',
'sex', 'sire', 'dam', 'microchip', 'breeder', 'owner')
widgets = {'file_1': forms.HiddenInput(),
'desc_1': forms.HiddenInput(),
}
views.py
#login_required
def newdog(request):
file_opties = Dog.FILE_TYPE_CHOICES
if request.method == 'POST':
form = DogForm(request.POST, request.FILES)
if form.is_valid():
dog = form.save(commit=False)
if request.FILES.get('file_1'):
dog.file_1 = request.FILES['file_1']
dog.user = request.user
dog.save()
assign_perm('accounts.view_dog', request.user, dog)
assign_perm('accounts.change_dog', request.user, dog)
assign_perm('accounts.delete_dog', request.user, dog)
return redirect('accounts:profile')
else:
form = DogForm()
return render(request, 'accounts/add_dog.html', {'form': form,
'buttontitle': 'Opslaan',
'formtitle': 'Hond toevoegen',
'file_type': file_opties})
My form template:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Title{% endblock %}
{% block content %}
<h2>{{ formtitle }}</h2>
<form id='hond' method="post" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form.visible_fields %}
<div class="mb-3">
{{ field.errors }}
{{ field.label }}{% if field.field.required %}*{% endif %} <br>{{ field }}
</div>
{% endfor %}
{% if form.instance.file_1 %}
{{ form.instance.get_desc_1_display }}<br>
{% endif %}
<div class="input-group mb-3">
<input class="form-control" type="file" name="file_1" id="id_file_1">
<select class="form-select" name="desc_1" id="id_desc_1">
<option selected>Type bestand</option>
{% for item in file_type %}
<option value={{ item.0 }}>{{ item.1 }}</option>
{% endfor %}
</select>
</div>
<button class="btn btn-primary" type="submit">{{ buttontitle }}</button>
</form>
<button class="btn btn-primary" style="margin-top:20px" onclick="history.back()">Annuleren</button>
{% endblock %}
This is my form HTML, with the file input and description input right on the bottom
<form id="hond" method="post" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="gxmQEruF9vTKQshK1M4YnRRg4r0X1SkzEJwbAOwQcbq1mmGvBRSC89DwmZfT6Sv7">
<div class="mb-3">
Stamboomnummer* <br><input type="text" name="stamboomnummer" class="form-control textInput" maxlength="20" required="" id="id_stamboomnummer">
</div>
<div class="mb-3">
Stamboomnaam* <br><input type="text" name="stamboomnaam" class="form-control textInput" maxlength="60" required="" id="id_stamboomnaam">
</div>
<div class="mb-3">
Geboortedatum* <br><input type="text" name="date_of_birth" class="form-control" required="" id="id_date_of_birth">
</div>
<div class="mb-3">
Ras* <br><select name="breed" class="form-select" id="id_breed">
<option value="FR" selected="">Flatcoated Retriever</option>
<option value="CBR">Chesapeake Bay Retriever</option>
<option value="CCR">Curly Coated Retriever</option>
<option value="GR">Golden Retriever</option>
<option value="LR">Labrador Retriever</option>
<option value="NSDTR">Nova Scotia Duck Tolling Retriever</option>
<option value="MISC">Ander ras, geen retriever</option>
</select>
</div>
<div class="mb-3">
Geslacht* <br><select name="sex" class="form-select" required="" id="id_sex">
<option value="" selected="">---------</option>
<option value="REU">Reu</option>
<option value="TEEF">Teef</option>
</select>
</div>
<div class="mb-3">
Vader* <br><input type="text" name="sire" class="form-control textInput" maxlength="60" required="" id="id_sire">
</div>
<div class="mb-3">
Moeder* <br><input type="text" name="dam" class="form-control textInput" maxlength="60" required="" id="id_dam">
</div>
<div class="mb-3">
Chipnummer* <br><input type="text" name="microchip" class="form-control textInput" maxlength="30" required="" id="id_microchip">
</div>
<div class="mb-3">
Fokker* <br><input type="text" name="breeder" class="form-control textInput" maxlength="50" required="" id="id_breeder">
</div>
<div class="mb-3">
Eigenaar* <br><input type="text" name="owner" class="form-control textInput" maxlength="50" required="" id="id_owner">
</div>
<div class="input-group mb-3">
<input class="form-control" type="file" name="file_1" id="id_file_1">
<select class="form-select" name="desc_1" id="id_desc_1">
<option selected="">Type bestand</option>
<option value="SB">Stamboom</option>
<option value="RB">Registratiebewijs</option>
<option value="SJP">SJP-diploma</option>
<option value="CDD">CDD-diploma</option>
<option value="WT">Workingtestdiploma</option>
<option value="MISC">Overig</option>
</select>
</div>
<button class="btn btn-primary" type="submit">Opslaan</button>
</form>
Now, form.is_valid() is False, and the form errors are:
desc_1: Selecteer een geldige keuze. Type bestand is geen beschikbare keuze.
Which means something like: Select a valid option, Type bestand (which is the placeholder text in my form) is not a valid option.
I have tried to override the clean-function but the field is not in the cleaned_data (which is logical I guess, since it's not a valid option) and I do not know how to get in before. I think I might have to define a custom field, but I cannot seem to find how to do that on a modelform with a hidden input :/ Any help would be greatly appreciated :)

Your form is submitting desc_1, so there's a an input with name="desc_1" that has a populated value of Type bestand somewhere in your template. blank=True means the value can be left empty. Since your field has choices and blank=True, the submitted value can be either empty or one of the FILE_TYPE_CHOICES.
You're saying that Type bestand is the placeholder for this field, but if you rendered this field as a hidden input ({{ form.desc_1 }} since you have a widget overridden) it would not and should not have a placeholder.
A regular form equivalent would be:
<input type="hidden" name="desc_1" value="">
Where the value attribute is either left empty or populated with one of the existing options, nothing else.
I will also add that if you're displaying desc_1 field as a <select> element, the placeholder option's value also has to be empty.
Edit
You have an option element that is selected by default. Add the disabled attribute to stop the form from submitting the placeholder text as a value for desc_1:
<option value="" selected disabled>Type bestand</option>

Related

Popup selected items from the form from python Django

I need to show the selected value from one page to another page, which means while I'm going to update my question I need to show the corresponding field to that form. Now I'm selecting the value using a drop-down list instead of that I need to the popup that value.
Django form.py
class QuestionForm(forms.ModelForm):
#this will show dropdown __str__ method course model is shown on html so override it
#to_field_name this will fetch corresponding value user_id present in course model and return it
courseID=forms.ModelChoiceField(queryset=models.Course.objects.all(), to_field_name="id")
This is my views.py
def update_question_view(request,pk):
question=QModel.Question.objects.get(id=pk)
#course=QModel.Question.objects.get(id=question.course_id)
questionForm=forms.QuestionForm(instance=question)
#CourseForm=forms.CourseForm(instance=course)
mydict={'questionForm':questionForm}
if request.method=='POST':
questionForm=forms.QuestionForm(request.POST,instance=question)
if questionForm.is_valid():
question=questionForm.save(commit=False)
course=models.Course.objects.get(id=request.POST.get('courseID'))
question.course=course
question.save()
else:
print("form is invalid")
return HttpResponseRedirect('/admin-view-question')
return render(request,'exam/update_question.html',context=mydict)
This is my models.py
class Course(models.Model):
course_name = models.CharField(max_length=50)
question_number = models.PositiveIntegerField()
def __str__(self):
return self.course_name
class Question(models.Model):
course=models.ForeignKey(Course,on_delete=models.CASCADE)
question=models.CharField(max_length=600)
option1=models.CharField(max_length=200)
option2=models.CharField(max_length=200)
option3=models.CharField(max_length=200)
option4=models.CharField(max_length=200)
status= models.BooleanField(default=False)
cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4'))
answer=models.CharField(max_length=200,choices=cat)
This is the template:
[![form method="POST" autocomplete="off" style="margin:100px;margin-top: 0px;">
{%csrf_token%}
<div class="form-group">
<label for="question">Skill Set</label>
{% render_field questionForm.courseID|attr:'required:true' class="form-control" %}
<br>
<label for="question">Question</label>
{% render_field questionForm.question|attr:'required:true' class="form-control" placeholder="Example: Which one of the following is not a phase of Prototyping Model?" %}
<br>
<label for="option1">Option 1</label>
{% render_field questionForm.option1|attr:'required:true' class="form-control" placeholder="Example: Quick Design" %}
<br>
<label for="option2">Option 2</label>
{% render_field questionForm.option2|attr:'required:true' class="form-control" placeholder="Example: Coding" %}
<br>
<label for="option3">Option 3</label>
{% render_field questionForm.option3|attr:'required:true' class="form-control" placeholder="Example: Prototype Refinement" %}
<br>
<label for="option4">Option 4</label>
{% render_field questionForm.option4|attr:'required:true' class="form-control" placeholder="Example: Engineer Product" %}
<br>
<label for="answer">Correct Answer</label>
{% render_field questionForm.answer|attr:'required:true' class="form-control" %}
<br>
<label for="answer">Question Verified{% render_field questionForm.status class="form-control" %}</label>
</div>][1]][1]

NOT NULL constraint failed: adminside_event.event_data

I have problem with my code which is i try to submit my Event form in the models. But when i run the form it will show the whole form (and another thing is that it will not show the values in the select box of the rounds) and when i click on the the submit button it will through an error.Please help me out this.
VIEW SIDE CODE:--
def addevents(request):
if request.method=="POST":
name=request.POST['events']
est=request.POST['starttime']
eet=request.POST['endtime']
s=Event()
s.ename=name
s.event_start_time=est
s.event_end_time=eet
s.save()
cats = request.POST.getlist('cats')
for i in cats:
s.categories.add(Category.objects.get(id=i))
s.save()
roundd = request.POST.getlist('rround')
for j in roundd:
s.rounds.add(Round.objects.get(id=j))
s.save()
return render(request,'adminside/addevents.html')
else:
rounds = Round.objects.all()
categories = Category.objects.all()
return render(request,'adminside/addevents.html',{'categories':categories,'rounds':rounds})
MODELS SIDE:-
class Event(models.Model):
ename=models.CharField(max_length=200)
categories = models.ManyToManyField(Category)
event_data = models.DateField()
event_start_time = models.TimeField()
event_end_time = models.TimeField()
rounds = models.ManyToManyField(Round)
EVENT PAGE FORM:-
{% extends 'adminside/master.html' %}
{% block content %}
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Events</h4>
<p class="card-description"> All fields are Compulsory </p>
<form class="forms-sample" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="exampleInputEmail1">Add Event</label>
<input type="text" class="form-control" name="events" id="exampleInputEmail1" placeholder="Enter Event">
</div>
<div class="form-group">
<label>Categories:</label>
<select class="form-control" multiple name="cats">
{% for i in categories %}
<option value="{{ i.id }}">{{ i.cname }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Event Start Time</label>
<input type="text" class="form-control" name="starttime" id="exampleInputEmail1" placeholder="Enter Event Start Time">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Event End Time</label>
<input type="text" class="form-control" name="endtime" id="exampleInputEmail1" placeholder="Enter Event End Time">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Round Name</label>
<select class="form-control form-control-lg" id="exampleFormControlSelect1" multiple name="rround">
{% for i in rounds %}
<option value="{{i.id}}">{{i.round}}</option>
{% endfor %}
</select>
</div>
<button type="submit" value=Addme class="btn btn-success mr-2">Submit</button>
<button class="btn btn-light">Cancel</button>
</form>
</div>
</div>
</div>
{% endblock %}
in addevents view you need to add something in event_data before saving because this value do not accept null or modify your models.py
event_data = models.DateField()
modify this to default value like the current time
event_data = models.DateField(default=timezone.now)
hope this helps

How to link user post with its session using flask and MongoDB?

I am trying to link users post using Flask. For instance, A user add a new product into the database from a form and it be displayed on its User template.
I don't know whether the post should be added to the database linked by user Id or I just need to use its session.
I have a simple function that I use in the form to insert the post into the collection but I don know whether I need to improve to link with the session user?
app.py:
#app.route('/insert_product', methods=['POST'])
def insert_product():
products=mongo.db.products
products.insert_one(request.form.to_dict())
return redirect(url_for('index'))
User template:
<form class="text-center border border-light p-5" action="{{url_for('insert_product')}}" method='POST'>
<p class="h4 mb-4">Add a new product</p>
<div class="form-row mb-4">
<!-- Category -->
<select class="form-control " name="category_name">
<option disabled selected>Select Category</option>
{% for cat in category %}
<option value='{{cat.category_name}}'>{{cat.category_name}}</option>
{% endfor %}
</select>
</div>
<!-- Product Name -->
<input type="text" id="product_name" name="product_name" class="form-control mb-4" placeholder="Product Name" required>
<!-- Price -->
<input type="number" min="1" step="any" id="#" name="price" class="form-control mb-4" placeholder="Price" required>
<input type="text" id="url" name="url" class="form-control mb-4" placeholder="Add Image URL"> {% if session['email'] != None %}
<input type="text" id="seller" name="seller" class="form-control mb-4" placeholder="Seller Name" value="{{session['name']}}" required> {% endif %}
<div class="form-group green-border-focus">
<textarea class="form-control" id="product_description" name='product_description' placeholder="Add product description" rows="3" required></textarea>
</div>
<!-- Sign up button -->
<button class="btn btn-info my-4 btn-block" type="submit">Submit</button>
<hr>
<!-- Terms of service -->
<p>By clicking
<em>Sign up</em> you agree to our
terms of service
</form>
I am able to display the post and all other CRUD functions. Just this small issue I would like to know to complete my project. Thank you.
I found the answer. I just needed to match the seller name into the collection with the section name using pymongo declaring it as a variable items=mongo.db.find({'seller':session.get('name')}) looping to retrieve the products/posts:
#app.route('/user')
def user():
items=mongo.db.products.find({'seller':session.get('name')})
category=mongo.db.category.find()
email = session.get('email')
if not email:
return redirect(url_for('login'))
return render_template('user.html', category=category, items=items)
Retrieving all the products done by its logged/session users:
{% for item in items%}
code here..
{% endfor %}

Radio Button with default selection in Django

I had the same doubt of radio button in model file.
I want it to be a compulsory/required field with default selection to "No".
Fields available would be - Yes/No. Any suggestions.
B_CHOICES = [('P','Positive'),('N','Negative')]
Tag_Type = models.CharField(choices=B_CHOICES, max_length=128)
Here's my form and model code-
Form -
<form id="ant_form" name="ant_form" method="POST" action="#">{% csrf_token %}
<input name="r_user" type="checkbox" value="{{user.id}}" /> {{user.username}}
<input type="radio" name="txt{{user.id}}" value="P" > </input>
P Comment
<input type="radio" name="txt{{user.id}}" value="N" > </input>
N Comment
<textarea style="height: auto" rows="1" id="txt{{user.id}}" name="comment_{{user.id}}" cols="50">
</textarea>
<br>
</li>
{% endfor %}
</ul>
</div>
{% endif %} {# users #}
</form>
Model -
class r(models.Model):
BCHOICES = [('P','P'),('N','N'),]
tag_type = models.CharField(max_length=2, default=Negative, choices=BCHOICES)
You can set the default to 'N':
from django.db import models
B_CHOICES = [('P','Positive'),('N','Negative')]
class MyModel(models.Model):
tag_type = models.CharField(choices=B_CHOICES, max_length=128, default='N')
When you render a ModelForm for the given MyModel, then the HTML will look like:
<select name="tag_type" id="id_tag_type">
<option value="P">Positive</option>
<option value="N" selected>Negative</option>
</select>

Can't render django-countries-plus options in form template

For some reason I can't get the list of Countries in django-countries-plus to render in my template.
The table is imported fine under Countries Plus > Countries and I've set the models.py up as follows:
from countries_plus.models import Country
class Project(models.Model):
title = models.CharField(max_length=500)
status = models.BooleanField(default=True)
location = models.CharField(max_length=500)
projectcountry = models.ForeignKey(Country)
Then added the new field projectcountry to the form on forms.py:
from django.forms import ModelForm
from .models import Project, Proposal
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['title', 'status', 'location', 'projectcountry']
Then in the template I'm trying to bring in the 252 countries in the table to render in a Bootstrap dropdown:
<form class="form-horizontal" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="col-sm-2 control-label">PROJECT TITLE</label>
<div class="col-sm-6">
<textarea rows="1" class="form-control" name="title"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">STATUS</label>
<div class="col-sm-6">
<select name="status" class="form-control">
<option value="1">Active</option>
<option value="0">Disabled</option>
</select>
</div>
<div class="col-sm-4">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">CITY / TOWN</label>
<div class="col-sm-6">
<textarea rows="1" class="form-control" name="location"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">COUNTRY</label>
<div class="col-sm-6">
<select name="projectcountry" class="form-control">
{% for country in countries %}
<option value="{{ country.iso }}">{{ country.name }}</option>
{% endfor %}
</select>
</div>
<div class="col-sm-4">
</div>
</div>
</form>
Can you see what I'm doing wrong? I've been struggling with this researching all day but not cracked it.

Categories