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]
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>
Can anyone help me with this issue? I saw all posts which are similar to my issue, but I can't fix this up.
Error:
Reverse for 'commit_add' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['git/project/(?P<pk>[0-9]+)/add_commit/$']
views.py
class CommitCreate(CreateView):
template_name = 'layout/project_commit_detail.html'
model = Commit
fields = ['user', 'project', 'branch', 'commit_title', 'commit_body']
success_url = reverse_lazy('git_project:index')
html form
<div class="container-fluid">
Add New Commit
<div id="demo1" class="collapse" >
<form class="form-horizontal" action="{% url 'git_project:commit_add' project.id %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% if user.is_authenticated %}
<label for="user">Commit created by: "{{ user.username }}"</label><br>
<input id="user" type="hidden" name="user" value="{{ user.id }}">
<label for="project">Commit for project: "{{ project.proj_title }}"</label><br>
<input id="project" type="hidden" name="project" value="{{ project.id }}">
<label for="branch">Branch: </label>
<select>
{% for branch in all_branches %}
<option id="branch" name="branch">{{branch.branch_name}}</option>
{% endfor %}
</select><br>
<label for="commit_title">Commit Title: </label>
<input id="commit_title" type="text" name="commit_title"><br>
<textarea id="commit_body" name="commit_body" rows="5" cols="50" placeholder="Commit body..."></textarea><br>
<button type="submit" class="btn btn-success">Commit</button>
{% endif %}
</form>
</div>
url.py
url(r'project/(?P<pk>[0-9]+)/add_commit/$', views.CommitCreate.as_view(), name='commit_add'),
model.py
class Commit(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=0)
project = models.ForeignKey(Project, on_delete=models.CASCADE, default=0)
branch = models.ForeignKey(Branch, on_delete=models.CASCADE, default=0)
commit_title = models.CharField(max_length=64)
commit_body = models.CharField(max_length=16384)
commit_date = models.DateTimeField(default=timezone.now)
I don't know why is happening. Can anyone help me? I am very new in Django.
Thanks! :)
Can you help me with this issue? I want to pass data from HTML form to Database.
This is my HTML form:
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% if user.is_authenticated %}
<label for="username">Username: </label>
<input id="username" type="text" name="username" value="{{ user.username }}" disabled><br>
<label for="image">Image: </label>
<input id="image" type="file" name="image">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Save Changes</button>
</div>
</div>
{% endif %}
</form>
And this is my Views.py
class CreateProfile(CreateView):
template_name = 'layout/add_photo.html'
model = Profile
fields = ['image', 'user']
success_url = reverse_lazy('git_project:index')
When I fill in the form (username is equal to logged in username, and chose an image) and when I click "Save Changes", the data has to be passed in Database in table Profile. Here is class Profile in models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.FileField()
I know this is basic, but I don't know how to fix it up, so please, help! :)
I'm trying to submit a form with just the date(and now time), but when I go to submit it I get the error incidents_incident.incident_date_time_occurred may not be NULL even when I enter an actual date in the input field. Why do I get that error when I enter in a date?
models.py
class Incident(models.Model):
incident_date_time_occurred = models.DateTimeField('incident occurred', default=timezone.now, blank=True)
class Meta:
verbose_name_plural="Incident"
forms.py
class IncidentForm(forms.ModelForm):
class Meta:
model = Incident
fields = ('incident_date_time_occurred',)
report.html
{% extends "base.html" %}
{% block content %}
<div class="container-fluid">
<form action="{% url 'incidents:report' %}" method="POST">{% csrf_token %}
{% csrf_token %}
<div class="row">
<div class="form-group col-md-4">
<label for="date" class="col-sm-4 control-label">{{ form.incident_date_time_occurred.label }}</label>
<input type="datetime-local" name= "incident_date_time_occurred" class="form-control" id="date">
</div>
</div>
<input type="submit" value="Inschrijven!" class="btn btn-primary" />
</form>
</div>
{% endblock %}
Can you check your solution by using default form created from incident? As I remember Django's dateTimeField requires two fields: date and time.
https://docs.djangoproject.com/en/1.7/ref/models/fields/#datetimefield
You are missing the name attribute on the date input. Try that:
<input type="date" class="form-control" id="date" name="incident_date_time_occurred">