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.">
Related
In my template I have a form that includes two input elements whose values can be adjusted with javascript. I want to be able to take these values and, on form submit, display them in a sentence in a for loop underneath.
index.html:
<form action="{% url 'workouts:workout' %}" method="post">
{% csrf_token %}
<div class="weight">
<h4>WEIGHT (kgs):</h4>
<button type="button" class="weight-dec">-</button>
<input type="text" value="0" class="weight-qty-box" readonly="" name="one">
<button type="button" class="weight-inc">+</button>
</div>
<div class="reps">
<h4>REPS:</h4>
<button type="button" class="rep-dec">-</button>
<input type="text" value="0" class="rep-qty-box" readonly="" name="two">
<button type="button" class="rep-inc">+</button>
</div>
<input type="submit" value="Save" name="submit_workout">
<input type="reset" value="Clear">
</form>
{% if exercise.workout_set.all %}
{% for w in exercise.workout_set.all %}
{{ w.content }}
{% endfor %}
{% endif %}
I have given the form above an action attribute for a url which maps to a view, and each of the inputs has a name in order to access their values in the view. I also have written this form in forms.py:
class WorkoutModelForm(forms.ModelForm):
class Meta:
model = Workout
fields = ['content']
And for context, here is my model:
class Workout(models.Model):
content = models.CharField(max_length=50)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default=None)
class Meta:
ordering = ('created',)
My problem from here is that I have no idea how to actually incorporate my model form in my template, or how to write a view that will do what I want it to. I am still new to this and have been searching for an answer for sometime, but so far have not found one. Please help.
This is able to help you, you should first have a look at the django Class-Based Views , more specifically the FormView, django already has generic views capable of handling data posted on forms. Your code would look like this:
# forms.py
# imports ...
class WorkoutModelForm(forms.ModelForm):
class Meta:
model = Workout
fields = ['content']
# urls.py
from django.urls import path
from . import views
app_name = 'myapp'
urlpatterns = [
path("test-form/", views.TesteFormView.as_view(), name='test-form'),
]
# views.py
from django.views.generic import FormView
from myapp import forms
from django.contrib import messages
class TesteFormView(FormView):
template_name = "myapp/index.html"
success_url = reverse_lazy('myapp:test-form')
form_class = forms.WorkoutModelForm
def get(self, request, *args, **kwargs):
return super(TesteFormView, self).get(request, *args, **kwargs)
def form_valid(self, form):
print(f"POST DATA = {self.request.POST}") # debug
content = form.cleaned_data.get('content')
# fieldx= form.cleaned_data.get('fieldx')
# do something whit this fields like :
Workout.object.create(content=content)
messages.success(self.request,"New workout object created")
return super(TesteFormView, self).form_valid(form=self.get_form())
def form_invalid(self, form):
print(f"POST DATA = {self.request.POST}") # debug
for key in form.errors:
messages.error(self.request, form.errors[key])
return super(TesteFormView, self).form_invalid(form=self.get_form())
And your template would look like:
# myapp/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TestForm</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">submit</button>
</form>
</body>
</html>
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.
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">
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.