How do you render form from views in template without model? - django

I have a problem with my Django Code.I'm trying to render a form from views to template and i'm just seeing the submit button. I noticed that we can use forms dynamically by introducing it like this {{ form }}, but when I use it, I just see the "submit" button on the page(Sorry I don't know how to upload a local image here). I join my four files: views.py, home.html, forms.py and urls.py
Thank you in advance
home.html
<form method="POST" novalidate action="/config">
{% csrf_token %}
<fieldset>
<legend class="border-bottom mb-4">Home</legend>
{{ form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
views.py
def inputHome(request):
form = InputHomeForm()
if request.method == 'POST':
form = InputHomeForm(request.POST)
if form.is_valid():
mk = form.cleaned_data['mk']
return HttpResponseRedirect('blog-config')
else:
form = InputHomeForm()
return render(request, 'blog/home.html', {'form': form})
forms.py
class InputHomeForm(forms.Form):
mk = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
urls.py
urlpatterns = [
path('home/', blog_views.home, name='blog-home'),
]
I don't have an error message so i don't have an idea of the problem.

You are missing form tag in html.
HTML should be,
<form method='post'>
{% csrf_token %}
<fieldset>
<legend class="border-bottom mb-4">Home</legend>
{{ form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>

Slightly unrelated (cf Nishant's answer for the main issue), but here:
if request.method == 'POST':
form = InputHomeForm(request.POST)
if form.is_valid():
mk = form.cleaned_data['mk']
return HttpResponseRedirect('blog-config')
else:
form = InputHomeForm()
In the else clause, you're replacing the bound invalid form (which carries the validation errors) with an unbound form, so you'll never get the error messages. Just remove the whole else clause.

Related

User form foreignkeyfield form not valid

I was creating a post based website i want to show the author's name to show up in the post it works in the admin site when adding posts but when i try uploading a post from the site the form is not getting validated therefore it is not getting saved please help
model :
from django.conf import settings
class MemeImg(models.Model):
Title = models.CharField(max_length=500)
op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
Post_Img = CloudinaryField('Post')
forms :
class PostImg(forms.ModelForm):
class Meta:
model = MemeImg
fields = ['Title', 'op', 'Post_Img']
view :
#login_required(login_url='/login')
def post(request):
func = data(request)
if request.method == 'POST':
form = PostImg(request.POST, request.FILES, instance=request.user)
form.op = request.user
if form.is_valid():
print('success')
posts = form.save(commit=False)
posts.op = request.user
form.save()
return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ')
else:
print("fail")
form = PostImg(request)
ctx = {
'form': form,
'url': func[0],
'name': func[1],
'date': func[2],
}
return render(request, 'Post.html', ctx)
and finally the post page template :
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
{{ form.Title|materializecss }}
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file">
</div>
<div class="file-path-wrapper">
{{ form.Post_Img }}
<input class="file-path validate" type="text">
</div>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
If anymore code is required please comment it
Thanks a lot
I think your problem come from the form instance which is instance=request.user, actually the instance is supposed to be the MemeImg object instance and not the user, that's making it not to save the image. So i have deleted the instance and also i don't know what you are using those extra context variable for 'url': func[0],'name': func[1], 'date': func[2] ?, so i deleted them too keep things simple. Now i think you should be able to save without any Issues.
#login_required(login_url='/login')
def post(request):
if request.method == 'POST':
form = PostImg(request.POST, request.FILES)
if form.is_valid():
print('success')
data = form.save(commit=False)
data.op = request.user
form.save()
return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ')
else:
print("fail")
form = PostImg(request.POST)
ctx = {
'form': form,
}
return render(request, 'Post.html', ctx)
Also your form had in it {{ form.Post_Img }} which i don't no what you are looking to accomplish with that variables?, the right way is doing {{ form.as_p }} or simply just calling the form like this {{ form }} so i have made the correction in you HTML
too.
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
{{ form.Title|materializecss }}
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file">
</div>
<div class="file-path-wrapper">
{{ form }}
<input class="file-path validate" type="text">
</div>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>

Why don't my entries get saved in the database in Django?

The post requests from the frontend do not get saved in the database, without any error shown. However, when I manually add entries from the admin panel, it shows on the frontend.
My index.html(form part):
<form class="main__input--form" method="POST">
{% csrf_token %}
<p class="main__input--text">
<textarea name="content" id="content" class="main__input--content" cols="35" rows="8" aria-label="Entry content" placeholder="Enter text here..."></textarea>
</p>
<button class="main__input--submit" type="submit">Vent</button>
</form>
My extension of index which loops through the database entries:
{% for obj in all_vents %}
<div>
<h1>{{obj.vent}}</h1>
</div>
<br />
{% endfor %}
My models.py:
class Vents(models.Model):
vent = models.CharField(max_length=10000)
def __str__(self):
return self.vent
My forms.py:
from django import forms
from .models import Vents
class VentForm(forms.ModelForm):
class Meta:
model = Vents
fields = ['vent']
My views.py:
from django.shortcuts import render, redirect
from .forms import VentForm
from .models import Vents
def ventout(request):
if request.method == "POST":
form = VentForm(request.POST or None)
if form.is_valid():
form.save()
return redirect("ventout")
else:
all_vents = Vents.objects.all()
return render(request, "ventout.html", {"all_vents": all_vents})
Views:
def ventout(request):
all_vents = Vents.objects.all()
if request.method == "POST":
form = VentForm(request.POST or None)
if form.is_valid():
form.save()
return redirect("ventout")
else:
form = VentForm()
context = {"all_vents": all_vents, "form":form}
return render(request, "ventout.html", context)
Template:
<form class="main__input--form" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="main__input--submit">Vent</button>
</form>
you could install/use "crispy_forms_tags" to make the form look better,
https://django-crispy-forms.readthedocs.io/en/latest/index.html
if you want to go further you could install/use "widget_tweaks"
https://pypi.org/project/django-widget-tweaks/
Your index.html from part should have {{ form }} form tag, as I guess.
Try Using following code
<form class="main__input--form" method="POST">
{% csrf_token %}
{{ form }}
<p class="main__input--text">
<textarea name="content" id="content" class="main__input--content"
cols="35" rows="8" aria-label="Entry content" placeholder="Enter text here...">
</textarea>
</p>
<button class="main__input--submit" type="submit" value="Submit">Vent</button>
</form>

Displaying 3 separate forms on the same page in django

I'm working on a single page site which is to have 3 different forms on the same page:
Tour form
flight form
bookform
I created the forms using model form, but how do I display the forms such that my site will know which form I'm submitting data to ?
you need pass your forms in your views.py
from your_app.forms import TourForm, FlightForm, BookForm
def your_view_name(request):
if request.method == 'POST':
tour_form = TourForm(request.POST or None)
flight_form = FlightForm(request.POST or None)
book_form = BookForm(request.POST or None)
# so you have 3 different forms
if tour_form.is_valid():
tour_form.save()
return redirect('some_url')
elif flight_form.is_valid():
flight_form.save()
return redirect('some_url')
elif book_form.is_valid():
book_form.is_save()
return redirect('some_url')
else:
return redirect('some_url')
else:
tour_form = TourForm()
flight_form = FlightForm()
book_form = BookForm()
context = {
'tour_form': tour_form,
'flight_form': flight_form,
'book_form': book_form
}
return render(request, 'your_template_name.html', context)
then simply in your template add your forms
<form method='post'>
{% csrf_token %}
{{ tour_form }}
<button class='btn btn-primary' type='submit'>submit</button>
</form>
<form method='post'>
{% csrf_token %}
{{ flight_form }}
<button class='btn btn-primary' type='submit'>submit</button>
</form>
<form method='post'>
{% csrf_token %}
{{ book_form }}
<button class='btn btn-primary' type='submit'>submit</button>
</form>

How to retrieve row from database by matching form field

I'm making an Inventory Management System, which now I'm trying to make my form input more efficient.
I have 2 tables of Arrival and Withdraw
In table Arrival there are prod_cd , prod_nm, ..., withdraw
In table Withdraw there are prod_cd, prod_nm, withdraw
I want to make my form only input the prod_cd and then the field of prod_nm and withdraw would automatically retrieved from the Withdraw table
I've try to make another page so there will be Inquiry first to retrieve the Withdraw.objects, and then Add the record but it throw an error
views.py
def add_cycle(request, model, cls, inquiry):
if request.method == "POST":
form = cls(request.POST)
if form.is_valid():
form.save()
return redirect(inquiry)
else:
form = cls()
return render(request, 'add_new.html', {'form': form})
def add_arrival(request):
return add_cycle(request, Arrival, ArrivalForm, inquiry_arrival)
def inquiry_cycle(request, pk, model, cls):
instance= Withdraw.objects.get(pk=pk)
form = cls(instance=instance)
if request.method == "POST":
form = cls(request.POST,instance=instance)
if form.is_valid():
form.save(commit=True)
return redirect ('index')
else:
form = ArrivalForm(instance=instance)
return render_to_response('add_newInquiry.html', {'form': form})
def inquiry_arrival (request, pk):
return inquiry_cycle(request, pk, Arrival, ArrivalForm)
urls.py
url(r'^add_arrival$', add_arrival, name='add_arrival'),
url(r'^inquiry_arrival$', inquiry_arrival, name='inquiry_arrival'),
forms.py
class ArrivalForm(forms.ModelForm):
class Meta:
model = Arrival
fields = ('prod_cd', 'prod_nm', 'quantity', 'issues', 'location', 'withdraw', 'expired_date', 'sup_sheet')
add_new.html
<form method="POST">
<br>
{% csrf_token %}
<h4>ADDING ITEMS</h4>
<div class="form-group row">
<label for="id_{{ form.prod_cd.name }}" class="col-2 col-form-label"> {{ form.prod_cd.label }} </label>
<div class="col-10">
{{ form.prod_cd }}
</div>
</div>
<button type="submit" class="btn btn-primary" name="button"> Inquiry</button>
</form>
add_newInquiry.html
<form method="POST">
<br>
{% csrf_token %}
<h4>ADDING ITEMS</h4>
{% for field in form %}
<div class="form-group row">
<label for="id_{{ field.name }}" class="col-2 col-form-label"> {{ field.label }} </label>
<div class="col-10">
{{ field }}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary" name="button"> Add Record</button>
</form>
I expect my form would retrieve some of it fields value from database, but I still got an error
ValueError at /add_arrival
The view inventory.views.add_arrival didn't return an HttpResponse object. It returned None instead.
Let's trace the error together! So, The view inventory.views.add_arrival didn't return an HttpResponse object. It returned None instead. What this means is that when Django attempts to fetch the add_arrival view, no templates are returned.
Let's take a further look at add_arrival view. It calls the function add_cycle. Pay attention to the last parameter inquiry_arrival, which is a method.
Now, in the add_cycle function, if the form is valid, we return redirect(inquiry) where inquiry is the inquiry_arrival method. However, since inquiry is a method, it needs to be called for something to be returned! To call this method, you should have added brackets behind inquiry, like so: redirect(inquiry()). Refer to this link for further information. Good luck!

Django - How to Authenticate users while logging in (or) registering while using django-bootstrap-toolkit?

I am trying to authenticate a user(using the simple authenticate() function) in django.
def auth(request):
if request.method == 'POST':
auth_form = AuthenticationForm(request.POST)
if auth_form.is_valid():
auth_form.save()
user = authenticate(username=request.POST['id_username'],password=request.POST['id_password'])
if user is not None:
login(request,user)
return redirect('/profile/home/')
else:
return redirect('/')
else:
return redirect('/')
def register(request):
if request.method == 'POST':
form = SimpleUserCreation(request.POST)
if form.is_valid():
form.save()
user = authenticate(username=request.POST['id_username'],password=request.POST['id_password1'])
login(request,user)
return redirect('/profile/home/')
else:
return redirect('/')
This is the template displaying the forms - Just wanted to display login and register forms in the same page(for this example)
{% extends 'base.html' %}
{% load bootstrap_toolkit %}
{% block content %}
<div class="row">
<div class="span4 offset1 login">
<form class="form-signin" action="/auth/" method="POST">
{% csrf_token %}
{{ auth_form|as_bootstrap }}
<br>
<center>
<button class="btn btn-large btn-primary" type="submit">
Sign In
</button>
</center>
</form>
</div>
<div class="span4 offset2 signup">
<form action="/register/" method="POST">
{% csrf_token %}
{{ form|as_bootstrap }}
<br>
<center>
<button class="btn btn-large btn-primary" type="submit">
Register
</button>
</center>
</form>
</div>
</div>
{% endblock %}
I am getting an error like this:
ValueError at /auth/
The view SimpleUserAuth.auth.views.auth didn't return an HttpResponse object.
Any idea where i am going wrong?? I think its the authenticating function's inability to find the correct id for the fields...maybe i am wrong. I am a Noob :|
Cheers
In your auth method, if auth_form.is_valid() returns False, you do not return a response object.
The same is the case in def register(request): . If it is a GET request, the method does not return a response object.
Hence the error(s)
I made the mistake in these lines -
1) AuthenticationForm takes argument as follows:
AuthenticationForm(data=request.POST)
2) u can't save AuthenticationForm.
auth_form = AuthenticationForm(request.POST)
if auth_form.is_valid():
auth_form.save()
Thanks for the help karthik :)