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.
Related
I implemented my own user login form with django like below
from django.contrib.auth.forms import AuthenticationForm
class CustomUserLoginForm(AuthenticationForm):
class Meta:
model = CustomUser
fields = ('email', 'password')
then as a view this is what I have:
from rest_auth.views import LoginView
from users.forms import CustomUserLoginForm
class CustomLoginView(LoginView):
def get(self, request):
form = CustomUserLoginForm()
return render(request, "api/test_template.html", context={"form": form})
in my template then, I am calling {{form.as_p}} in <form> tag to show the form input details.
However, by default, this shows the username and password forms. How can I replace the username with the email?
in the rest-auth, browserable api, both the username and the email are present so I know that I can do this since I am using the rest-auth LoginView as backend.
Can I manually unpack {{form}} since later I would still like to style this form. How can I do this?
update
I unpacked the form in `api/test_template.html myself which now looks like the below:
{% block content %}
<div class="container">
<form method="POST">
{% csrf_token %}
<div>
<label for="{{ form.email.id_for_label }}">Email: </label>
<input{{ form.email }}>
</div>
<div>
<label for="{{ form.password.id_for_label }}">password: </label>
<input type="password" {{ form.password }}>
</div>
<button style="background-color:#F4EB16; color:blue" class="btn btn-outline-info" type="submit">Login</button>
</form>
Don't have an account? <strong>register here</strong>!
</div>
{% endblock %}
this works, however, rest-auth framework still require the username to not be empty. how can I change that, to ignore the username?
my user model
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
def __str__(self):
return self.email
You should set USERNAME_FIELD='email' on your CustomUser model.
There is nice blogpost on How to use email as username.
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.">
Hi I am learning Django for a project and I am trying to upload a file along with a on option in dropdown list through a form using POST.
Here are my files:
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from .forms import UploadFileForm
# function to handle an uploaded file.
from save_uploaded_file import handle_uploaded_file
def index(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return render(request, 'viewer_app/display_image.html')
else:
print('error')
return render(request, 'viewer_app/index.html', {'form': form})
else:
return render(request, 'viewer_app/index.html')
forms.py
from django import forms
class UploadFileForm(forms.Form):
file = forms.FileField()
displayType = forms.ChoiceField(widget=forms.Select(), required=True)
save_uploaded_file.py
def handle_uploaded_file(f):
with open('static/viewer_app/temp.exr', 'wb+') as recieved_exr:
for chunk in f.chunks():
recieved_exr.write(chunk)
index.html
<div id="formDiv" style="display:none;" class="form" >
<form method="post" enctype="multipart/form-data" class="form-style">
<label for="browse">Upload file</label>
<input type="file" value="Browse" id="brow" /><br></br>
<label for="display">Display type</label>
<select id="display-type" name="display">
<option id="RGB1" value="RGB1">RGB1</option>
<option id="RGB2" value="RGB2">RGB2</option>
<option id="RGB3" value="RGB3">RGB3</option>
<option id="RGB4" value="RGB4">RGB4</option>
</select><br></br>
<input type="submit" value="Show file" id="showimage"/><br></br>
{% csrf_token %}
</form>
</div>
So, after I run the server to display the page and I select the upload and click submit, it doesn't upload and save the file and in the terminal I see the "error" text in the terminal which is displayed due to from.is_valid() not being true.
I tried to add {{ form.errors }} {{ form.non_field_errors }} to the html file but I still don't know exactly what is that I am doing wrong.
Also I can see the absence of name attributes inside your <input> tag and a potentially wrong name attribute inside your <select> tag. You should put the exact name of the field inside your html 's name attribute for the form to get bounded. Same goes for the <select> tags.
Try putting:
<input type="file" value="Browse" id="brow" name="file"/>
and
<select id="display-type" name="displayType">
and probably your problem will be solved.
If I may suggest, why aren't you using the standard django template form tags, Such as {{ form.as_p }} ? These methods are quite handy and will also handle the errors successfully. You should try using them. check them here
EDIT
You haven't given any choices attribute to you ChoiceField in your forms.py. Make sure to give a attribute choices as a tuple to your ChoiceField. It can be done as:
#import ugettext_lazy
from django.utils.translation import ugettext_lazy as _
#inside your form class
class UploadFileForm(forms.Form):
CHOICES = (
('RGB1', _('RGB1')),
('RGB2', _('RGB2')),
('RGB3', _('RGB3')),
#And so on
)
#First option in the tuple is stored in db. Second is displayed in Forms.
displayType = forms.ChoiceField(widget=forms.Select(), required=True , choices = CHOICES)
file = forms.FileField()
EDIT 2:
Get the file url as below,
from django.contrib.staticfiles.templatetags.staticfiles import static
url = static('viewer_app/temp.exr')
#See if temp.exr exists prior to this. Otherwise create a file manually or through python.
Then open the file by supplying this url.
Again I would recommend you to check ModelForms. They'll completely eliminate the need to write files this way.
Hope it helps. Thanks.
Hi i want to redirect to a destination page with the from data. For example when user fills a form the data inputted in the form, i want that to be outputted on the destination page
my codes are as follows:-
source page(experiment.html), I am unsure what the action should be for the form so please help me with it
<form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST">
{% csrf_token %}
<label>Researcher Name(s):<input type="text" name="researcher">
<lable>Study Summary<textarea rows="10" cols="50" placeholder="here you go" maxlength="500" class="form-control" name="study"></textarea>
<br>
<input type = "submit" value="Submit" class="btn btn-primary" />
</form>
destination page (about_experiment.html)
<h3>Holding page for {{ exp.name }}.</h3>
<h2> {{ form }} </h2>
views.py
from .forms import AboutHelp
from django.shortcuts import render
from django.http import HttpResponseRedirect
def about_experiment(request):
if request.method == 'POST':
form = AboutHelp(request.POST)
if form.is_valid():
researcher = form.cleaned_data['researcher']
study = form.cleaned_data['study']
else:
form = AboutHelp()
return render(request, 'about_experiment.html', {'form': form})`
forms.py
from django import forms
class AboutHelp(forms.Form):
researcher = forms.CharField(max_length=100)
study = forms.CharField(max_length=500)
urls.py
url(r'^about/(?P<ex_link_name>\w+)', lazer.views.about_experiment, name='lazer.views.about_experiment'),
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">