my django template is not submitting data! i know it is very basic thing but there is something i cannot realize here! my Model is:
class project(models.Model):
Project_Name = models.CharField(max_length=50)
And my ModelForm is:
class create_project(forms.ModelForm):
class Meta:
model = project
fields = ['Project_Name']
views.py
def project_create_view(request):
form = create_project(request.POST or None)
msg = ''
if form.is_valid():
form.save()
msg = 'Data Submitted'
form = create_project()
return render(request, 'create_project.html', {'form':form, 'msg':msg})
And my template is:
<form action="" method="POST">
{% csrf_token %}
<table border="1">
<tr>
<td>
<div>
<label for="id_Project_Name">Project Name</label>
<input type="text" name="Project_Name" id="id_Project_Name">
</div>
</td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
My context dict is 'form', i tried so many ways searched online but no luck, can anyone help?...
I haven't pasted all the project as the case is similar for the rest fields.
In your html,
<form method="POST" action="#keep it blank or add action as per your requirement" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<span> {{field.errors}} </span>
<div> {{field}} </div> #you can add label or placeholder as per your requirement
{% endfor %}
<input type="submit" value="Submit">
</form>
You have not added enctype in your html.
Note : You can modify your views.
i managed to solve it this way after taking support from one of my experienced friends:
<td>
<div>
<label for="{{form.Project_Name.name}}">Project Name</label>
<input type="text" name="Project_Name" id="{{form.Project_Name.name}}">
</div>
</td>
Related
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
I want the user to be able to add or remove fields in the website, I am using flask and fields.FieldList
I know how to do that directly with javascript only clone the field section of the DOM and rename the attributes like name, id etc... is there an easy way to do it with flask/ flask forms? I want to achieve something like in the picture (doesn't have to be in that layout, I really don't care the layout since I can move it later on)
and then been able to pass it to the back end and been recognize by the flask forms.
thanks in advance, I appreciate it =)
This are my forms:
class AddressForm(FlaskForm):
addr = fields.StringField("address")
class MainForm(FlaskForm):
addressees = fields.FieldList(fields.FormField(AddressForm), min_entries=1, validators=[DataRequired()])
This is my view:
def addressees_create():
if request.method == 'POST':
form = MainForm()
if form.validate():
print("is validate")
else:
print("was not validate")
if form.validate_on_submit():
print("the form was validated on submit")
else:
print("was not validated on submit")
print(form.data)
addressees = form.data["addressees"]
for address in addressees:
print("\t"+str(address))
return render_template("my/template.html",form=form)
else:
form = MainForm()
return render_template("my/template.html", form=form)
This is the template:
<div>
{% for item in form.addressees %}
{{ item.hidden_tag() }}
{{ item.addr }}
{% endfor %}
<div style="color: red;">
{% for error in form.addressees.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
</div>
I also had this problem. Here is my solution
class CreatePollForm(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
options = FieldList(StringField())
submit = SubmitField('Create')
<ul id="options">
<li>
<label for="options-0">Options-0</label>
<input id="options-0" name="options-0" type="text" value="">
</li>
<li>
<label for="options-1">
Options-1
</label>
<input id="options-1" name="options-1" type="text" value="">
</li>
<li>
<label for="options-2">Options-2</label>
<input id="options-2" name="options-2" type="text" value="">
</li>
<li>
<label for="options-3">Options-3</label>
<input id="options-3" name="options-3" type="text" value="">
</li>
<li>
<label for="options-4">Options-4</label>
<input id="options-4" name="options-4" type="text" value="">
</li>
</ul>
You can refer to this data like this:
form = CreatePollForm()
print(form.options.data)
I am trying to create an app where a user can manage a database of "Lost property" items. To do so I have a main page where all the items are displayed and I have a button per row to be clicked when the item is returned to the owner.
That button is submitting a form that should contain the ID value of the element that has been clicked so I trying to get something like
<input id="id_id" name="id" type="hidden" value="{{lostitem.id}}">
But I don't know how to pass that value to my form ! Here is my template :
{% for lostitem in lostitems %}
<tr>
<td>{{lostitem.id}}</td>
<td>{{lostitem.description}}</td>
<td>
<form class="give-back-item-form" method="POST">
{% csrf_token %}
{{formGiveBackItem.as_p}}
<button type="submit" class="button btn btn-xs btn-success buttonItems">
<span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span>
</button>
<!-- TRYING TO ADD A HIDDEN INPUT WITH THE ID AS VALUE -->
</form>
</td>
</tr>
{% endfor %}
Here is my form from forms.py
class GiveBackItemForm(forms.ModelForm):
id = forms.CharField(widget=forms.HiddenInput())
class Meta:
model = ItemLost
fields = ('id',)
And here is where I'm trying to get my $_POST['id'] and to update my object (I couldn't test this part as I'm not getting any POST information at the moment) :
from .forms import GiveBackItemForm
"""Defining our views"""
def item_list(request):
formGiveBackItem = GiveBackItemForm()
"""Ordering objects by date of creation"""
lostitems = ItemLost.objects.filter(added_date__lte=timezone.now()).order_by('added_date')
if request.method == "POST":
"""Giving back an item"""
itemToGive = ItemLost.objects.get(pk=request.POST.get('id'))
itemToGive.giveBackItem
"""Returning our ordered objects to the view"""
"""Request = everything we receive from the user (in a form for example)"""
return render(request, 'lostitem/item_list.html', {'lostitems': lostitems, 'formGiveBackItem' : formGiveBackItem})
Thanks for any help or remark about the code ! I'm just getting started and it was really hard to find anything helpful about my problem
EDIT : I managed to make it work by still using the Django ModelForm and the view to handle my form
Here is my code in my view :
def item_list(request):
"""Ordering objects by date of creation"""
lostitems = ItemLost.objects.filter(added_date__lte=timezone.now()).order_by('added_date')
"""To get data from the form"""
give_back_item_form = GiveBackItemForm(request.POST or None)
# check if form is valid
if give_back_item_form.is_valid():
itemToGive = ItemLost.objects.get(pk=give_back_item_form.cleaned_data['id'])
itemToGive.returned_date=timezone.now()
itemToGive.save()
# your rest of the code here
"""Returning our ordered objects to the view"""
"""Request = everything we receive from the user (in a form for example)"""
return render(request, 'lostitem/item_list.html', {'lostitems': lostitems, 'give_back_item_form' : give_back_item_form})
And here is the code for my template !
<form class="give-back-item-form" method="POST">
{% csrf_token %}
<input type="hidden" name="id" value="{{ lostitem.id }}">
<button type="submit" class="button btn btn-xs btn-success buttonItems">
<span class="glyphicon glyphicon-share-alt" aria-hidden="true"> </span>
</button>
</form>
Thank you all for your answers it lead me to the right solution !
If all you want to do is post back the id of an associated ItemLost object so that you can invoke a method on it (e.g., giveBackItem()), there's no need to use a ModelForm at all. Just use a normal HTML <form>, and manually put the hidden field in it:
<form class="give-back-item-form" method="POST">
{% csrf_token %}
<button type="submit" value="Give Back">
<input type="hidden" name="id" value="{{lostitem.id}}">
</form>
So your complete template would become:
{% for lostitem in lostitems %}
<tr>
<td>{{lostitem.id}}</td>
<td>{{lostitem.description}}</td>
<td>
<form class="give-back-item-form" method="POST">
{% csrf_token %}
<button type="submit" class="button btn btn-xs btn-success buttonItems">
<span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span>
</button>
<input type="hidden" name="id" value="{{lostitem.id}}">
</form>
</td>
</tr>
{% endfor %}
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">
I'm trying to create a button on the framework django that let me delete my own article on my blog. I tried to create a code for this functionality, but it doesn't work.
views.py
if(request.GET.get('delete')): #if the button is clicked
delete_article = get_object_or_404(Article, id=id)
if request.POST:
form = DeleteNewForm(request.POST, request.FILES)
if form.is_valid():
delete_article.delete()
return HttpResponseRedirect("/")
template.html
<form enctype='multipart/form-data' action="." method="post" class="form" autocomplete="off" autocorrect="off">
{% csrf_token %}
<div class="form-group">TITRE
{{ form.title.errors }}
{{ form.title }}
</div>
<div class="form-group">CONTENU
{{ form.media }}
{{ form.contenu.errors }}
{{ form.contenu }}
</div>
<div class="form-group">
{{ form.image.errors }}
{{ form.image }}
</div>
<input type="submit" class="btn btn-default" value="Edit Article"/>
<input type="submit" class="btn btn-default" value="Delete Article" name="delete">
</form>
Here is what happen when I submit the form : I am not redirected on the index as it should redirect me and the article has not been deleted.
Is there a problem which don't let me delete my article in these lines?
I have no idea what you're doing in your views or in your template. But if I want to delete something, I just define a separate view for that.
# views.py
from django.views.generic.base import View
class DeleteView(View):
def post(self, request *args, **kwargs):
article = get_object_or_404(id=request.POST['article_id'])
# perform some validation,
# like can this user delete this article or not, etc.
# if validation is successful, delete the article
article.delete()
return HttpResponseRedirect('/')
Your template should be like this:
<form action="/url/to/delete/view/" method="POST">
{% csrf_token %}
<input type="hidden" value="{{ article.id }}">
<input type="submit" value="Delete">
</form>