No update of database with UpdateView django - python

I know my code is not optimal as I'm only a beginner with Django so don't be too hard on me
Here is my code :
views.py
class ComposantUpdate(UpdateView):
model = configuration
fields = '__all__'
template_name = 'accueil/exploitation/update_composant.html'
update_composant.html
<form action="{% url 'composant_update' pk=composant.id %}" method="post">
{% csrf_token %}
<div class="form-group">
{% for field in form %}
<label class="col-md-6 offset-md-3 nom_champ"> {{field.label_tag}}</label>
<input class="col-md-4 offset-md-4 contenu_champ" type="text" name="{{ field.label }}" id="{{ field.id_for_label }}" value="{{ field.value }}"/>
{%endfor%}
<br>
<br>
<button class="col-md-6 offset-md-3 btn btn-primary" type="submit" value="Update" /> Mettre à jour </button>
</div>
</form>
urls.py
path('update_composant/<int:pk>', views.ComposantUpdate.as_view(),
name='composant_update'),
models.py
class configuration(models.Model):
Num_ordre = models.CharField(max_length=15)
Composant = models.CharField(max_length=15)
Designation = models.CharField(max_length=15)
Qte_servie = models.IntegerField()
Qte_a_servir = models.IntegerField()
Lot = models.CharField(max_length=15)
Categorie = models.CharField(max_length=15)
Famille = models.CharField(max_length=15)
def __str__(self):
return '%s %s %s' % (self.Num_ordre, self.Designation, self.Lot)
when I go to the url of the form, all the fields get the content of the database which is what I expect but if I modify the "Lot" field and click to submit, my database is not updated at all with the new value of "Lot". DO you have any idea of why ? For information, I do get redirected to the 'composant_update' view and no error is risen

In fact, I didn't write my html correctly, the attribute "name" in the input should have been {{field.html_name}} instead of {{field.label}}.
This doesn't work :
<input class="col-md-4 offset-md-4 contenu_champ" type="text" name="{{ field.label }}" id="{{ field.id_for_label }}" value="{{ field.value }}"/>
This works :
<input class="col-md-4 offset-md-4 contenu_champ" type="text" name="{{ field.html_name}}" id="{{ field.id_for_label }}" value="{{ field.value }}"/>
See https://docs.djangoproject.com/en/2.0/topics/forms/#s-looping-over-the-form-s-fields for more information
Thanks Willem Van Onsem !

Related

How to display single/particular data record from database -django

I want to display a particular data record from the database of a person who is logged in to the website. I have a default primary key in the migration. Other than that I don't have any of the primary or foreign keys. Below is the models.py and template codes.
models.py
class Ticket(models.Model):
Email = models.CharField(max_length=40)
to = models.CharField(max_length=40)
cc = models.CharField(max_length=50)
subject = models.CharField(max_length=25)
class Meta:
db_table = 'ticket'
def __str__(self):
return self.Email
Following is the views which I had used before, that display's the whole data from the database.
Views.py
def ticket(request):
ticket = Ticket.objects.all()
return render(request, 'web/ticket.html', {'ticket':ticket})
But I want to display data of the respective mail id
ticket.html
{% for ticket in ticket %}
<fieldset id="first">
<label for="From"><b>From</b></label>
<input type="text" id="From" name="From" style="width:100%" value="{{ ticket.Email }}" required> <br> <br>
<label for="To"><b>To</b></label>
<input type="text" id="To" name="To" style="width:100%" value="{{ ticket.to }}" required><br> <br>
<label for="Cc"><b>Cc</b></label>
<input type="text" id="Cc" name="Cc" style="width:100%" value="{{ ticket.cc }}" required><br> <br>
<label for="Subject"><b>Subject</b></label>
<input type="text" id="Subject" name="Subject" style="width:100%" value="{{ ticket.subject }}" required><br> <br>
</fieldset>
{% endfor %}
Thanking you in advance. You will be highly appreciated if you could explain the needful code.

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

Django: may not be NULL when submitting a form

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

Validating and displaying errors in custom Django form

When I use form.as_p to display my form and, for example, I click on Submit button without fill any field, it shows error messages asking me to fill the required fields. However, when I customize the output of my html template, it doesn't validate the fields and doesn't show any error message. My forms.py:
# forms.py
class SignUpForm(forms.ModelForm):
username = forms.CharField(label='Username', max_length=75, widget=forms.TextInput(attrs={'placeholder' : 'Username'}))
email = forms.EmailField(label='Email', max_length=255)
first_name = forms.CharField(label='First Name', max_length=75)
last_name = forms.CharField(label='Last Name', max_length=75)
birthday = forms.DateField(label='Birthday')
gender = forms.ChoiceField(choices = User.GENDER_CHOICES)
class Meta:
model = User
fields = ['username', 'password', 'email', 'first_name', 'last_name', 'birthday', 'gender']
widgets = {
'password': forms.PasswordInput(attrs={'class': 'form-control'}),
'email': forms.EmailInput(attrs={'class': 'form-control'}),
'birthday': forms.DateInput(attrs={'class': 'form-control'}),
}
def save(self, commit=True):
user = super(SignUpForm, self).save(commit=False)
user.username = self.cleaned_data['username']
user.set_password(self.cleaned_data['password'])
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.birthday = self.cleaned_data['birthday']
user.gender = self.cleaned_data['gender']
if commit:
user.save()
return user
My HTML template is like this:
# registration.html
<form class="form-signin" action="/register/" method="post">
<h2 class="form-signin-heading">registration now</h2>
<div class="login-wrap">
<p>Enter your personal details below</p>
<input type="text" class="form-control" placeholder="{{ form.first_name.label }}" name="{{ form.first_name.name }}" id="id_{{ form.first_name.name }}" maxlength="75" autofocus>
<input type="text" class="form-control" placeholder="{{ form.last_name.label }}" name="{{ form.last_name.name }}" id="id_{{ form.last_name.name }}" maxlength="75" autofocus>
<input type="text" class="form-control" placeholder="{{ form.email.label }}" name="{{ form.email.name }}" id="id_{{ form.email.name }}" maxlength="255" autofocus>
<div class="radios">
{% for choice in form.gender.field.choices %}
<label class="label_radio col-lg-4 col-sm-4" for="">
<input name="{{ form.gender.name }}" id="radio-01" value="{{choice.0}}" type="radio" checked /> {{ choice.1 }}
</label>
{% endfor %}
</div>
<p> Enter your account details below</p>
<input type="text" class="form-control" placeholder="{{ form.username.label }}" name="{{ form.username.name }}" id="id_{{ form.username.name }}" autofocus>
<input type="password" class="form-control" placeholder="{{ form.password.label }}" name="{{ form.password.name }}" id="id_{{ form.password.name }}">
<label class="checkbox">
<input type="checkbox" value="agree this condition"> I agree to the Terms of Service and Privacy Policy
</label>
<input class="btn btn-lg btn-login btn-block" type="submit" value="Submit"/>
<div class="registration">
Already Registered.
<a class="" href="login.html">
Login
</a>
</div>
</div>
</form>
I'm starting now with Django, I read the documentation about custom forms, but I didn't find nothing about how to validate fields as forms.as_p does.
That is the wrong way to produce custom HTML for your form. You should still use the Django form fields - {{ form.first_name }} etc - rather than creating HTML versions yourself and populating them.
However, the issue is simpler than that: you have forgotten to add the {{ form.myfield.errors }} for each field, and the {{ form.non_field_errors }} at the top of the form.
Also note there's no reason to do all that extra work in save. All of those fields are already being set by the superclass: the only thing you need to take care of manually is user.set_password.

Categories