i am having trouble validating my django form. my form is not validating. can anyone please examine my code and point out exactly where i am doing wrong. here are my codes.
models.py-
from django.db import models
classcommentbox
(models.Model) :
box=models.CharField(max_length=
50 )
forms.py-
from django.forms import ModelForm
from . models import commentbox
class commentboxForm(ModelForm):
class Meta:
model=commentbox
fields=['box']
views.py-
from django.http import HttpResponse
from . models import commentbox
from . forms import commentboxForm
def submit(request):
if request.method=="POST":
form=commentboxForm(request.
POST)
if form.is_valid():
return HttpResponse('valid')
else:
return HttpResponse('not
Valid')
else:
return HttpResponse("error")
template-
<form action="{% url 'poll:submit'
%}"method="POST">
{%csrf_token%}
<label for"comment"> say something:
</label>
<textarea class="form-control"
rows="3" id="comment"> </textarea>
<button type="button"> submit
</button>
</form>
add name attribute in textarea tag
<textarea class="form-control" name="box" rows="3" id="comment"> </textarea>
You need to add name for the input,
In your template,
<textarea class="form-control" rows="3" name="box" id="comment"> </textarea>
Or,
<input type="text" name="box" class="form-control">
Related
I have a serch field on my page
<form method="GET" class="container mb-5">
<input type="search" class="form-control rounded" placeholder="Write a name" aria-label="Search"
aria-describedby="search-addon" name="search"/>
<button type="submit" class="btn btn-outline-primary px-5" >Search</button>
</form>
And here is my views
def my_view(request):
value_one = request.GET.get("search", None)
objects = MyModel.objects.all()
if value_one:
objects = objects.filter(field_one=value_one)
After I input something in a search field and push the button 'search', text which was in search field dissapears, I want it to stay until the next input. Is it possible to do with Django or not? Don't even know how to google it, everything I found was on different topic
on your template add value to your input:
<form method="GET" class="container mb-5">
<input type="search" class="form-control rounded" placeholder="Write a name" aria-label="Search" value="{{value_one"}}
aria-describedby="search-addon" name="search"/>
<button type="submit" class="btn btn-outline-primary px-5" >Search</button>
</form>
and on your view add that value to your context :
def my_view(request):
value_one = request.GET.get("search", None)
objects = MyModel.objects.all()
if value_one:
objects = objects.filter(field_one=value_one)
return render(request,'template.html',{'value_one':value_one,'objects':objects})
Have you heard of django's Form class ? You should be using the Form class to create forms in Django and that would allow you to preserve data between "submit" calls as well as handle errors. Some example code snippets for you:
forms.py
from django import forms
class SearchForm(forms.Form):
search = forms.CharField(label="Search Query", widget=forms.TextInput(attrs={"class": "form-control rounded", "placeholder": "Write a name", "aria-label": "Search", "aria-describedby": "search-addon"}))
views.py
from django.shortcuts import render
from .forms import SearchForm
def my_view(request):
form = SearchForm({"search": request.GET.get("search", None)})
if form.is_valid():
search_query = form.cleaned_data.get("search")
if search_query:
objects = MyModel.objects.filter(field_one=search_query).all()
# ...snip...
return render(request, 'searchform.html', {"form": form})
searchform.html
<form action="{% url 'my_view' %}" method="get">
{{ form }}
<input type="submit" value="Submit" class="btn btn-outline-primary px-5">
</form>
Why am I asking question despite already been asked? I read many question posted on Stack Overflow but I am not able to fix the code as I am new to Python Language.
What am I trying to do: Simply trying to take the input from user and return an HttpResponse (if successfully). Otherwise, an error HttpResponse message to return.
Problem : The MyForm.is_valid() in Forms.py is always returning False! I tried many solutions posted on previous questions and also read the documentary thrice but not able to understand, what am I doing wrong?
Views.Py
from django.http import HttpResponse
from .forms import PostForm
.
.
. <<code here>>
def register(request):
if request.method == 'POST':
Myform = PostForm(request.POST)
if Myform.is_valid():
return HttpResponse("<h1>Is_Valid is TRUE.</h1>")
else:
return HttpResponse("<h1>Is_Valid is False.</h1>")
else:
return HttpResponse("<h1> GET REQUEST>>>> </h1>")
Forms.Py
from django.forms import ModelForm
from .models import Post
class PostForm(ModelForm):
class Meta:
model= Post
fields = ['Username']
Models.Py
from django.db import models
class Post(models.Model):
Username = models.CharField(max_length = 20)
def __str__(self):
return self.name
HTML CODE
{% block body %}
<div class="container-fluid">
<form method="POST" class="post-form" action="{% url 'submit' %}">
{% csrf_token %}
<div class="form-group"> <!-- Full Name -->
<label for="Username" class="control-label">Full Name</label>
<input type="text" class="form-control" id="Username" name="full_name" placeholder="Enter the name of Patient here.">
</div>
<div class="form-group"> <!-- Submit Button -->
<button type="submit" class="btn btn-primary"> Submit!</button>
</div>
</form>
</div>
<hr/>
{% endblock %}
Urls.Py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^/submit$', views.register , name = 'submit'),
]
The name of your input should be username:
This is how you send this value to the form.
NOTE: It's better to use the django form, that you've already done with ModelForm
<input type="text" class="form-control" id="username" name="username" placeholder="Enter the name of Patient here.">
I am new to Django and trying to build a simple web page. I am trying for post request but there no values getting inserted into the database.I hope the problem should be in views.py forms.is_valid() Since no logs are recorded after this line.Please assist
model.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Q
from django.forms import ModelForm
from django import forms
# Create your models here.
class aws_cred(models.Model):
aws_access_user_id = models.ForeignKey(User,null=False,related_name="aws_acc_user")
access_key = models.CharField(max_length=300)
secret_key = models.CharField(max_length=300)
class aws(ModelForm):
class Meta:
model = aws_cred
fields = ['access_key','secret_key','aws_access_user_id']
views.py
from django.shortcuts import render_to_response,HttpResponseRedirect,render,redirect,reverse
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from s3comp.models import aws_cred,aws
import logging
#login_required
def fileinput(req):
logging.basicConfig(filename='log_filename.txt',level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
if req.method == 'POST':
form = aws(req.POST)
logging.debug(form)
try:
logging.debug('step 4')
if form.is_valid():
logging.debug('step 5')
access_key_val = req.POST.get('access key','')
secret_key_val = req.POST.get('secret key','')
aws_access_user_id_val = req.POST.get('aws access user id', '')
logging.debug(access_key_val+" " +secret_key_val+" " +aws_access_user_id_val)
cred_obj = aws(access_key = access_key_val,secret_key =secret_key_val,aws_access_user_id = aws_access_user_id_val)
cred_obj.save()
return HttpResponseRedirect(reverse('s3comp:fileinput'))
except Exception as e:
logging.debug(e)
else:
form = aws()
return render(req,'s3comp/fileinput.html',{'form':form})
html file
<form action="{% url 'fileinput_home' %}" method="post">
{% csrf_token %}
<p><label for="Aws access user id">User:</label><input type="text" name="Aws access user id" value={{ user.get_username }}/></p>
<p><label for="Access Key">Access Key:</label><input type="text" name="Access Key"/></p>
<p><label for="Secret Key">Secret Key:</label><input type="text" name="Secret Key"/></p>
<input type="submit" value="Submit">
</form>
You are using wrong name attribute value in template and views, So update according to below code
<form action="{% url 'fileinput_home' %}" method="post">
{% csrf_token %}
<p><label for="Aws access user id">User:</label><input type="text" name="aws_access_user_id" value={{ user.get_username }}/></p>
<p><label for="Access Key">Access Key:</label><input type="text" name="access_key"/></p>
<p><label for="Secret Key">Secret Key:</label><input type="text" name="secret_key"/></p>
<input type="submit" value="Submit">
</form>
Views.py
access_key_val = req.POST.get('access_key','')
secret_key_val = req.POST.get('secret_key','')
aws_access_user_id_val = req.POST.get('aws_access_user_id', '')
What I'm trying to do is to allow a user to enter any text in a form and have the data stored in a database. However, it is not being saved when I test it. I'm sure it's probably something stupid, but any help will be appreciated. I'm also pretty new to using Django.
Below is what I have currently have. Any help will be appreciated.
models.py:
from __future__ import unicode_literals
from django.db import models
class TEST(models.Model):
test_name = models.CharField(max_length=100)
forms.py:
from django import forms
class Test_Form(forms.Form):
test_name = forms.CharField(max_length=100)
views.py:
from django.shortcuts import render
from Test.forms import Test_Form
from Test.models import Test
from django.http import HttpResponseRedirect
def index(request):
return render(request, 'Test/Test.html')
def Test_View(request):
if request.method == 'POST':
form = Test_Form(request.POST)
if form.is_valid():
test_name = request.POST.get('test_name', '')
return HttpResponseRedirect(reverse('Test:IOC'))
else:
form = Test_Form()
return render(request, 'Test/Test.html', {'form': form})
Snippet from test.html
<form action="/Test/" method="POST" id="Test" class="form-horizontal form-groups-bordered" role="form">
{% csrf_token %}
<div class="form-group">
<div class="row">
<label class="col-lg-2 control-label" for="test_title">Full Name of Test</label>
<div class="col-lg-8">
<input id="ioc_name" class="form-control" name="test_name" type="CharField" data-validate="required" placeholder="ex: This is a test">
</div>
<div class="col-lg-1 col-lg-offset-9">
<a class="btn btn-success btn-icon">
Submit
<input type="submit" />
<i class="entypo-check"></i>
</a>
</div>
</form>
The model instance isn't save automatically with magic. You need to instantiate it, assign the data, and call the save method, like this:
test = TEST(test_name=form.cleaned_data["test_name"])
test.save()
Or in one step: TEST.create(test_name=form.cleaned_data["test_name"])
Or even shorter (if I remember well): TEST.create(**form.cleaned_data)
You should check the docs from creating forms from models, it'll get your work easier (this is for Django 1.1.0) (https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/)
Also, your input is wrong:
You have to set type to a valid value (text in this case). Anyway, as t doesn't recognizes CharField as a valid type, it sets its value to text, which is the default, so you don't have problems here. Valid types
I don't know if data-validate is part of your own code, but if not and you wanna the field be required before hitting submit, you should use required, which is an HTML attr.
What am I doing wrong?
...
from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
#csrf_protect
def home(request):
return render_to_response('home/home.html', {}, RequestContext(request))
def mail(request):
if request.method == 'POST':
...
Form:
<form method="POST" action="sendemail">
{% csrf_token %}
<input name="name" type="text" placeholder="Namr">
<input name="email" type="text" placeholder="mail">
<input type="submit">
</form>
URL:
url(r'^sendemail$', 'openshift.views.mail')
Thank you.
The #csrf_protect decorator should be on the view that handles the form, not the one displaying the form.
Besides, if you have the CSRF middleware installed, then all POST views are automatically protected.
See the docs: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/