Django: may not be NULL when submitting a form - python

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">

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]

Django multiple radio input from HTML form with same name

I am having a problem with Django forms. I am currently using the request.POST to validate the POST within views.
I want to send inputed-data(radio type) from my template with the same name.
In my template.py:
<form method="post" action="{% url 'app:AnsSubmission' %}">
{% csrf_token %}
{% for i in Exam %}
<div class="form-group col-xl-12">
<label>{{ i.question }}</label>
<div class="radio">
<label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="True" required>True</label>
</div>
<div class="radio">
<label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="False" required>False</label>
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And willing to fetch these data in views.py like:
givenAns_list = request.POST.getlist('givenAns')
for i in givenAns_list:
this_givenAns = givenAns_list[i]
But the problem here is this radio type input field doesn't take value for the same name(not as a list I wish). If I select answer of 2nd question, the 1st one's selection is unselected.
Please suggest how can I fix this?

How can I give an error when someone edits there profile and changes the email to an email that already exists using django?

I want to give an error that an account with a email already exists, but it doesn't seem to work when a user edits there profile. Also, if the email isn't valid when submitting the form it it gives a value error: "The view accounts.views.edit_profile didn't return an HttpResponse object. It returned None instead."
Here is the code:
{% extends 'base.html' %}
{% block head %}
<link href="\static\accounts\css\forms.css" rel="stylesheet">
{% endblock %}
{% block body %}
<h3 style="text-align: center">Edit profile</h3>
<form id="login-form" method="post">
{% csrf_token %}
<input placeholder="Email" id="id_email" name="email"
type="text" class="form-control" value="{{ user.email}}">
<input placeholder="First name" id="id_first_name" name="first_name"
type="text" class="form-control" value="{{ user.first_name}} ">
<input placeholder="Last name" id="id_last_name" name="last_name"
type="text" class="form-control" value="{{ user.last_name}}">
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<p class=" label label-danger">
<div style="text-align: center">
{{ error }}
</div>
</p>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error }}</strong>
</div>
{% endfor %}
{% endif %}
<div style="text-align:center;">
<button type="submit" class="btn btn-outline-dark centerbutton">Save edits</button>
</div>
</form>
{% endblock %}
Also, here is the code I used to check if the email exists in the registration form, but it doesn't seem to work for the edit profile form:
def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')
if email and User.objects.filter(email=email).exclude(username=username).exists():
raise forms.ValidationError(u'An account with this email address already exists')
return email
And my editprofileform:
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name',
'password'
)
This is too large of a question to answer on here and I won't be posting any code for you. You will need to read some docs and work on it yourself.
Checking that email already exists... you will likely have to go to your database or for that. Enforcing that an email column be unique in your database is a good way to handle this. You can catch the database errors and handle them as you like.
As for the valid email validation, you will want to use Django's validators. One of the validators is specifically for checking valid email format.
https://docs.djangoproject.com/en/2.2/ref/validators/#emailvalidator

Error with Django Template rendering No Reverse Match

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! :)

How to pass data from HTML form to Database in Django

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! :)

Categories