Django 2.0 Form is not saving data to database - python

so I have a very simple blog app and I'm trying to figure out why the data entered in the form doesn't save to the database and it doesn't redirect me to my index page.
forms.py
from django import forms
class NewBlog(forms.Form):
blogger = forms.CharField(max_length=20, widget=forms.TextInput(attrs=
{'placeholder' : 'Name'}))
text = forms.CharField(widget=forms.Textarea(attrs={'placeholder' :
'Text'}))
new_blog.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>New Blog</title>
</head>
<body>
<form action="{% url 'new_blog' %}" method="POST">
{% csrf_token %}
<h2>Write your blog here:</h2>
{{ form }}
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
views.py
from django.shortcuts import render, redirect
from .models import BlogPost
from .forms import NewBlog
def index(request):
blogs = BlogPost.objects.all()
context = {'blogs' : blogs}
return render(request, 'blog/index.html', context)
def newBlog(request):
if request == 'POST':
form = NewBlog(request.POST)
if form.is_valid():
blogger = form.cleaned_data['blogger']
text = form.cleaned_data['text']
new_blog = BlogPost(blogger = blogger, text = text)
new_blog.save()
return redirect('index')
else:
form = NewBlog()
context = {'form' : form}
return render(request, 'blog/new_blog.html', context)

I think the problem is likely to be the first line of your view.
if request == 'POST':
should be:
if request.method == 'POST':

To save an Object into database
instead of
new_blog = BlogPost(blogger = blogger, text = text)
new_blog.save()
use the best way:
BlogPost.objects.create(blogger = blogger, text = text)
It will be automatically saved

Related

Why Django from in Invalid?

I create a django form. I am also inserting the valid values in the form field but still getting form not valid error. I used the same code yesterday and it was working fine, but I don't know why its giving the not valid error, What might be the reason for this?
Here is My Code:
View.py
from django.shortcuts import render,redirect
from django.views.generic import View,TemplateView
from .forms import Registration_Form
from .models import User_Registration
from django.contrib import messages
# Create your views here.
class MainPageView(TemplateView):
template_name='main.html'
class LoginView(TemplateView):
template_name='login.html'
def RegistrationView(request):
form=Registration_Form()
if request.method=='POST':
print(request.POST)
if form.is_valid():
form.save()
print("Valid")
return redirect('login_view')
else:
print("Not Valid")
# messages.error(request,"Form is Invalid!")
return redirect('registration_view')
else:
return render(request,'registration.html',{'form':form})
# template_name='registration.html'
forms.py
from django import forms
from .models import User_Registration
class Registration_Form(forms.ModelForm):
class Meta:
model=User_Registration
fields=('company_name','username','password','email')
widgets={
'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}),
'username':forms.TextInput(attrs={'class':'form-control'}),
'password':forms.PasswordInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
}
registration.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="form-group">
<br><br><br>
<h2 style="padding-left: 480px;">Registration Form</h2>
<br>
<form method="POST" action="">
{{form.as_p}}
{% csrf_token %}
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
A form is always invalid if no data is passed. You thus need to pass the request.POST (and perhaps request.FILES) when constructing the form:
def RegistrationView(request):
if request.method == 'POST':
form = Registration_Form(request.POST, request.FILES)
if form.is_valid():
form.save()
print('Valid')
return redirect('login_view')
else:
print('Not Valid')
else:
form = RegistrationForm()
return render(request,'registration.html',{'form':form})
You forgot to initialize your form with the POST data :
def RegistrationView(request):
form=Registration_Form()
if request.method=='POST':
print(request.POST)
form = Registration_Form(request.POST) # line added
if form.is_valid():
form.save()
...

How can I make Django render in the browser?

I'm trying to utilize Django forms.ModelForm function. However, I can not get it to render in the browser (Firefox and Chrome tested). In both browser inspection of code, the table\form does not show and there is no error coming from Django at all. The only thing that shows from the html file is the "Save button" Is there something I am missing here?
In Models.py
from django.db import models
class Product_sell_create(models.Model):
product_product_sell = models.CharField(max_length=120)
product_price_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_volume_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_location_sell = models.CharField(max_length=120)
product_description_sell = models.TextField(blank=False, null=False)
Forms.py
from django import forms
from .models import Product_sell_create
class ProductName(forms.ModelForm):
class Meta:
model = Product_sell_create
fields = [
'product_product_sell',
'product_volume_sell',
'product_price_sell',
'product_location_sell',
'product_description_sell'
]
Views.py
from django.shortcuts import render
from .forms import ProductName
def products_create_view(request):
form = ProductName(request.POST or None)
if form.is_valid():
form.save()
form = ProductName()
context = {
'form': form
}
return render(request, "sell.html", context)
sell.html
{% include 'navbar.html' %}
<h1> Upper test</h1>
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST </h1>
{% block content %}
{% endblock %}
just did it, you would have problems POSTing your object too:
views.py:
from django.shortcuts import render, redirect
from .forms import ProductName
from .models import Product_sell_create
def products_create_view(request):
if request.method == 'POST':
form = ProductName(request.POST)
if form.is_valid():
prod = form.save(commit=False)
prod.save()
return redirect('../thanks')
else:
form = ProductName()
context = {
'form': form
}
return render(request, "form_test.html", context)
def thanks_view(request):
query = Product_sell_create.objects.all()
return render (request, 'thanks.html', {'query' : query})
forms.py and models.py keeps the same
sell.html:
<h1> Upper test</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST2 </h1>
thanks.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{ query }}</h1>
<h2>THANKS</h2>
</body>
</html>
did you create the 'sell.html' inside a 'templates' folder in your app folder?
MyApp/templates/sell.html

Django - Update User instance by form

Befor all :
Djano VERSION = 1.8, and it's obligatory that I use this version
Question
I do not know why I cannot update the User instance by a form.
I mean by updating: changing the value in the database and in the request
The User model is not created by me but I use django.contrib.auth.models.User
Code
This is my code
app/forms.py
from django import forms
from django.contrib.auth.models import User
class ModificationForm(forms.ModelForm):
class Meta:
model = User
fields = ['email']
app/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from app.forms import ModificationForm
#login_required
def profil(request):
if request.method == "POST":
form = ModificationForm(data=request.POST, instance=request.user)
if form.is_valid():
form.save()
else:
form = ModificationForm()
return render(request, "profil.html", {'form':form})
profile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Profil</title>
</head>
<body>
<h1>Profil</h1>
<a href='/deconnexion'> Logout </a>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Enregistrer" />
</form>
</body>
</html>
Your posting to the wrong link!
If you do not know it, just leave the action empty in the html insted of action="." !

in my project how can i set http session tracking login time for 30 second only

In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password.
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from .models import Reg
from .forms import LoginForm
from .forms import RegForm
def reg(request):
if request.method == 'POST':
form = RegForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponse('reg success')
else:
print(form.errors)
return HttpResponse("error")
else:
form = RegForm()
return render(request,'reg.html', {'form': form})
def login(request):
if request.method == "POST":
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
un =MyLoginForm.cleaned_data['user']
pw=MyLoginForm.cleaned_data['pwd']
dbuser = Reg.objects.filter(user=un,pwd=pw)
if not dbuser:
return HttpResponse('opppppss login faield')
else:
return HttpResponse('login success')
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def home(request):
return render(request,'home.html')
models.py
from __future__ import unicode_literals
from django.db import models
class Reg(models.Model):
user = models.CharField(primary_key=True,max_length=20)
pwd = models.CharField(max_length=20)
fname=models.CharField(max_length=10)
lname=models.CharField(max_length=10)
dob=models.DateField()
mobno=models.IntegerField()
forms.py
from django import forms
from .models import Reg
class RegForm(forms.ModelForm):
class Meta:
password = forms.CharField(widget=forms.PasswordInput)
model = Reg
widgets = {'pwd': forms.PasswordInput(),}
fields = ['user', 'pwd','fname','lname','dob','mobno']
class LoginForm(forms.Form):
user = forms.CharField(max_length=20)
pwd = forms.CharField(widget=forms.PasswordInput())
home.html
<!DOCTYPE html>
</html>
<html>
<body bgcolor="#00ffff">
<h1>welcome </h1>
click here to register<br>
click here to login
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
reg.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try adding this to your settings.py
SESSION_COOKIE_AGE = 30

working with forms in django

I want to write form and when submit it write "welcome!" in my page.But after I submit form method still is GET!!what's wrong?
this is my models:
from django.db import models
import django_tables2 as tables
from django import forms
class Form1(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
this is my view:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
# ContactForm was defined in the previous section
form = Form1(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
return render(request, 'student/Home.html',{'message':'welcome'})
else:
form = Form1() # An unbound form
return render(request, 'student/Home.html', {'form': form})
this is my template(Home.html):
<!DOCTYPE html>
<html>
<body>
<form action="{% url 'student:contact' %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit" />
</form>
<p>{{message}}<p>
</body>
</html>

Categories