how to send a form to html in django - python

I am trying to send a form to html using django. this is the form
from django import forms
class contactForm(forms.Form):
name = forms.CharField(required=False, max_length=100,help_text='100 characters max.')
email = forms.EmailField(required=True)
comment = forms.CharField(required=True, widget=forms.Textarea)
The view file is
from django.shortcuts import render
from .forms import contactForm
# Create your views here.
def contact(request):
form = contactForm(request.POST or None)
if form.is_valid():
print (request.POST)
context = locals()
template = 'contact.html'
return render(request, template, context)
and the html file which is named correctly is,
{% extends 'base.html' %}
{% block content %}
<h1> Contact </h1>
<form method='POST' action=''> {% csrf_token %}
{{ form.as_p }}
<input type='submit' value='submit form' class='btn btn-default' />
</form>
{% endblock %}
When you visit the page the only thing that shows up is the h1 tag how do i fix this?

You can try
def contact(request):
form = contactForm(request.POST or None)
if form.is_valid():
print (request.POST)
context = locals()
template = 'contact.html'
return render(request, template, context)
return render(request, 'contact.html', {'form': form})

The correct format of rendering a from is this:
from django.shortcuts import reverse
from django.http import HttpResponseRedirect
from . import models
from . import forms
def contact(request):
if request.POST == 'POST':
form = forms.contactForm(request.POST or None)
contact_model = models.contactModel() #err is here name it with appropriate model name contactModel is just an example
if form.is_valid():
contact_model.name = form.cleaned_data['name']
contact_model.email = form.cleaned_data['email']
contact_model.comment = form.cleaned_data['comment']
contact_model.save()
return HttpResponseRedirect('/success/')) #desired url to redirect, you can use reverse to call templates according to url names
else: #if request is GET
form = forms.contactForm()
context = {
'form': form
}
template = 'contact.html'
return render(request, template, context=context)
Do not use action in your template, just set your urls.py to redirect to the desired view.

Related

Django register form

so, I made the registration page with django and it doesn't show the form
register.html
<form method="post">
{{ form.as_table }}
{% csrf_token %}
<input type='submit' value="Register">
</form>
and this is the views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'register.html', { 'form ' : form})
def login(request):
return render(request, 'login.html')
And all it shows is the register button
Could be one of two things:
Put the {% csrf_token %} before the form variable in your template.
Don't put any whitspace in the form key in your context dictionary (so instead of ' form ' it should be 'form')
I think you mistakenly wrote "form " instead of "form" and also put {% csrf_token %} in the form tag right before the rendering

Why is my Django form not "valid"? Can't get the POST request to update database

I am trying to create a user profiles for users in my Django app. I have the form displaying where I want it to and when I try to submit, nothing happens.
I put a print statement after the form.is_valid in my view.py and found that it wasn't 'valid' but I have no idea why.
I have tried several different ways to 'clean' / 'validate' data but I can't get past the form being 'invalid.'
Any help would be greatly appreciated!
urls:
path('userinfo/', views.user_info, name='userinfo')
form template:
{% extends "base.html" %}
{% load bootstrap4 %}
{% block content %}
<div class="container">
<h1>Enter User Info</h1>
<form method="POST" class="form">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" class="btn btn-primary" value="Create Profile">
</form>
</div>
{% endblock %}
view:
def user_info(request):
form = ProfileForm()
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
form.save()
else:
form = ProfileForm()
return render(request, 'miraDashboard/form.html', context={'form': form})
model:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
name = models.CharField("Full Name", max_length=1024)
job_role = models.CharField("Role", max_length=254, default="Seeking Job Opportunities")
zip_code = models.CharField("Zip Code", max_length=5)
user_image = models.ImageField("Upload Profile Picture", upload_to='images/')
def __str__(self):
return f'{self.user.username} Profile'
form:
from django.forms import ModelForm
from .models import Profile
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['name','job_role','zip_code', 'user_image']
if you want to see errors in form change else statmant:
def user_info(request):
form = ProfileForm()
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
form.save()
else:
print(form.errors.as_data()) # here you print errors to terminal
return render(request, 'miraDashboard/form.html', context={'form': form})
after form.is_valid() you don't need to set it again (form = ProfileForm() in else statment). this way your form will get errors( you cen see them in form.errors).

form.save() not working my form.save for updating data isnt working

form.save() not working my form.save for updating data isnt working when i try to update my post it shows the original unedited post it dosent save the updated version.i donnt know whats causing the error idk if its views or anything in template if anyone could help i will be very grateful please help.
here is the code:
views.py
from django.shortcuts import render
from django.shortcuts import HttpResponseRedirect
from .models import Post
from .forms import PostForm
def post_list(request):
posts = Post.objects.all()
context = {
'post_list': posts
}
return render(request, "posts/post_list.html", context)
def post_detail(request, post_id):
post = Post.objects.get(id=post_id)
context = {
'post': post
}
return render(request, "posts/post_detail.html", context)
def post_create(request):
form = PostForm(request.POST or None)
if form.is_valid():
form.save()
return HttpResponseRedirect('/posts')
context = {
"form": form,
"form_type": 'Create'
}
return render(request, "posts/post_create.html", context)
def post_update(request, post_id):
post = Post.objects.get(id=post_id)
form = PostForm(request.POST or None, instance=post)
if form.is_valid():
form.save()
return HttpResponseRedirect('/posts')
context = {
"form": form,
"form_type": 'Update'
}
return render(request, "posts/post_update.html", context)
def post_delete(request, post_id):
post = Post.objects.get(id=post_id)
post.delete()
return HttpResponseRedirect('/posts')
urls.py
from django.urls import path
from .views import post_list, post_detail, post_create, post_update, post_delete
urlpatterns = [
path('', post_list),
path('create/', post_create),
path('<post_id>/', post_detail),
path('<post_id>/update', post_update),
path('<post_id>/delete', post_delete),
]
post_update.html
<h1>welcome to post {{ form_type }}</h1>
<form method="POST" action=".">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button type="submit">{{ form_type }}</button>
</form>
action="." takes you from <post_id>/update to <post_id>/. You can fix this a few ways:
Change it to action="", which will submit from <post_id>/update to <post_id>/update.
Add a slash to the URL, i.e. path('<post_id>/update/', ...). Then action="." will submit from <post_id>/update/ to <post_id>/update/
Use the {% url %} tag instead of hardcoding the action. In your case there's a few changes you'd need to make, so I'll leave that as a challenge for you. The docs on reversing URLs should help.

Store name value with Django sessions for another view

The error that Django throws at me when I fill in the form is: 'GetSessionName' object has no attribute 'name' and I have never worked with sessions before so I don't know how to solve this problem. The idea of the site is to have a small Login screen where you type your name then move to the chat.
views.py
from django.shortcuts import render, redirect
from django.utils import timezone
from .models import *
from .forms import Chat, GetSessionName
def chat(request):
Messages = Message.objects.all().order_by('-created')
form = Chat()
if request.method == "POST":
form = Chat(request.POST)
if form.is_valid():
form.save()
return redirect ("chat")
name = request.session['name']
context = {"Message": Messages, "form": form, 'name': name}
return render(request, 'chat/chat_messages.html', context)
def login(request):
form = GetSessionName()
if request.method == "POST":
form = GetSessionName(request.POST)
if form.is_valid():
request.session['name'] = form.name
return redirect('chat')
context={'form': form}
return render(request, 'chat/chat_login.html', context)
forms.py
from django import forms
from django.forms import ModelForm
from .models import Message
from .models import *
class Chat(forms.ModelForm):
class Meta:
model = Message
fields = "__all__"
class GetSessionName(forms.Form):
name = forms.CharField(max_length=30)
chat_login.html
{% extends 'chat/base.html' %}
{% block content %}
<form method="POST" action="">
{% csrf_token %}
{{form}}
</form>
{% endblock content %}
you clearly right used sessions but the problem is getting field name in dicts of forms.
You just should add 'cleaned_data'
def login(request):
form = GetSessionName()
if request.method == "POST":
form = GetSessionName(request.POST)
if form.is_valid():
request.session['name'] = form.cleaned_data['name']
return redirect('chat')
context={'form': form}
return render(request, 'chat/chat_login.html', context)
Best regards

Django UserCreationForm neither gives error message nor registering user

I am beginner to python Django. And trying build an posting article website with the help of tutorials. I got stuck at UserCreationForm. I have created a form using UserCreationForm, but when I am submitting the form I am not able to neither submit the form nor getting any error message on the page.
My views.py code
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.template.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
print args
return render_to_response('register.html', args)
def register_success(request):
return render_to_response('register_success.html')
register.html
{% extends "base.html" %}
{% block content %}
<h2>Register</h2>
<form action="/accounts/register/" method="post"> {% csrf_token %}
{{form}}
<input type="submit" value="Register"/>
</form>
{% endblock %}
register_success.html
{% extends "base.hml" %}
{% block content %}
<h2>You have registered!</h2>
<p>Click Here to login again</p>
{% endblock %}
The problem is that you are always creating a blank form.
args['form'] = UserCreationForm()
This means that you do not see any errors for POST requests when the form is invalid.
Instead, you should only create the blank form for GET requests.
from django.shortcuts import render
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
form = UserCreationForm()
args = {'form': form}
return render(request, 'register.html', args)
Note that I have simplified the view by using render instead of the obsolete render_to_response. That means you don't need to handle csrf manually.
You can use Django Generic Views, specifically CreateView, it will make your life a lot easier. You can use it like so:
from django.views.generic import CreateView
class CreateUserView(CreateView):
template_name = 'register.html'
form_class = UserCreationForm
success_url = '/accounts/register_success'
Add this to your urls.py and you are good to go:
from mysite.views import CreateUserView
# add this url pattern
url(r'^sign_up/$', CreateUserView.as_view(), name='signup'),

Categories

Resources