Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"NoReverseMatch" when in button that refers to a page with parameter in the url
I have this error: "NoReverseMatch at /home/2/ Reverse for 'calendar_new' with arguments '('',)' not found. 1 pattern(s) tried: ['home/(?P<group_id>\d+)/calendar/new/$']" in a button. In the ulr I have a "group_id" parameter which I need to use as a filter parameter. I don't understand what's wrong, because if I write the path manually in the url I don't have any problem and it opens the page correctly. "group_id" is already a parameter present in the url. In calendar.html: <div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column"> <main class="inner cove border" role="main" style="background-color: white;"> <h1 class="cover-heading mt-3">Lista Calendari di {{ nome }}</h1> <div class="mt-5"> <ul class="list-group"> {% for calendar in object_list %} <a href="{{ calendar.id }}"><li class="list-group-item list-group-item-action">{{ calendar.name }}</li></a> {% empty %} <li class="list-group-item">Non ci sono calendari disponibili per questo edificio</li> {% endfor %} </ul> </div> </main> <!-- NUOVO CALENDARIO --> <a class="btn btn-primary btn-lg active mt-5 mb-5" href="{% url 'cal:calendar_new'%}">Aggiungi Calendario</a> </div> In urls.py: url(r'^home/(?P<group_id>\d+)/$', views.CalendarsOfGroupView.as_view(), name='group_view'), url(r'^home/(?P<group_id>\d+)/calendar/new/$', views.calendar, name='calendar_new'), -
Issue deploying django app on Heroku - Issue with pyobjc-framework-AddressBook
I'm trying this command git push heroku master, it is going through my requirements.txt entirely but then gets stuck on this : Collecting pyobjc-framework-AddressBook==6.2.2 remote: Downloading pyobjc-framework-AddressBook-6.2.2.tar.gz (76 kB) remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_i44fimz/pyobjc-framework-AddressBook/setup.py'"'"'; file='"'"'/tmp/pip-install-_i44fimz/pyobjc-framework-AddressBook/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-jbmvd3ua remote: cwd: /tmp/pip-install-_i44fimz/pyobjc-framework-AddressBook/ remote: Complete output (15 lines): remote: Traceback (most recent call last): remote: File "", line 1, in remote: File "/tmp/pip-install-_i44fimz/pyobjc-framework-AddressBook/setup.py", line 30, in remote: for fn in os.listdir("Modules") remote: File "/tmp/pip-install-_i44fimz/pyobjc-framework-AddressBook/pyobjc_setup.py", line 429, in Extension remote: universal_newlines=True, remote: File "/app/.heroku/python/lib/python3.6/subprocess.py", line 356, in check_output remote: **kwargs).stdout remote: File "/app/.heroku/python/lib/python3.6/subprocess.py", line 423, in run remote: with Popen(*popenargs, **kwargs) as process: remote: File "/app/.heroku/python/lib/python3.6/subprocess.py", line 729, in init remote: restore_signals, start_new_session) remote: File "/app/.heroku/python/lib/python3.6/subprocess.py", line 1364, in _execute_child remote: raise child_exception_type(errno_num, err_msg, err_filename) remote: FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/xcrun': '/usr/bin/xcrun' remote: ---------------------------------------- remote: ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I kind of understood that pyobjc is for Mac and that Heroku is using Linux. But I don't know how to deal with that because there … -
Django. Populate user name or ID when user saving a model from web pages
Help please!!! I have model "UserImg" with field "user" that editable=False. I don't want to show this field, but I want it to be automatically filled in with the user name when the user is saved from web page. Thank you in advance model.py def upload_myimg_path(instance, filename): return 'documents/{0}/{1}'.format(instance.created_by.username, filename) class UserImg(models.Model): user = models.ForeignKey(User, verbose_name=_('Created by'), on_delete=models.CASCADE, editable=False, null=True, blank=True) name = models.CharField(max_length=100, default='') image = models.ImageField(upload_to=upload_myimg_path, verbose_name=_('File')) def __str__(self): return str(self.user) forms.py class UserImgForm(forms.ModelForm): class Meta: model = UserImg fields = '__all__' views.py def createuserimg(request): if request.method == 'POST': form = UserImgForm(request.POST or None) if form.is_valid(): form.save() return redirect('/accounts/users') else: return redirect('/accounts/') else: form = UserImgForm return render(request, 'accounts/user_form.html', {'form': form}) -
Is there a way to store form layout in order to generate form dynamically in django mvt?
I'm working on a pretty large Django project, which has over 60 different forms layout (can be more than this when needed). I pretty confuse that how can I build all such forms manually??. I've came up with an idea is that I'm gonna store form layout in database and with every new forms, I just need to config in database and then using crispy layout to dynamically generate those forms... Do you guys have any better ideas? Thanks -
NameError: name 'mymodel' is not defined
I have deployed my Django project for test on a remote server and got an error I don't have locally and I don't understand the error generally, this kind of error means the models has not been imported but this is not the case: line 3, models Pays is imported morevover, trace error indicated a line that don't seems to match the error: Exception Location: /home/test/intensetbm_app/intensetbm-etool/randomization/forms.py in clean_ran_num, line 93 /home/test/intensetbm_app/intensetbm-etool/randomization/forms.py in clean_ran_num if int(data) == 0: but line 93 is not in clean_ran_num but in clean_ran_cri forms.py from django import forms from .models import Randomisation, patient_code_is_valid from parameters.models import Pays import datetime import time from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError from parameters.models import Thesaurus from django.conf import settings class RandomisationForm(forms.ModelForm): # surcharge méthode constructeur (__init__) pour avoir accès aux variables de sessions # https://stackoverflow.com/questions/3778148/django-form-validation-including-the-use-of-session-data def __init__(self, request, *args, **kwargs): super(RandomisationForm, self).__init__(*args, **kwargs) self.request = request self.language = request.session.get('language') TYPES = Thesaurus.options_list(6,self.language) YESNO = Thesaurus.options_list(1,self.language) TB = Thesaurus.options_list(9,self.language) SEVERITY = Thesaurus.options_list(8,self.language) HIV = Thesaurus.options_list(4,self.language) self.fields["ran_dat"] = forms.DateField( label = _("Date of randomization"), initial = timezone.now(), required = True, ) # empêche l'autocomplétion self.fields['ran_dat'].widget.attrs.update({ 'autocomplete': 'off' }) self.fields["ran_num"] = forms.CharField(label = _("Patient number"), … -
Django : Filtering Post by user + UserProfile data
I Hope you're well. I got an error : name 'username' is not defined I'd like to have a public page with the user slug. Ex. profile/louis/ Louis's Post + Louis's UserProfileData I'm beginning with Django, so I made some mistake. nutriscore/models.py class Post(models.Model): author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') user/models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) user/views.py #public profile @login_required(login_url='/earlycooker/login') def userpublicpostview(request, slug): template = 'user_public_profile.html' user = User.objects.filter(username).values() user_id = user[0]['id'] userprofile = UserProfile.objects.filter(user_id=userprofile).values() user_post = Post.objects.filter(author = user_id, slug=slug) return render(request, template, {'user_posts':user_posts,'userpublic': userpublic}) user/urls.py path('profile/<slug:slug>/', userpublicpostview,name="user_public_cookwall"), -
Django: How to go about loading multiple images from multiple objects on same render in html
I have been searching and came across this (Multiple images per Model) which explains how to get all the images for a specific object but how would I load multiple images for a list of 2,000+ objects - I know I could loop and grab all the objects from each image but then how would I display the correct images with the correct objects in the html? While writing this, I was wondering if this is a good use for template_tags but I am extremely new to them. Working with these basic cut down models as an example. class Auction(models.Model): auction_title = models.CharField(max_length=255, null=True) class Listing(models.Model): auction_id = models.ForeignKey(Auction, on_delete=models.CASCADE) title = models.CharField(max_length=255) class ListingImage(models.Model): listing_id = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='images') image = models.ImageField() view example to run off of, expecting anything up to thousands of items returned. listings = Listing.objects.filter(time_ending__gte=datetime.now()).order_by('time_starting') so with that example view above how would I go about grabbing each image for each of those listings and then more of an issue was finding the way to display those in html in loops or in any order or specifically chosen. Thank you so much for your help! -
How to integrate django and RASA
i have a problem in connecting both django webpages and rasa bot The output i looking for when the user ask the questions through the django webpage and the reply need to on the webpage by using the rasa The output now getting was "i can't understand what you are saying" which was from my Javascript for the webpage. -
django schedule job to loop through ticker list
I have the following list of tickers and I want to schedule a job to run every 30 seconds using Django Q. I am open to solutions other than Django Q, but that is preferred as in the future I'll have more complicated tasks to complete. ["AAPL", "AMZN", "GOOG"] this is the current code that I have. how would I loop the tickers through the prep_yahoo_financials() function and run it every 30 seconds ? def prep_yahoo_financials(ticker): financials = get_yahoo_financials(ticker) financials = parse_yahoo_financials(financials) payload = prep_yahoo_payload(ticker=ticker, financial_dictionary=financials) return payload Schedule.objects.create( func=prep_yahoo_financials seconds=30 repeats=-1 ) -
Django loops on /password-reset-confirm/ . Why?
It was created in 2-nd version of django, I am trying it under 3.0.6. What changes has been done that can affect this authentication views/routes? Django sends email but after following link shows page password-reset-confirm with button and does not follow to password-reset-complete after clicking on button but returns to the same page indefinitely. urlpatterns = [ path('admin/', admin.site.urls), path('register/', users_views.register, name="register"), path('profile/', users_views.profile, name="profile"), path('login/', auth_views.LoginView.as_view(template_name="users/login.html"), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name="users/logout.html"), name="logout"), path('password-reset/', auth_views.PasswordResetView.as_view(template_name="users/password_reset.html"), name="password_reset"), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name="users/password_reset_done.html"), name="password_reset_done"), path('password-reset-confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name="users/password_reset_confirm.html"), name="password_reset_confirm"), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name="users/password_reset_complete.html"), name="password_reset_complete"), path('', include("blog.urls")), ] template {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Reset Password</legend> {{ form|crispy }} <!-- {{ form.as_p }} --> </fieldset> <div class="form-group"> <button class='btn btn-outline-info' type='Submit'>Reset Password</button> </div> </form> </div> {% endblock content %} -
Connecting Amazon S3 to existing Django project
There is a need to introduce external storage for media files uploaded by users in Django project. This is why I consider using Amazon S3. The problem is that I am not sure how to manage already existing files. Did anyone have the experience of connecting existing Django project and relocating media storage + already uploaded files onto Amazon S3? What are the possible caveats? -
Django ORM many to many filter by authors and the count of books
I'm using Django 2.2 I have two tables with the Many-to-Many relation class Book(models.Model): title = models.CharField(max_length=50) authors = models.ManyToManyField(Author) class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) I have a list of authors first_name author_names = ['john', 'parker', 'donald'] How can I get the count of books each author have? -
Django signal to convert video is running even if I update other fields without updating the video file field. Is there a way to change that?
Hey guys I am facing a problem with the signal to convert videos running everytime I update other fields in the video model. Is is possible to change this problem. I want the video processing to run only when I upload the video file field and not any other. This is the signal. @receiver(post_save, sender=VideoPost) def convert_video(sender, instance, **kwargs): enqueue(tasks.convert_all_videos, instance._meta.app_label, instance._meta.model_name, instance.pk) print('Done converting!') please do let me know if more information is needed. Thank you! -
How can I get choice value in views.py from User model in Django?
In my User model, I have a charfield for choice (Teacher and Student). I want to check if that charfield is Teacher or Student in views.py. How can I do that? models.py class User(AbstractUser): class Types(models.TextChoices): TEACHER = "TEACHER", "Teacher" STUDENT = "STUDENT", "Student" type = models.CharField( _('Type'), max_length=50, choices=Types.choices ) in my views.py def registerView(request): if request.user.profile.type == "TEACHER": # do something else: # do something I know my views.py is not correct but I want to do something like that. -
How to multiply 2 columns in Django ORM
I have a MySQL table recording invoice line entries. I would like to multiply the unit_price and quantity to obtain the sub_total(multiple Line Entries). Here is how my line_entries_table looks like invoice_id| unit_price| quantity 14646 | 521.2900 | 1.9000 14646 | 200.9900 | 1.5900 14646 | 260.0700 | 1.5800 14646 | 375.1700 | 1.7100 14646 | 496.4300 | 1.8800 14646 | 164.3100 | 1.6100 14646 | 279.2200 | 1.6400 14646 | 343.0100 | 1.7200 -------------------------- 25728 | 326.3400 | 1.5300 25728 | 521.2900 | 1.9000 25728 | 200.9900 | 1.5900 25728 | 260.0700 | 1.5800 25728 | 375.1700 | 1.7100 25728 | 496.4300 | 1.8800 25728 | 164.3100 | 1.6100 25728 | 279.2200 | 1.6400 25728 | 343.0100 | 1.7200 25728 | 326.3400 | 1.5300 Result: invoice_id| sub_total 14646 | 5107.5021 25728 | 2698.8797 I would like to obtain the sub_total of all the invoices at once. Here is the MySQL command which works in my case: select invoice_id, SUM(unit_price*quantity) AS sub_total from details_invoice_service_details WHERE invoice_id IN (14646 ,25728) GROUP BY invoice_id Any idea how to accomplish this in Django: Here is the part of the code, I tried: rows = invoice.models.InvoiceLineEntries_Model.objects.filter(invoice_id__in=invoice_ids) -
Display my response errors in span with their respective fields
In this html file i define form and span fields for displaying respective fields errors.How i show my response errors in span with respective fields. Please help How i show my response errors in span with respective fields. Please help This my response of django view when i submit form: {"result": "error", "message": {"username": ["Please fill the username"], "first_name": ["Please fill the first name"], "last_name": ["Please fill the last name"], "email": ["Please fill the email"], "password": ["Please fill the password"], "password2": ["Please fill the confirm password"]}} How i show my response errors in span with respective fields. Please help My html file: In this html file i define form and span fields for displaying respective fields errors. How i show my response errors in span with respective fields. Please help How i show my response errors in span with respective fields. Please help How i show my response errors in span with respective fields. Please help {% block body %} <html> <head> </head> <body> <form id="wrapper"> // This my form <div id="div2"> <h1>Create an account</h1> <li> <input type="text" placeholder="Username" id="username" name="username"> // This my input <input type="text" placeholder="First Name" id="first_name" name="first_name"> </li> <span style="color: red" name="username"></span> <span style="color: red" name="first_name"></span> … -
How to create Scheduled skype online meeting link programatically by python/django?
I want to create skype meeting link like "join.skype.com/YHeJdxncAImN" programatically in python , that we get when we click "create a free meeting " button in https://www.skype.com/en/free-conference-call/ . After getting the link i'll send it through email to user to connect the meeting ...I am very new in django . Please help me.. Thank you in advance ... -
How to make single user for multiple Django projects?
I have created a Django project in which I have created too many apps. Due to too many apps, my current deployed server getting slower. To solve this problem and for the new extra upcoming apps, I want to create a new Django project and will deploy it on the other server but I don't have an idea how to use all old project apps features as well as all users here I found django-sso answer in github question regarding SSO find one article here and followed, used Django-Simple SSO but this article flow is not working. django-cas-server this library not follow django3+ is there any better way? I didn't find any goood article regarding django-SSO. Anyone help or suggestion will be more valuable for me and for Django SSO... -
How to add samesite none option in django settings file
I used Django 2.0.2 version. I tried to process google authentication in Django project. I got the token but I will pass URL and token. it return 404 error. I need to add samesite='none' in Django settings project. Where to add I don't know and I tried to add many ways but still it's throwing 404 error. How to fix it. Settings.py MIDDLEWARE = [ 'django_cookies_samesite.middleware.CookiesSameSite', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] So, I added samesite.middleware.CookiesSameSite middleware. but still I facing this warning A cookie associated with a cross-site resource at http://stats.XXXX.com/ was set without the SameSite attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details How to fix it -
Expected table or queryset, not str
I am trying to render a table using django-tables2, but I get this error message: Expected table or queryset, not str views.py: def getKpiTableCsd(request, report_id): template = loader.get_template('kpi/confirm_kpi_csd.html') report = get_object_or_404(KpiMembersCsd, id=report_id) context = RequestContext(request, {'report': report}) table_context = KpiMembersCsdTable(KpiMembersCsd.objects.filter( id=report_id)) # creating table object not string return HttpResponse(template.render(context.flatten()), {'table': table_context}) tables.py: import django_tables2 as tables import kpi.models class KpiMembersCsdTable(tables.Table): class Meta: model = kpi.models.KpiMembersCsd Traceback: File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/flex/work/02_dolasilla/dolasilla_seite/kpi/views.py", line 32, in getKpiTableCsd return HttpResponse(template.render(context.flatten()), File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render result = block.nodelist.render(context) File "/home/flex/work/02_dolasilla/dolasilla/lib/python3.7/site-packages/django/template/base.py", line … -
why posts are not shown in home page?
when I add a post in the admin panel, the posts are not shown on the home page of the app. it only shows spaces of the post but couldn't show writeup of the post on the home page. views.py from django.shortcuts import render,HttpResponseRedirect from django.contrib import messages from django.http import HttpResponse from .forms import SignUpForm, LoginForm from django.contrib.auth import authenticate, login, logout from .models import Post # Create your views here. # home def home(request): posts = Post.objects.all() return render(request, 'blog/home.html',{'posts':posts}) home.html {% extends 'blog/base.html' %} {% load static %} {% block content %} <div class="col-sm-10"> <h3 class="text-white my-5">Home Page</h3> {% for post in posts %} <div class="jumbotron jumbotron-fluid jumbo-colour"> <div class="container"> <h1 class="display-4 font-weight-bold">{{posts.title}}</h1> <p class="lead">{{posts.desc}}</p> </div> </div> {% endfor %} </div> {% endblock content %} models.py from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length=150) desc = models.TextField() -
Django Gateway Timeout running on IIS
I am running a Django app on a windows 10 machine with IIS web server. The application based on user command starts a selenium instance and try to collect some data from third party sites. The problem is that when the collecting data gets long time, actually more than 30s i get a 504 Gateway Timeout at the client. I searched across the web and find some parameters to set including: ARR timeout application pool idle timeout Default website Connection timeout adding following parameters to the applicationHost.config file: <application fullPath="..." arguments="...\wfastcgi.py" signalBeforeTerminateSeconds="60" idleTimeout="900" activityTimeout="180" requestTimeout="10000" /> But, any of them helped and the 504 again on 30s. -
What is the differences between __date__range and __range for writing django queries?
I am getting different datasets when using __date__range["2019-04-01","2019-04-30"] and for __range["2019-04-30"] -
TypeError: Object of type 'TopicSerializer' is not JSON serializable Django
Hi All I faced this issue while getting API response. I am using django==2.1.7. Below I am adding my code snippet models.py The model contains topic names(en,bn), taglist(string), and Bucket_id or topic_id class Topics(models.Model): id = models.AutoField(primary_key=True) name_en = models.CharField(max_length=70, blank=False, default='') name_bn = models.CharField(max_length=70, blank=False, default='') tags = models.TextField(blank=False, default='') bucket_id = models.IntegerField() def set_tags(self, x): self.tags = json.dumps(x) def get_tags(self): return json.loads(self.tags) class Meta: managed = True db_table = 'follow_topics' serialize.py TopicSeializer used for JSON serialize the model from rest_framework import serializers from .models import Topics class TopicSerializer(serializers.ModelSerializer): class Meta: model = Topics fields = ['name_en','name_bn','tags', 'bucket_id'] views.py get_topic function gives me the list of the topic from the model @api_view(('GET',)) def get_topics(requests): topic_id = requests.GET.get('topic_id', None) post_data = Topics.objects.filter(bucket_id=topic_id).first() serialize_data = TopicSerializer(post_data, many=True) return Response({"status": "success", "data": serialize_data}) I got serializable error. This error looks frustrating for me. Please help me share some useful resource or way that I can fix this error Environment: Request Method: GET Request URL: http://127.0.0.1:8000/feed/v1/get_topics?topic_id=2 Django Version: 2.1.7 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'rest_framework', 'feedv1'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response … -
{% csrf_token %} is not working in django
Template includes just only html forms and it says CSRF token missing or incorrect. template: <form method='POST'> {% csrf_token %} <div class='row'> <div class='col'> <input value={{ option1 }} type='submit' class="btn btn-primary btn-lg btn-block button" name='option'/> </div> <div class='col'> <input value={{ option2 }} type='submit' class="btn btn-primary btn-lg btn-block button" name='option'/> </div> </div> </form> Code for views.py def QuestionAnswer(request, user_id, user, question_id): user = User.objects.get(pk=user_id) question = Question.objects.all().filter(user=user) option = Choices.objects.all().filter(question = question[0]) return render(request, 'quiz/QuestionAnswer.html', { 'question':question[0].question, 'option1':option[0], 'option2':option[1], })