Hi i just have a small doubt can we create a HTML template which will have the Django form and normal HTML form together.
I created a HTML template which has both normal HTML input tag and Django forms.
I am getting the following error when i do a form.save(commit=False)
could not be created because the data didn't validate.
My view.py
if request.method == 'POST':
form_value = request.POST.copy()
print form_value
form = InfoForm(data=request.POST)
post_val = form.save(commit=False)
my HTML
<div class="form-row">
<div class="form-group col-md-4">
{{form.name}}
</div>
<div class="form-group col-md-4">
{{form.number}}
</div>
<div class="form-group col-md-4">
{{form.location}}
</div>
</div>
<div class="form-group">
<label for="Feedback">Feedback</label>
<div id="Feedback" class="optionBox1">
<div class="input-group my-add-div">
<input type="text" class="form-control" name="feedback" required>
<input type="text" class="form-control" name="feedback" required>
<input type="text" class="form-control" name="feedback" required>
</div>
</div>
</div>
my form.py
class InfoForm(forms.ModelForm):
name = forms.CharField(label='Project Name',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Click to enter text',}))
number = forms.DecimalField(label='Project #',widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'Enter the ID',}))
location = forms.CharField(label='Location',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter the Location',}))
class Meta:
model = Info
field = ('name','number','location',)
My Model.py
name = models.CharField(max_length=200,blank=True , null=True)
number = models.IntegerField(blank=True , null=True)
location = models.CharField(max_length=200,blank=True , null=True)
feedback = ArrayField(ArrayField(models.CharField(max_length=200,blank=True,null=True)))
Thanks in advance
You need to first call form.is_valid() to use save method on the form.
All what you need to create any form in template you want, example:
``
<form action="." method="post">
{% csrf_token %}
<input type="text" name="first_name">
<p><input type='submit' value="Change"></p>
</form> ``
then, in your view call
first_name = request.POST['first_name']
and it will be works fine.
Related
I have 3 form inputs that will be submitted when one master button is clicked to then be passed into a view as the request parameter. I would like to get the values of first_name, last_name and email inside my view using request.get(). When the button is clicked the values inside my form appear as None
HTML:
<div id="form_content">
<form action="" method="post">
<section class="form_inputs">
<label for="first_name">First Name:</label>
<input type="text" id="first_name">
</section>
<section class="form_inputs">
<label for="last_name">Last Name:</label>
<input type="text" id="last_name">
</section>
<section class="form_inputs">
<label for="email">Email:</label>
<input type="text" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
views.py
def home(request):
form_response = request.GET.get("form_content")
print(form_response)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)
first you need to add csrf_token in your code for post method and also give a name for each input like this :
<div id="form_content">
<form action="" method="post">
{% csrf_token %}
<section class="form_inputs">
<label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name">
</section>
<section class="form_inputs">
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name">
</section>
<section class="form_inputs">
<label for="email">Email:</label>
<input type="text" name="email" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
and then:
def home(request):
first_name = request.POST['first_name']
last_name = request.POST['last_name']
email = request.POST['email']
print(first_name, last_name, email)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)
In your input tags, you have not passed the name parameter. Pass the name parameter in your input tags, as Django collects the data from the name tags.
For example, in your case, it must be:
<input type="text" id="id_first_name" name="first_name">
<input type="text" id="id_last_name" name="last_name">
<input type="text" id="id_email" name="email">
I have created one html form for my web application. Now I want to fetch data for further validation on submit the form in DJANGO. So how can I do this. I have attached my html form code below. Actually, I can get the data by the request.POST.get('field_name') method but I want to get data in the single object. Also I want to create seprate python file for validation. So how can I redirect on that file.
<form action="/contact_form_data_insert" name = "contact_us_form" id = "contact_us_form" method="POST">
<div class="bg-transperent container mt-6">
<div class="bg-transperent container">
<div class="row bg-transperent">
<div class="col-lg-6 bg-transperent contact_field">
<div class="form-outline my-2 px-2" >
<input type="text" id="contact_name" name="contact_name" class="form-control form-control-lg-border-0" placeholder = "Your Name"/>
</div>
</div>
<div class="col-lg-6 bg-transperent contact_field">
<div class="form-outline my-2 px-2" >
<input type="text" id="contact_company" name="contact_company" class="form-control form-control-lg-border-0" placeholder = "Your Company" />
</div>
</div>
</div>
<div class="row bg-transperent">
<div class="col-lg-6 bg-transperent contact_field">
<div class="form-outline my-2 px-2" >
<input type="tel" id="contact_phone_number" name="contact_phone_number" class = "form-control form-control-lg-border-0" placeholder = "Phone Number">
</div>
</div>
<div class="col-lg-6 bg-transperent contact_field">
<div class="form-outline my-2 px-2" >
<input type="email" id="contact_email" name="contact_email" class="form-control form-control-lg-border-0" placeholder = "Email"/>
</div>
</div>
</div>
</div>
<div class="bg-transperent container">
<div class="row">
<div class="col-12 bg-transperent contact_field ">
<div class="form-outline my-2 px-2" >
<input type="text" id="contact_subject" name = "contact_subject" class="form-control form-control-lg-border-0" placeholder = "Subject" />
</div>
</div>
</div>
</div>
<div class="bg-transperent container">
<div class="row">
<div class="col-12 bg-transperent contact_field">
<div class="form-outline my-2 px-2" >
<textarea class="form-control form-control-lg-border-0" id="contact_question" name="contact_question" placeholder = "Your Question" rows="5"></textarea>
</div>
</div>
</div>
</div>
<div class="container bg-transperent">
<div class="row">
<div class="col-lg-2 px-4">
<input type="submit" class = "btn btn-info btn-lg btn-block"style="color: white;font-family: serif; font-weight: bolder; " value="SEND">
</div>
</div>
</div>
</div>
</form>
Make Django form in the backend for example login form has username and password fields
Don't use it in the front
Just make your own form in the front end with fields named username and password
Django of course can't tell if the data sent from Django form or custom form
So it'll treat it normally
For example
class LoginForm(Form):
username = ...
password = ...
class Meta:
fields = ('username', 'password')
Now in the backend
form = LoginForm (request.POST)
if form.is_valid():
The form only needs data named username and password from the front side
About using Django forms, here's a quick demo... You can create a file within your app folder called forms.py and place the following inside of it.
from django import forms
class ContactForm(forms.Form):
# You can also modify the field attributes from here if you wish to
contact_name = forms.CharField(widget=forms.TextInput(attrs={'id':'contact_name', 'name': 'contact_name', 'class': 'form-control form-control-lg-border-0', 'placeholder': 'Your Name'}))
# You can take the same approach for the other text & email input fields below
contact_company = forms.CharField(widget=forms.TextInput(attrs={...}))
contact_phone_number = forms.CharField(widget=forms.TextInput(attrs={...}))
contact_subject = forms.CharField(widget=forms.TextInput(attrs={...}))
contact_email = forms.EmailField(widget=forms.EmailInput(attrs={...}))
# Textarea field
contact_question = forms.CharField(widget=forms.Textarea(attrs={'id':'contact_question', 'name': 'contact_question', 'class': 'form-control form-control-lg-border-0','placeholder': 'Your Question', 'rows': '5'}))
# Can create any method in here to handle a specific process if the form is valid
def save(self):
pass
From your views.py file within the same app folder:
from .forms import ContactForm # Importing the custom form you created
# Now let's say I want to pass it to a specific view to allow a user to submit his/her information...
def contact_form_view(request):
if request.method == 'POST':
form = ContactForm(data=request.POST)
if form.is_valid():
# Do something here to process and save the form data
form.save()
else:
print(form.errors)
else:
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})
Now, within your html template, you could just replace the respective input fields with the form object fields. For example:
<form method="POST" ...>
# Where you have these fields
<input type="text" id="contact_name" name="contact_name" class="form-control form-control-lg-border-0" placeholder = "Your Name"/>
# Just replace with... (i.e.: contact_name as above)
{{ form.contact_name }}
# Apply the above with the other respective fields.
</form>
I trust you already know how to set up your url for the view. In a nutshell, that's an approach you could take.
I do recommend that you read the doc for more information on the Django forms though.
I'm working on a little e-commerce site. when I post a product from my site, the image(picture) doesn't show but when I post from the admin panel, the image shows so I don't why. I need help on this please. This is the code.
The code below is from the model.py
class OrderedItem(models.Model):
name = models.CharField(max_length=50)
price = models.FloatField()
image = models.ImageField(upload_to='pics')
def __str__(self):
return self.name
The code below is from the views.py
def additem(request):
if request.method == 'POST':
stock_name = request.POST['stock_name']
stock_price = request.POST['stock_price']
stock_image = request.POST['stock_image']
new_item = Stock(stock_name=stock_name, stock_price=stock_price, stock_image=stock_image)
new_item.save()
return redirect('/')
else:
return render(request, 'post.html')
the code below is from the html page
<form action="{% url 'additem' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" name="stock_name" id="" placeholder="stock_name">
</div>
<div class="form-group">
<input type="text" name="stock_price" id="" placeholder="stock_price">
</div>
<div class="form-group">
<input type="file" name="stock_image">
</div>
<div class="form-group">
<input type="submit" value="Additem" class="btn btn-primary btn-lg">
</div>
</form>
You need to add enctype='multipart/form-data' in the form otherwise no file will be accepted.
<form method="POST" action="" enctype='multipart/form-data'>
To get the images inputted in your html file
stock_image = request.FILES['stock_image']
I have form:
<form id="contact-form" class="contact__form" method="POST" action="{% url 'backcall' %}">
{% csrf_token %}
<span class="text-color">Send letter</span>
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="tel" name="phone" class="form-control" placeholder="Phone (+380)" pattern="[\+][3][8][0]\d{9}" minlength="13" maxlength="13" />
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" placeholder="Email">
</div>
<div class="form-group-2 mb-4">
<textarea name="message" class="form-control" rows="4" placeholder="Your letter"></textarea>
</div>
<button class="btn btn-main" name="submit" type="submit">Send</button>
</form>
views.py:
def backcall(request):
backcall = BackCall(name = request.POST['name'], phone = request.POST['phone'], email=request.POST['email'] , message = request.POST['message'])
backcall.save()
return redirect('thanks')
models.py
class BackCall(models.Model):
name = models.CharField(max_length=50)
phone = models.CharField(max_length=13)
email = models.EmailField()
message = models.TextField(default=None)
datetime = models.DateTimeField(auto_now_add=True)
When I fill out the form and submit nothing happens. When I follow the link 'backcall/' I get an error.
What the problem can be connected with and how to fix it?
Please, search more, exist the solution
Use the MultiValueDict's get method. This is also present on
standard dicts and is a way to fetch a value while providing a default
if it does not exist.
def backcall(request):
backcall = BackCall(name = request.POST.get('name'), phone = request.POST.get('phone'), email=request.POST.get('email') , message = request.POST.get('message'))
backcall.save()
return redirect('thanks')
You should check whether or not the record exists in your database, I think, a quick example would be:
def backcall(request):
obj, created = BackCall.objects.get_or_create(email=request.POST.get('email'),
defaults={'phone': request.POST.get('phone'),
'name': request.POST.get('name'),
'message': request.POST.get('message')}
if created:
return redirect('thanks')
return ...
I have created an HTML form trying to do simple registration.
The problem is that after clicking submit button no error appears but when I chech database the data from fields is not there.
signup.html
<form action="\polls\Registration" method="POST">
<div class="form-group mb15">
<input type="text" class="form-control" name="userName" placeholder="Enter Your Username" required>
</div>
<div class="form-group mb15">
<input type="password" class="form-control" name="password" placeholder="Enter Your Password">
</div>
<div class="form-group mb15">
<input type="text" class="form-control" name="fullName" placeholder="Enter Your Full Name">
</div>
<div class="form-group mb20">
<label class="ckbox">
<input type="checkbox" name="checkbox">
<span>Accept terms and conditions</span>
</label>
</div>
<div class="form-group">
<button class="btn btn-success btn-quirk btn-block">Create Account</button>
<br>
Already a member? Sign In Now!
</div>
</form>
forms.py
class RegistrationForm(forms.Form):
userName= forms.CharField(label='Username',max_length=100)
password = forms.CharField(label='Password', max_length=100)
fullName= forms.CharField(label='Full Name', max_length=100)
myview.py
def reg(request):
if request.method == 'POST':
the request:
form = forms.RegistrationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/polls/signin')
else:
form = forms.RegistrationForm()
return render(request, 'signup.html', {'form': form})
urls.py
urlpatterns = [
url(r'^Registration', myview.reg,name='Registration'),
]
[SOLVED]
What I did is that I created a model to handle form processing.I also used modelForm instead of forms. For anyone having same issue check this