Can't save data from HTML form to database Django - python

I'm trying to save data entered in this form (below) into a database:
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO</title>
</head>
<body>
{% if user.is_authenticated %}
<form id='add-task' method='post'>{% csrf_token %}
<div class="mb-3">
<input type="text" class="form-control" name="task-name" placeholder="task name">
</div>
<div class="mb-3">
<input type="text" class="form-control" name="task-desc" placeholder="description">
</div>
<div class="mb-3">
<input type="text" class="form-control" name="deadline" placeholder="YYYY-MM-DD">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</br></br>
{% endif %}
</body>
</html>
I'm not sure if I poorly formatted the code or if I'm using the wrong HTML. Is it possible to do this using HTML or should I just use a ModelForm?
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from .models import Task
def home(request):
# checks if user is logged in so that it can display task creation page
if request.user.is_authenticated:
return render(request, 'home.html', {'user': request.user})
# add new task ---> ALL THE CODE BELOW
if request.method == 'POST':
name = str(request.POST['task-name'])
desc = str(request.POST['task-desc'])
deadline = request.POST['deadline']
task = Task(task_name=name, task_desc=desc, task_deadline=deadline)
task.save()
#messages.success(request, "You've added a task.")
return render(request, 'home.html', {})

If you want to get your code as it is running:
def home(request):
# checks if user is logged in so that it can display task creation page
if request.user.is_authenticated:
if request.method == 'POST':
name = str(request.POST['task-name'])
desc = str(request.POST['task-desc'])
deadline = request.POST['deadline']
task = Task(task_name=name, task_desc=desc, task_deadline=deadline)
task.save()
return render(request, 'home.html', {'user': request.user})
else:
return render(request, 'home.html', {})
But you don't need to pass in user as context. This is available anyway.
So you could just do:
def home(request):
if request.method == 'POST':
name = str(request.POST['task-name'])
desc = str(request.POST['task-desc'])
deadline = request.POST['deadline']
task = Task(task_name=name, task_desc=desc, task_deadline=deadline)
task.save()
return render(request, 'home.html')
And request.user will still be available as {{ request.user.is_authenticated }} in your template.

Related

UnboundLocalError local variable 'context' referenced before assignment Django

I get the error below immediately after i add a new root url inside the root urls.py.
When i remove the dashboard view, url and i try to load index view, it renders successfully. What am i doing wrong or what can i do to resolve the issue.
Error message
UnboundLocalError at /blogapp/
local variable 'context' referenced before assignment
Request Method: GET
Request URL: http://127.0.0.1:8000/blogapp/
Django Version: 4.0.2
Exception Type: UnboundLocalError
Exception Value:
local variable 'context' referenced before assignment
My views
from multiprocessing import context
import re
from django.shortcuts import render
from django.http import HttpResponse
from .odd_finder_func import *
def index(request):
if request.method == 'POST':
odd1 = float(request.POST.get('odd1'))
odd2 = float(request.POST.get('odd2'))
odd3 = float(request.POST.get('odd3'))
func_def = odd_finder_true(odd1, odd2, odd3)
context = {
'Juice': func_def['Juice'],
'TotalImpliedProbability': func_def['TotalImpliedProbability'],
'HomeOdd': func_def['HomeOdd'],
'DrawOdd': func_def['DrawOdd'],
'AwayOdd': func_def['AwayOdd'],
'Home_True_Odd': func_def['Home_True_Odd'],
'Draw_True_Odd': func_def['Draw_True_Odd'],
'Away_True_Odd': func_def['Away_True_Odd'],
'True_Probability': func_def['True_Probability']
}
context = context
return render(request, 'index.html', context)
def dashboard(request):
return render(request, 'dashboard.html')
blogapp urls.py
from django.urls import path
from .views import *
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
myblog urls.py the root file.
from django.contrib import admin
from django.urls import path, include
from blogapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.dashboard, name='dashboard'),
path('blogapp/', include('blogapp.urls')),
]
index.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<div class="container">
<!-- Content here -->
<form action="" method="post">
{% csrf_token %}
<div class="mb-3">
<label for="Odd1" class="form-label">Home Odd</label>
<input type="number" class="form-control" name="odd1" id="odd1" min="0" value=" " step=".01" required='required'>
</div>
<div class="mb-3">
<label for="Odd2" class="form-label">Draw Odd</label>
<input type="number" class="form-control" name="odd2" id="odd2" min="0" value=" " step=".01" required='required'>
</div>
<div class="mb-3">
<label for="Odd3" class="form-label">Away Odd</label>
<input type="number" class="form-control" name="odd3" id="odd3" min="0" value=" " step=".01" required='required'>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<input class="btn btn-primary" type="reset" value="Reset">
</form>
</div>
<div class="container">
<p>Total Implied probability percentage: {{TotalImpliedProbability}}</p>
<p>Bookie juice is: {{Juice}}</p>
<p>Home Odd: {{HomeOdd}}</p>
<p>Draw Odd: {{DrawOdd}}</p>
<p>Away Odd: {{AwayOdd}}</p>
<p>Home True Odd: {{Home_True_Odd}}</p>
<p>Draw True Odd: {{Draw_True_Odd}}</p>
<p>Away True Odd: {{Away_True_Odd}}</p>
<p>True Probability is: {{True_Probability}}</p>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
-->
</body>
</html>
Below is an attachment of the django app files is set up.
You need to define context when if request.method == "GET"
def index(request):
if request.method == "POST":
odd1 = float(request.POST.get("odd1"))
odd2 = float(request.POST.get("odd2"))
odd3 = float(request.POST.get("odd3"))
func_def = odd_finder_true(odd1, odd2, odd3)
context = {
"Juice": func_def["Juice"],
"TotalImpliedProbability": func_def["TotalImpliedProbability"],
"HomeOdd": func_def["HomeOdd"],
"DrawOdd": func_def["DrawOdd"],
"AwayOdd": func_def["AwayOdd"],
"Home_True_Odd": func_def["Home_True_Odd"],
"Draw_True_Odd": func_def["Draw_True_Odd"],
"Away_True_Odd": func_def["Away_True_Odd"],
"True_Probability": func_def["True_Probability"],
}
context = context
# INDENT THIS
return render(request, "index.html", context)
else:
# WHAT IS THE CONTEXT WHEN request.method == "GET" ?
return render(request, "index.html", {})
The problem is that the variable context you created has the same name as the context you imported from multiprocessing at the top of the file. Changing the variable name should fix the problem.
from multiprocessing import context
import re
from django.shortcuts import render
from django.http import HttpResponse
from .odd_finder_func import *
def index(request):
if request.method == 'POST':
odd1 = float(request.POST.get('odd1'))
odd2 = float(request.POST.get('odd2'))
odd3 = float(request.POST.get('odd3'))
func_def = odd_finder_true(odd1, odd2, odd3)
response_context = {
'Juice': func_def['Juice'],
'TotalImpliedProbability': func_def['TotalImpliedProbability'],
'HomeOdd': func_def['HomeOdd'],
'DrawOdd': func_def['DrawOdd'],
'AwayOdd': func_def['AwayOdd'],
'Home_True_Odd': func_def['Home_True_Odd'],
'Draw_True_Odd': func_def['Draw_True_Odd'],
'Away_True_Odd': func_def['Away_True_Odd'],
'True_Probability': func_def['True_Probability']
}
return render(request, 'index.html', response_context)

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

Categories