CSRF token missing or incorrect on one page - django

Have a homepage there every page with a form works fine.
Added a form to my start page and in my local server it works fine.
But when I add it to the production server it does not work.
It say's that CSRF- token is missing or incorret.
But I have added the token, and it works all the other pages.
What is that I'm missing... ?
View
#login_required
def start(request) :
libs = Library.objects.all();
header = Header('Start');
studies = None;
source = None;
if request.method == 'POST' :
if 'Show_studie' in request.POST:
studies = Study.objects.all;
if 'Show_source' in request.POST:
source = Source.objects.all;
dctArgs = {
'library_list': libs,
'styles_dir': conf.styles_path,
'header': header.html,
'studies_list':studies,
'source_list':source,
'images_dir': conf.images_path,
};
return render_to_response('start.html', dctArgs, RequestContext(request));
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE></TITLE>
<link rel="stylesheet" type="text/css" href="{{styles_dir}}/common.css" />
<link rel="stylesheet" type="text/css" href="{{styles_dir}}/header.css" />
<link rel="stylesheet" type="text/css" href="{{styles_dir}}/Headerstyles.css" />
</HEAD>
<BODY>
{{header|safe}}
<h1></h1>
<table id="doc_tbl" class="data" cellspacing=0>
<tr>
<th>Name</th>
<th>Documents</th>
<th>Export</th>
</tr>
{% for library in library_list %}
<tr>
<td>{{library.name}}</td>
<td>{{library.source_set.all|length}}</td>
<td>Andra till Jesper Export</td>
</tr>
{% endfor %}
</table>
<h3>Messages</h3>
{{messages}}
</br>
<form id="form1" name="form1" method="post" action="/start/" enctype="multipart/form-data">
{% csrf_token %}
<fieldset style="width:300px; margin-left:5px;">
<legend> Show all </legend>
<input type="checkbox" name="Show_studie" value="Show Studie"> Studie
<input type="checkbox" name="Show_source" value="Show Source"> Source
</br>
</br>
<input type="submit" value="Show All">
</fieldset>
{% if studies_list %}
<h3> Studies </h3>
<table class="table1">
<thead>
<tr>
<th></th>
<th scope="col1" >Name</th>
<th scope="col1" >Added by</th>
</tr>
</thead>
{% for study in studies_list %}
<tbody>
<tr>
<td>
<img class="icon" src="{{images_dir}}/edit-icon.png"/>
<img onclick="javascript:return confirmDelete_name('Are you sure? The study and any associated information will be deleted.', {{study.id}}, 'delete_study');" class="icon" src="{{images_dir}}/delete-icon.png"/>
</td>
<td>{{study.name}}</td>
<td>{{study.metadata_added_by_user.first_name}} {{study.metadata_added_by_user.last_name}}</td>
</tr>
{% endfor %}
</table>
{% endif %}
{% if source_list %}
<h3> Source </h3>
<table class="table1">
<thead>
<tr>
<th></th>
<th scope="col1" >Name</th>
<th scope="col1" >Added by</th>
</tr>
</thead>
{% for source in source_list %}
<tbody>
<tr>
<td>
<img class="icon" src="{{images_dir}}/edit-icon.png"/>
<img onclick="javascript:return confirmDelete_name('Are you sure? The study and any associated information will be deleted.', {{study.id}}, 'delete_study');" class="icon" src="{{images_dir}}/delete-icon.png"/>
</td>
<td>{{source.name}}</td>
<td>{{source.metadata_added_by_user.first_name}} {{source.metadata_added_by_user.last_name}}</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
</form>
</BODY>
</HTML>
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's
CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
• The view function uses RequestContext for the template, instead of Context.
• In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
• If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views
that use the csrf_token template tag, as well as those that accept the POST data.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
Settings
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
On the page that working I get this message:
<django.contrib.messages.storage.fallback.FallbackStorage object at 0x03B7A270>

Try wrapping your view in the #requires_csrf_token decorator, like so:
from django.views.decorators.csrf import requires_csrf_token
#requires_csrf_token
#login_required
def start(request):
...

You can use the csrf_exempt decorator to disable CSRF protection for a particular view.
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def someview():
......
I know Its not what you want but you can try this if you want :)

Related

how can i stop to run path with same parameter on continue path

here i send my details
how can i stop this for example if i run http://127.0.0.1:7000/search_acctable/?txt=Kalpesh but if now i again run my code this is run like http://127.0.0.1:7000/search_acctable/?txt=Kalpesh/search_acctable/?txt=any in django how can i solve this
i need help to solve this problem
views.py
def s_index(request):
current_url = request.build_absolute_uri()
#print(current_url)
src = request.POST.get('txt_search')
#if request.POST['btn_clear']:
# return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page
if request.POST['btn_search']:
rec=accmaster.objects.filter(Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src) ).values() # for filter with and conition onyl put comma if want or condition use pipe sign and Q
if rec.exists():
rec=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values()
grp_city=accmaster.objects.filter( Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src)).values('acc_city').annotate(Sum('acc_op')).order_by('acc_city')
template=loader.get_template('index.html')
output=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values().aggregate(Sum('acc_op'))
context ={
'rec':rec,
'output':output['acc_op__sum'],
'grp_city':grp_city,
}
return HttpResponse(template.render(context,request))
else :
return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page
urls.py
from django.urls import path
from . import views
urlpatterns=[
path('',views.index,name='index'),
path('addacc/',views.add,name='addacc'),
path('addacc/addrecord/',views.addrecord,name='addrecord') ,
path('delete/<int:id>',views.delete,name='delete') ,
path('update/<int:id>',views.update,name='update'),
path('update/updaterecord/<int:id>',views.updaterecord,name='updaterecord'),
path('index/',views.s_index,name='s_index'),
#path('',views.form_view,name='mform')
]
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function printreport(){
//var divtoprint=document.getElementById("maindiv");
var printcontext=document.getElementById("maindiv").innerHTML;
var originalcontext=document.body.innerHTML;
var nwin=window.open("");
nwin.document.open();
nwin.document.write('<html><head><link rel="stylesheet" media="print" href="{% static 'mystyleprint.css' %}" ></head><body>');
nwin.document.write(printcontext);
nwin.document.write("</body></html>");
//document.write(printcontext);
//document.body.innerHTML=printcontext;
//printWindow.document.write(divtoprint);
nwin.print();
nwin.document.close();
nwin.close();
}
</script>
<link rel="stylesheet" href="{% static 'mystyle.css' %}" >
<link rel="stylesheet" href="{% static 'mystyleprint.css' %}" media="print"> <!-- make seprate css for print document and make media print-->
</head>
<body >
<form action="index/" method="post" >
{% csrf_token %}
<div>
<button type="button">Add Account</button>
<label>Search :</label> <input id="txt_search" name="txt_search" autocomplete="off">
<input type="submit" id="btn_search" name="btn_search" value="Search" onclick="myfunction()">
<input type="button" id="btn_clear" name="btn_clear" value="clear"" onclick="history.back()">
<input type="button" name="btn_print" value="Print" onclick="printreport()">
</div>
<br>
<div id="maindiv">
<table id="maintable">
{% with no="s" %}
<h1> Account List </h1>
<tr>
<th> Sr.No </th>
<th> Name </th>
<th> City </th>
<th> Opening Balance </th>
<th id="thedit"> Edit </th>
<th id="thdelete"> Delete </th>
</tr>
{% for y in grp_city %}
<tr>
<td id="tdcity" colspan=4 style="color:magenta"> {{ y.acc_city }}</td>
{% for x in rec %}
{% if x.acc_city == y.acc_city %}
<tr>
<td style="width:4%" id="srno"></td>
<td>{{ x.acc_name }}</td>
<td style="width:20%"> {{ x.acc_city}}</td>
<td align="right" style="width:10%"> {{ x.acc_op}}</td>
<td style="width:4%" id="redit"> <img src="{% static 'icon/update.png' %}"></td>
<td style="width:4%" id="rdelete"> </td>
</tr>
{% endif %}
{% endfor %}
<td colspan=4 align="right" style="color:magenta; font-size:18px;" >Total: {{ y.acc_op__sum|floatformat:2 }} </td>
<td colspan=2 id="nodisp"> </td>
</tr>
{% endfor %}
<tr>
<td colspan=4 align="right" style="color:red; font-size:20px">Total : {{output|floatformat:2}} </td>
</tr>
</table>
</div>
<p>
</p>
{% endwith %}
</form>
</body>
</html>
i don't know to how to handle it i am new to django

How do I search 2 tables in

I am continuing to learn Django as a newbie.....I would like some direction in relation to 1 search query against two tables that hold the same headers such as customer names.
So table 1 is customer names from 2022 and table 2 is customer names from 2021.
I can create the models / admin and URL and set the project up.
How do I create a query to search both tables at the same time and display the result?
View.py
def index(request,):
q = request.GET.get('q')
if q:
#this is what is searched against.....ie the columns in our model.py
vector = SearchVector('name')
#This is the value the user is searching for:
query = SearchQuery (q)
# customers = customer.objects.filter(name__search=q)
# customers = customer.objects.annotate(search=vector).filter(search=query)
customers = customer1.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.001).order_by('-rank')
else:
customers = None
context = {'customers': customers}
return render(request, 'index.html', context)
Index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GAEN</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
</head>
<body>
{% include 'navbar.html' %}
<div class="container">
{% block content %}
<br><br><br><br>
<form>
<div class="mb-3">
<label for="Search Query" class="form-label ">
<h3>db Search Query</h3>
</label>
<br><br>
<input type="text" class="form-control" aria-describedby="#" name="q">
<br><br>
<button type="submit" class="btn btn-primary ">Submit</button>
<button type="submit" class="btn btn-danger">Reset</button>
</div>
</form>
{% if customers %}
<br>
<h3><mark>Results:</mark> {{ customer | length }}</h3>
<br><br>
{% for customer in customers %}
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Search Result</th>
<th scope="col">name</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>{{ customer.name }}</td>
</tr>
</tbody>
</table>
Rank: {{ customer.rank }}
<br><br><br>
{% endfor %}
{% endif %}
{% endblock %}
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2"
crossorigin="anonymous"></script>
Django-filter can do it easily!

Django (Trying to use pagination with filter)

I am trying to add Pagination to my queryset with filter, filter seems to work but pagination doesn't. Can someone let me know what changes i need to make so that pagination works.
When we go onto page 2 we get the whole query result instead of filter
Django filer + pagination
Below is the code:
def index(request):
user_list_all = MasterGidrDataDict.objects.all()
user_filter = UserFilter(request.GET, queryset=user_list_all)
user_list = user_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(user_list, 50)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
args = {'paginator': paginator, 'filter': user_filter, 'users': users}
return render(request, 'app1/index.html', args)
index.html
<html>
<head>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
</head>
{% block content %}
<form method="get">
{{ filter.form.as_p }}
<button type="submit">Search</button>
</form>
<div class = "tabl" >
<table class = 'table table-bordered'>
<thead>
<tr>
<th style="color:black;"> id </th>
<th style="color:black;"> vendor_name </th>
<th style="color:black;"> market_name</th>
<th style="color:black;"> grup </th>
<th style="color:black;"> vrbl </th>
<th style="color:black;"> code </th>
<th style="color:black;"> output </th>
<th style="color:black;"> active_flag </th>
<th style="color:black;"> load_date <th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.id|upper }}</td>
<td>{{user.vendor_name}}</td>
<td>{{user.market_name}}</td>
<td>{{user.grup}}</td>
<td>{{user.vrbl}}</td>
<td>{{user.code}}</td>
<td>{{user.output}}</td>
<td>{{user.active_flag}}</td>
<td>{{user.load_date}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="pagination">
<span class="step-links">
{% if users.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ users.number }} of {{ users.paginator.num_pages }}.
</span>
{% if users.has_next %}
next
last »
{% endif %}
</span>
</div>
{% endblock %}
</html>
This is a common problem with how pagination & filtering work together, there are edge cases to cover a bit yourself.
This article from Caktus Group describes the problem in detail, but basically, you need to build your links in your template to preserve the filters as well as the page number. It's because you're using GET method to submit your filtering form, which means the data is passed as a query parameter, like your page number.
When on a filtered page, the pagination links do not include the current filters.
Your view looks fine to me.
For your template, in the filter part {% for user in users %}, I had it differently, I did something like {% for user in users.object_list %}.
In the pagination part, I added a template tag to render the url with the filter. If you aren't worrying about appending to url, an easier way to encode url without a template tag, is use {{ request.get_full_path }}, e.g.next
View below for my view and template files.
search_view.py
from django.shortcuts import render
from app.models.filters_model import ApiStatusFilter
from app.models.api_status import ApiStatus
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from datetime import datetime, timedelta
def status(request):
all_entries_ordered = ApiStatus.objects.values().order_by('-created_at')[:200]
for dictionarys in all_entries_ordered:
dictionarys
apistatus_list = ApiStatus.objects.values().order_by('-created_at')
apistatus_filter = ApiStatusFilter(request.GET, queryset=apistatus_list)
paginator = Paginator(apistatus_filter.qs, 10)
page = request.GET.get('page')
try:
dataqs = paginator.page(page)
except PageNotAnInteger:
dataqs = paginator.page(1)
except EmptyPage:
dataqs = paginator.page(paginator.num_pages)
return render(request, 'status_page_template.html', {'dictionarys': dictionarys, 'apistatus_filter': apistatus_filter, 'dataqs': dataqs, 'allobjects': apistatus_list})
status_template.html
{% load static %}
{% load my_templatetags %}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/table_styling.css' %}">
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
<table>
<thead>
<tr>
{% for keys in dictionarys.keys %}
<th>{{ keys }}</th>
{% endfor %}
</tr>
</thead>
<form method="get">
{{ apistatus_filter.form.as_p }}
<button type="submit">Search</button>
{% for user in dataqs.object_list %}
<tr>
<td>{{ user.id }}</td>
<td>{{ user.date_time }}</td>
<td>{{ user.log }}</td>
</tr>
{% endfor %}
</form>
</tbody>
</table>
<div class="pagination">
<span>
{% if dataqs.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ dataqs.number }} of {{ dataqs.paginator.num_pages }}.
</span>
{% if dataqs.has_next %}
next
last »
{% endif %}
</span>
</div>
</body>
</html>
my_templatetags.py
from django import template
register = template.Library()
#register.simple_tag
def query_transform(request, **kwargs):
updated = request.GET.copy()
for k, v in kwargs.items():
if v is not None:
updated[k] = v
else:
updated.pop(k, 0)
return updated.urlencode()

About Django Javascript

I don't know how do write javascript for Django?
Please help me
The following javascript code is correct?
This code is write in the HTML:
base.html:
{% load staticfiles %}
index.html
{% extends "base.html" %}
<html>
<head>
</head>
<body>
<script type="text/javascript">
$(document).ready(function()
{
$("#sampleTable").tablesorter();
);
</script>
<div class="import">
<table id="sampleTable" class="tablesorter">
<thead>
<tr>
<th class="{sorter:'metadata'}" style="width:100px">name</th>
<th class="{sorter:'metadata'}" style="width:260px">company</th>
</tr>
</thead>
</table>
{% if memo.count > 0 %}
{% for user in memo %}
<div><h3>
<table id="sampleTable1" class="tablesorter">
<tbody>
<td style=" border-bottom:1px solid #0099cc; text-align:center;">{{ user.user_name }}</td>
<td style=" border-bottom:1px solid #0099cc; text-align:center;">{{ user.company }}</td>
</tbody>
</table>
</div>
</body>
</html>
Django has nothing to do with Javascript by default. It just renders the templates and returns HTML. You write Javascript for Django, like you'd write anywhere else.
And whether that particular code is correct, Run it. If it runs then it's correct, if not, you have some error. But chances are they wont be related to Django.
BTW, your code is incomplete. You haven't closed the if and for blocks in the template. Also, if you're extending base.html, then your HTML should be inside a block that you defined in base.html. Please read the documentation before writing codes.

How to go to another page after login in django

I still wonder how to redirect after a successful login. At the moment it just redirects me, probably by default, to the django admin page. This is of course not what I want and I want to get redirected to a custom view with a custom template - to be specific of course the one where I used the #login_required decorator. Here are my views.py:
from django.shortcuts import render
from programm.models import *
from django.contrib.auth.decorators import login_required
def index(request):
return render(request, 'index.html')
#login_required(login_url='/login/')
def liste(request):
return render(request, 'liste.html', {'lObj': learningObjective.objects.all()})
This is my login template:
<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE|default:"de-de" }}" >
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<div class = "table">
<table>
<tr>
</td><td><p><u>Login Seite</u></p></td>
</tr>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
<tr>
<td><input type="submit" value="/programm/liste.html" /></td>
<input type="hidden" name="next" value="/programm/liste.html" method="post"/>
</form>
</tr>
<table>
</div>
</body>
</html>
And this is the template which I want to get redirected to, which also got the #login_required decorator:
<!DOCTYPE html>
<html>
<head>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'programm/style.css' %}" />
<div class = "title">
<h1 align = "center">Lernziele</h1>
</div>
</head>
<body>
<div class="liste">
{% for lObj_ in lObj %}
<li>Lernziel: {{ lObj_.learningObjectives }}</li>
{% endfor %}
</div>
</body>
</html>
And this is my urls.py
from django.conf.urls import patterns, url
from programm import views
from django.conf import settings
urlpatterns = patterns('',
url(r'^$', views.index, name = 'index'),
url(r'^liste.html$', views.liste, name = 'liste'),
)
The structure looks like this: Projectname _> Appname(programm) _> templates _> index.html, liste.html, registration(direction) _> login.html
Why not to use variable in settings.py:
LOGIN_REDIRECT_URL = '/whatever/page/'
Of course, this is if you need always redirects all the people to the same page on every login.