django-why this form is always invalid - python

i have created a form with minimal fields(for testing) , but it never enters form.is_valid()
Here is the minimal code
in the models.py
from django.db import models
class sample(models.Model):
field1=models.CharField(max_length=100)
field2=models.CharField(max_length=100)
in the forms.py
from django.forms import ModelForm
from app.models import sample
class someform(ModelForm):
class Meta:
model=sample
in the views.py
some imports
def index(request):
return render(request, 'app/index.html')
def contact(request):
if request.method=='POST':
form=someform(request.POST)
if form.is_valid():
field1=form.cleaned_data['field1']
field2=form.cleaned_data['field2']
return HttpResponse("valid")
else:
return HttpResponse("invalid")
else:
form=someform()
return HttpResponse("error")
The problem is , it never enters (if form.is_valid()) . Am i missing something ? please help
in the index.html
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input type="submit" id="submit" name="submit">
</form></body></html>

First pass your form to index.html, when the request is not POST in views.py:
else:
form=someform()
return render(request, 'index.html', locals())
In template you should make it like this:
<form action="contact" method="POST" xmlns="http://www.w3.org/1999/html">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn">Submit</button>
</form>

When receiving the POST query, Django is looking for the 2 fields of IDs id_field1 and id_field2, litteraly, thus your HTML is to be the following:
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="id_field1" name="field1">
<input type="text" id="id_field2" name="field2">
<input type="submit" id="submit" name="submit">
</form>
</body>
</html>
Another solution is to use the {{ form.as_p }} or {{ form.as_table }} to render the inputs inside or tags automatically.
You could also add {{ form.non_field_errors }}, {{ form.field1.errors }}, and {{ form.field2.errors }} in your current HTML to display the form errors when validation fails.

Related

Django form is not showing up

Here is my forms.py
from django import forms
class EmailForm(forms.Form):
from_ = forms.EmailField(max_length=50)
Here is my views.py
from django.shortcuts import render
from .forms import EmailForm
def index(request):
return render(request, "base.html")
def emailSender(request):
form = EmailForm()
return render(request, "base.html", {"form" : form})
And finally here is my html template
<form id="form" method="post">
{% csrf_token %}
{{ form }}
<div class="form-outline mb-4">
<label class="form-label" for="from">From:</label>
{{ form.from_ }}
</div>
Any of my {{ form }} does not work. When I check the inspect tab they both are not created so I think this isn't some css problems here.
Tried the form code in shell , seems to be working ,try the following edits:
use a clear name to the field in forms.py
from django import forms
class EmailForm(forms.Form):
email = forms.EmailField(max_length=50)
Fix the html template (don't forget to close the form, I suppose you're taking proper care of other html tags: html, head, body, ...)
<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>

Display two ModelForm class in a single Django html page

I am trying to create 2 forms and display it in a single Django HTML page. I created 2 Modelform class like this
class CompanyForm(forms.ModelForm):
class Meta:
model = Company
fields = "__all__"
class ToyForm(forms.ModelForm):
class Meta:
model = Toy
fields = "__all__"
In the HTML page I am only able to embed the model = Company. How can I embed the Model = Toy in the same page, what I tried brings up the same Company Form. Here is the html code
<form method="post">
{% csrf_token %}
<h2> Company Form </h2>
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
<form method="post">
{% csrf_token %}
<h2> Toy Form </h2>
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
In views.py
from django.shortcuts import render
from myapp.form import CompanyForm, ToyForm
def index(request):
cform = CompanyForm()
tform = ToyForm()
context={'cform':cform, 'tform':tform}
return render(request,"index.html",context)
In HTML Page
<form method="post">
{% csrf_token %}
<h2> Company Form </h2>
{{ cform.as_p }}
<input type="submit" value="Submit" />
</form>
<form method="post">
{% csrf_token %}
<h2> Toy Form </h2>
{{ tform.as_p }}
<input type="submit" value="Submit" />
</form>

Django 'float' object has no attribute 'user' while using login decorator

I'm trying to build a django app and the app works, great so far.
Right now i'm in the middle of making sure the user needs a login so they can log in.
if the user is logged in than the user can use an machine-learning model to solve a problem.
The error message I'm getting is 'float' object has no attribute 'user' and this started after I used the #login_required function in django.
NOTE: The user is login in via the localhost:8000/admin/ panel Django provides.
(later I will change that) after I fix this bug
views.py
def home(request):
return render(request, 'home.html')
#login_required
def dashboard(request):
return render(request, 'index.html')
#login_required
def getPredictions(temp_normal, hour,hour_x,hour_y):
import pickle
model = pickle.load(open("test_model.sav", "rb"))
prediction = model.predict([[temp_normal, hour,hour_x,hour_y]])
return prediction
#login_required
def result(request):
temp_normal = float(request.GET['temp_normal'])
hour = float(request.GET['hour'])
hour_x = float(request.GET['hour_x'])
hour_y = float(request.GET['hour_y'])
result = getPredictions(temp_normal, hour,hour_x,hour_y)
return render(request, 'result.html', {'result': result})
html code
index.html
{% extends "base.html" %}
{% block content %}
<div class="content">
<div class="row">
<div class="col-lg-4">
<div class="card card-tasks">
<h1> </h1>
<form action="{% url 'result' %}">
{% csrf_token %}
<p>temp_normal:</p>
<input class="form-control" type="text" name="temp_normal">
<br>
<p>Weging:</p>
<input class="form-control" type="text" name="Weging">
<br>
<p>str:</p>
<input class="form-control" type="text" name="straling">
<br>
<p>hour:</p>
<input class="form-control" type="text" name="hour">
<br>
<p>hour_x:</p>
<input class="form-control" type="text" name="hour_x">
<br>
<p>hour_y:</p>
<input class="form-control" type="text" name="hour_y">
<br>
<input class="form-control" type="submit" value='Bereken'>
</form>
</div>
</div>
</div>
</div>
{% endblock content %}
results.html
{% extends "base.html" %}
{% block content %}
<h1>Prediction</h1>
{{ result }}
<p>resultaat</p>
{% endblock content %}
the decorator login_required is just for views and expects a request object as first param, thats why the error, getPredictions is not a view is just a function. remove the decorator login_required to getPredictions and will work.

Not able to perform Update Operation on Django

I am making todo application and i am having problem doing the update operation
views.py
def update(request, task_id):
task = Task.objects.get(pk=task_id)
if request.method == 'POST':
form = TaskForm(request.POST or None, instance=task)
if form.is_valid():
form.save()
return redirect('/')
return render(request, 'update.html', {'task': task})
forms.py
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = '__all__'
urls.py
path('update/<int:task_id>', views.update, name='update'),
update.html
{% extends 'base.html' %}
{% block content %}
{% if task %}
<form class="form-inline my-2 my-lg-0" method="POST" >
{% csrf_token %}
<input type="search" class="form-control mr-sm-2" name="task" value="{{task.text}}">
<input type="hidden" name="completed" value="{{task.completed}}">
<button type="submit" class="btn btn-outline-secondary my-2 ">Edit Task</button>
</form>
{% endif %}
{% endblock %}
I am able to get the Value of the selected item in textbox but when i edit it and press Edit Task Nothing happens .
# The url name is update, so your action submit should go to 'update'
<form action="{% url 'update' task_id=task.pk %}" method="POST" class="form-inline my-2 my-lg-0">
…
</form>

Django : get data and edit in the same form, edit in one place

I've been working to make an edit form where shows data saved in db and user can edit it like jsp model and view. When user click button it shows add form but all the relevant information in db is already filled up in the form, so user can modifying old data and once they click submit button it redirect to main.
I succeeded to display a form when user click edit button but failed to get data.
this is views.py
#login_required
def update_article(request, article_no):
article = get_object_or_404(Article, no=article_no)
if request.method == "POST":
form = ArticleForm(request.POST, instance=article)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('blog.views.detail', no=article.no)
else:
form = ArticleForm(instance=article)
return render(request, 'blog/update_article.html', {'form': form})
urls.py
url(r'^update_article/(?P<article_no>[0-9]+)/$', views.update_article, name='update_article'),
update_article.html
{% extends 'blog/base.html' %}
{% block body %}
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<button type="submit" class="button-primary">submit</button>
</form>
list
{% endblock %}
detail.html
This is part of the page send users to update_article.html
<form action="{% url 'blog:update_article' item.no %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="no" value="{{ item.no }}" />
<button type="submit" class="button-primary">edit</button>
</form>
form_template.html
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2" for="title">{{ field.label_tag }</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
In update_article views
pass article object with form
return render(request, 'blog/update_article.html', {'form': form, 'article': article})
and then form in html page
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<input class="u-full-width" type="text" name="title" value="{{article.title}}"/>
<textarea class="u-full-width" name="content" value="{{article.content}}"></textarea>
<button type="submit" class="button-primary">등록</button>
</form>
I think this would help your problem
also I guess your action link is not valid

Categories

Resources