Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
csrf verification failing in django 1.9 admin login. Different value of csrf token at different places
Most of the SO answers are asking to clear cookies and confirm middleware class. I have already tried that. I am getting Forbidden (403) CSRF verification failed. Request aborted. error on Django admin login screen. I have hosted my site on pythonanywhere.com with django version 1.9. I have cleared the browser cookies. All of them. I reloaded the login screen. Get request. In source code I can see the csrf token with value = T18pUyBlcnpEx3riZf8GhJhQqdojVE3c In browser cookies, which were empty till now, one value has been set for my website, where csrf value is = XPp5hAhylAkt27U4SzGPNU7w8SFBJ3RP In response header, set cookies was send with cookies value = UT24544MghHLZi0IrGHQlCcpk1v0SbCy Now I entered the username and password and click on login button. Received the 403 error CSRF verification failed. Request aborted. I rechecked all the values of csrf token. In request header CSRF cookies values = XPp5hAhylAkt27U4SzGPNU7w8SFBJ3RP In form data csrf values = UT24544MghHLZi0IrGHQlCcpk1v0SbCy In browser cookies value = hzBt22VGswIgAxG8iHqmDAAr3J9268pI I already have 'django.middleware.csrf.CsrfViewMiddleware', in middleware classes. I cleared browser cache and cookies. Even restarted the system. Why there are different csrf-token values? What is the solution to this problem? -
Django REST framework custom permissions not working when used with Token Authentication
I'm building the backend for a twitter clone using the Django REST framework. Everything I needed to implement worked great with the regular authentication , but is giving me problems when expanding it to using token authorisation. I have a custom permission that doesn't allow a user that isn't the owner of the tweet to delete it. Unfortunately, when using tokens, any authenticated user is allowed to delete it. On the other hand when being accessed through the regular web browser, only once the owner of the tweet is authenticated does the delete option come up. The token authentication does work to identify what user is creating a tweet, or if someone is an authenticated user at all, but doesn't play well with my custom permission Here is my code: In settings.py I include REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ),} The view used to delete the tweet is class UserTweetsDetail(APIView): #View to get specific tweet from specific user authentication_classes = (TokenAuthentication,) permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, ) #If user is not the owner, each tweet is read only def getTweet(self,username,pk): #Fetch tweet from database try: user = User.objects.get(username = username) except User.DoesNotExist: raise Http404 try: tweet = user.tweets.get(id=pk) … -
Django TypeError at / render() got an unexpected keyword argument 'context_instance'
Currently setting up a Django web application on Azure, deployed through Git locally. I haven't actually written any code yet, and when I start up the development server using python3 manage.py runserver and go to the site's address I get the following error: TypeError at / render() got an unexpected keyword argument 'context_instance' It's traced to views.py, which has the following contents: """ Definition of views. """ from django.shortcuts import render from django.http import HttpRequest from django.template import RequestContext from datetime import datetime def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) return render( request, 'app/index.html', context_instance = RequestContext(request, { 'title':'Home Page', 'year':datetime.now().year, }) ) def contact(request): """Renders the contact page.""" assert isinstance(request, HttpRequest) return render( request, 'app/contact.html', context_instance = RequestContext(request, { 'title':'Contact', 'message':'Your contact page.', 'year':datetime.now().year, }) ) def about(request): """Renders the about page.""" assert isinstance(request, HttpRequest) return render( request, 'app/about.html', context_instance = RequestContext(request, { 'title':'About', 'message':'Your application description page.', 'year':datetime.now().year, }) ) I'm not sure what the error is, since the code was generated when the app was created in Azure. As far as I can tell from the documentation the parameters to render() are correct. -
How to create a Python URL that processes a webhoook
I am pretty new to web development and want to create a URL that accepts a webhook json and processes it . Is django the right tool for this ? Can someone please let me know if there is a better tool ? -
Django adding to database with form
I tried adding to my database (which is a list of colleges), with a form, but it is not working. Any idea why? It's bringing me to the success page, but not actually adding it to the database Model: class College(models.Model): college_name = models.CharField(max_length=120) logo = models.ImageField(upload_to="logos", default="logos/default.png") def __str__(self): return self.college_name @classmethod def create(cls, college_name): college = cls(college_name = college_name) return college View: def add(request): return render(request, 'app/add.html') def add_college(request): school = request.POST.get('collegename_input', '') College.create(school) return HttpResponseRedirect('add_success') def add_success(request): return render(request, 'app/add_success.html') add.html: <h2> Add your school </h2> <form action="{% url 'app:addcollege' %}" method="post"> {% csrf_token %} <label for="collegename_input">School: </label> <input type="text" id="collegename_input" name="collegename_input" /> <input type="submit" value="Add School" /> </form> Am I missing something? -
use django-rest-swagger 2 with custom swagger.json
I have a project build with django-rest-framework, and I want to use django-rest-swagger to get API documentation, so I made a swagger.json file via swagger editor, then my question is: How can I make django-rest-swagger read and render my own swagger.json instead of auto-generated from code? I've checked the django-rest-swagger doc over and over again but nothing found about that. Any comment will be appreciated. -
How to use cookies in a notification system with user's ip?
I'm creating an notification system where people can press a button named "never show me this notification again". I'm using the django context_processors because I want to show the notifications on every pages. Since I want to be able to manage the notifications directly through the admin interface I have a model form with two fields : title, message this is how I call the last notification created to show it to the user. context_processor.py from .models import Notification def notifications(request): notification = Notification.objects.last() ip = get_ip(request) #user's ip adress if request.method == "POST": #hide this notification to this ip with cookies return {'last_notification': notification} As for the template page I thought about something like this : base.html <h4>{{ last_notification.title }}</h4> <p>{{ last_notification.message }}</p> <form method="post"> {% csrf_token %} <button type="submit">never show me this notification again</button> </form> How can I use cookies and visitor's IP to hide the notification if he submits the form ? -
DRF: Reverse foreign key assignment using an array of primary keys
As stated in this question With Django REST Framework, a standard ModelSerializer will allow ForeignKey model relationships to be assigned or changed by POSTing an ID as an Integer. I am attempting to update a reverse relationship of the following format: class Lesson(models.Model): name = models.TextField() class Quiz(models.Model): lesson = models.ForeignKey(Lesson, related_name='quizzes', null=True) class LessonSerializer(serializers.ModelSerializer): quizzes = serializers.PrimaryKeyRelatedField(queryset=Quiz.objects.all(), many=True, write_only=True) class Meta: model = Lesson fields = ('quizzes') When posting an update containing an array of quiz primary keys using LessonSerializer I get TypeError: 'Quiz' instance expected, got '1'. Is it possible to assign or change a reverse relationship by POSTing an array of primary keys? -
django.core.exceptions.ImproperlyConfigured: error thrown when trying to write to database - Django app
This is my factbot.py file (scraper) from bs4 import BeautifulSoup import requests from lxml import html from .models import Fact def scrapeFacts(): page = requests.get('http://www.randomfunfacts.com/') tree = (page.content) soup = BeautifulSoup(tree, 'html.parser') fact = soup.find_all("i")[0].string print(fact) f = Fact(text = fact) f.save() This is my manage.py file: import os import sys import schedule import time import threading from threading import Thread from time import sleep from fact_bot_portal.factbot import scrapeFacts keepGoing = True schedule.every().day.at("20:40").do(scrapeFacts) def runScheduler(): while keepGoing: schedule.run_pending() time.sleep(1) if __name__ == "__main__": thread = Thread(target = runScheduler) thread.start() On scheduled scrape, I want the fact to be added to the database but I get this error: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. on server start. Thanks for any help you can give. -
HTML. How to make VS Code not add new lines automatically
I can't find suitable option for me to disable automatically adding newlines. I am using django and newlines often added in a middle of special tag, and it breaks everything. -
Django - Modeling a transition function
I'm using Django and trying to create a model for a Finite automaton and this is what I came up with so far: class Alphabet(models.Model): alphabet = models.CharField(max_length = 10, null = True, blank = True) automata = models.ForeignKey(Automata, on_delete = models.CASCADE) class States(models.Model): state = models.CharField(max_length = 10, null = True, blank = True) final = models.BooleanField(default = False) initial = models.BooleanField(default = False) automata = models.ForeignKey(Automata, on_delete = models.CASCADE) class Automata(models.Model): Now I would like to model the transition function, there is one for each automaton: Example: we can go from state1 to state2 using symbol1 I'm not sure how to go through with that, any help would be appreciated! -
Django server doesn't seem to be able to respond while requesting
I am trying to build an open-auth like system where the user can log into one app via another. During the process, my "authentication" app secretly sends a token to the "client" app. Then the client app calls the authentication app asking for the user's details, to check that they haven't changed. Finally, the authentication app responds with the user details, and the user is redirected to the client app and logged in with the token as a password. All this seems to work well on my local machine. However, when pushed on my public server, things go wrong. It looks like the authentication app can't handle being asked for user details while it's still waiting for a reply from the client app that should be confirming that the token has been set. Basically, the client app waits for the authentication app to reply to its request for details, which it never does. So the client app never replies to the authentication app that the token has been set successfully. So the request can never succeed. This is the rough timeline AUTH : Posts token to client, waits for 200 response CLIENT : Receive token, asks for user details, waits … -
Keep getting Server Error - 500
Every time I request a blog post on my website, I receive a server error 500. I have been trying to debug it for the past 3 days, and I have not been able to figure out what is going on. Here is the views.py for the blog detail: def blog_detail(): post = Post.objects.get(request_post) try: Next_Post_id = (post.id + 1) Next_Post = Post.objects.get(id=Next_Post_id) Next_Post = Next_Post.id except ObjectDoesNotExist: Next_Post = None # Previous Post try: Previous_Post_id = (post.id - 1) Previous_Post = Post.objects.get(id=Previous_Post_id) Previous_Post = Previous_Post.id except ObjectDoesNotExist: Previous_Post = None context = {'post': post, 'Next_Post': Next_Post, 'Previous_Post': Previous_Post} return render(request, "BlogHome/pages/post.html", context) and here is the post.html template: {% extends "BlogHome/includes/WELL.html" %} {% block content %} <script> document.title = "Pike Dzurny | {{post.title}}" </script> <div class="container-fluid text-center"> <center> <div class="well" id="WellPost"> <div class="container-fluid"> <h2 align="center" id="TitleText">{{post.title}}</h2> <h3 align="center" id="BodyText">{{ post.date|date:"m-d"}}</h3> <h3 align="left">{{ post.body|safe }}</h3> {% if post.id == 1 %} <ul class="pager"> <li class="previous disabled"><a href="/blog/{{ Previous_Post.id }}"><span aria-hidden="true">&larr;</span> Older</a></li> <li class="next "><a href="/blog/{{ Next_Post.id }}">Newer <span aria-hidden="true">&rarr;</span></a></li> <h1>hi 1</h1> </ul> {% if Next_Post is defined %} <ul class="pager"> <li class="previous disabled"><a href=""><span aria-hidden="true">&larr;</span> Older</a></li> <li class="next"><a href="/blog/{{ Next_Post.id }}">Newer <span aria-hidden="true">&rarr;</span></a> </li> </ul> <h1>2</h1> {% Previous_Post is defined … -
Websockets VS Server Sent Events(SSE) based on performance
I am aware of the difference between the two. Using WebSockets one can have bidirectional communication but with SSE only data can be pushed to power. But at the same time, web sockets are heavy. I am implementing a small game which will be played by 8-10 users simultaneously. I need to update the UI of all other players, whenever someone makes a move. The user interaction with the game is minimal. In this case, should I go with Websockets for the two-way interaction or SSE for updating the browser and POST requests from the browser to the server whenever a player makes a move. Which will be more efficient performance and load wise on the server. My backend is in Django and I will be using Django channels for SSE or Websockets. -
Django exclude insert/select logs
Every time I use get_or_create or any similar method, a have lots of logs in my terminal. I don't want to reduce logging level, but I also don't want to recieve these logging messages from Django. How can I avoid them? Any corrections in settings.py? -
Pass values between Forms
I have several forms(I'm not using formwizard) I want to take decisions based in the value of previous form. For instance: - disable a form2.field the if form1.field has a specific value - Transfer a value from form1 to form2 I'd like to put all the logic in the forms. I was trying to get the value in the save in the session from the form, I couldn't class form1(forms.ModelForm): ... class form2(forms.ModelForm): def __init__(self,*args, **kwargs): ms = kwargs.pop('fieldform1',None) if ms == 'value': self.fields['fieldform1'].widget.attrs['readonly'] = True -
Django - dynamic change form fields
I have a simple form to add a website to database. This is my site model: class Site(models.Model): category = models.ForeignKey('Category') category1 = models.ForeignKey('Category', related_name='+',) subcategory = ChainedForeignKey( 'Subcategory', chained_field='category', chained_model_field='category', show_all=False, auto_choose=True) name = models.CharField(max_length=70) description = models.TextField() # importuje zmienione TextFields widgets.py keywords = MyTextField() date = models.DateTimeField(default=datetime.now, editable=False) url = models.URLField() is_active = models.BooleanField(default=False) group = models.CharField(max_length=2, choices=(('Basic', 'Basic'), ('Premium', 'Premium'))) subcategory1 = ChainedForeignKey( 'Subcategory', chained_field='category1', chained_model_field='category1', related_name='subcategory1', show_all=False, auto_choose=True) def get_absolute_url(self): return "%s/%i" % (self.subcategory.slug, self.id) class Meta: verbose_name_plural = "Sites" def __str__(self): return self.name Forms.py class SiteAddFormFull(forms.ModelForm): url = forms.URLField(widget=forms.TextInput(attrs={'readonly': 'readonly'})) class Meta: model = Site fields = ('url', 'name', 'description', 'keywords', 'group', 'category1','subcategory1') I would like to change my form by adding fields 'Category1', 'Subcategory1' after user choose value in group field ('Premium'). Form should reload itself and show those fields. Before choosing 'Premium' fields 'Category1', 'Subcategory1' should be invisible. How can I achieve that? -
Django AbstractModel add table after migrate
I'm using AbstractModel to store created and modified user object for Post object. Effect of makemigrations is new table "userabastractmodel" and i don't know why. I removed database and then created new but the result is the same. This adds to my Post model a field userabstractmodel_ptr_id. I need these fields in Post table not in other connected by ForeginKey. What is wrong in this code? Models class UserAbstractModel(models.Model): created_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='+') modified_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='+') class Model: abstract = True class Subject(models.Model): name = models.CharField(max_length=80, null=False, blank=False, unique=True) slug = models.SlugField(unique=True, help_text='Short label used in URLs') category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='+') def save(self, *args, **kwargs): """Override save method to add some functions""" self.slug = slugify(self.name if self.slug in ['', None] else self.slug) super(Subject, self).save(*args, **kwargs) class Post(UserAbstractModel): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='+') content = models.TextField(blank=False, null=False) Makemigrations log forum\migrations\0001_initial.py: - Create model Category - Create model Subject - Create model UserAbstractModel - Create model Post - Add field created_user to userabstractmodel - Add field modified_user to userabstractmodel -
Django, the user model, profiles, and security
I just started fidling with the user model, and I'm probably wrong on this but I just had a thought and I'm not knowledgable enough to persuade myself it is indeed wrong. I have a user model, which I extended with a profile via a one-to-one model. (most sources I could find recommended this as a best practice). Now, it is possible for general users on my app to access bits of the profile data, such as someone's username (part of the user model) or nationality (part of the profile model). I grab this data in a view I created via objects.get and pass on the results to a template. But doesn't this also pass on the (hashed) passwords? And if so isn't this unsafe? -
Vesta panel Django
I want to run Django using Vesta panel. I tried it using Apache and using Nginx. Everywhere does not come out, no access. Tried the instructions from the website https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04 All muffled... Forgive to help or may have a suitable manual Ubuntu 16.04, Django 1.10, python 3.5 Or there is another free panel with clear settings? -
How to localize Django website
I have a website developed using Django. I want to offer language switcher option to translate the site to another language. Is there any plugin (like Google Language Translate for WordPress Site) or some other way to achieve the goal? -
Django custom authentication syntax error
I am trying to upgrade my Django project to 1.10, but I am hitting this brick wall when implementing custom email authentication. I have followed the instructions on django docs, but it keeps throwing silly and confusing IndentationError: Environment: Request Method: POST Request URL: http://localhost:8000/accounts/login Django Version: 1.10.5 Python Version: 2.7.13 Installed Applications: [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'debug_toolbar', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', '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'] Traceback: File "C:\Users\ED\Environments\firone_110\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\ED\Environments\firone_110\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\ED\Environments\firone_110\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ED\Environments\firone_110\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\ED\Environments\firone_110\firone_110\accounts\views.py" in dispatch 34. return super(Login, self).dispatch(*args, **kwargs) File "C:\Users\ED\Environments\firone_110\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Users\ED\Environments\firone_110\firone_110\accounts\views.py" in post 67. the_user = authenticate(**the_credentials) # <-- This is what I do not understand. Why is this an error? File "C:\Users\ED\Environments\firone_110\lib\site-packages\django\contrib\auth\__init__.py" in authenticate 66. for backend, backend_path in _get_backends(return_tuples=True): File "C:\Users\ED\Environments\firone_110\lib\site-packages\django\contrib\auth\__init__.py" in _get_backends 27. backend = load_backend(backend_path) File "C:\Users\ED\Environments\firone_110\lib\site-packages\django\contrib\auth\__init__.py" in load_backend 21. return import_string(path)() File "C:\Users\ED\Environments\firone_110\lib\site-packages\django\utils\module_loading.py" in import_string 20. module = import_module(module_path) File "c:\python27\Lib\importlib\__init__.py" in import_module 37. __import__(name) Exception Type: IndentationError at /accounts/login Exception Value: unindent does not match … -
Django Object to Create a New Google Maps Marker
There are several online posts with others trying to accomplish the same thing, but none that provided a solution. I have a database of veteran memorial plaques and one of the variables is a map grid that is matched to a set of pre-defined lat/lng. What I am trying to do is use the {{ grid_map }} Django as my map position variable. Any help or feedback would be great. Below is my template and script. <section id="course-list"> <div id="plaques" class="table-responsive"> <table class="display table table-hover course-list-table"> <thead> <tr> <th>First</th> <th>Last</th> <th>Branch</th> <th>Wall</th> <th>Dir</th> <th>Row</th> <th>Num</th> <th>map</th> </tr> </thead> <tbody class="list"> {% for obj in object_list %} <tr> <th><a href="{{ obj.get_absolute_url }}">{{ obj.first_name }}</a></th> <th><a href="{{ obj.get_absolute_url }}">{{ obj.last_name }}</a></th> <th>{{ obj.branch }}</th> <th>{{ obj.wall|upper }}</th> <th>{{ obj.direction|title }}</th> <th>{{ obj.row }}</th> <th>{{ obj.plaque_num }}</th> <th>{{ obj.grid_map }}</th> </tr> {% endfor %} </tbody> </table> </div> <script> var title = {{ title | js }}; // This is mapped to context var map; a2 = {lat: 32.840801, lng: -117.244842}; // Test Marker // Need to Use Django Variables. function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: 32.840691, lng: -117.24469}, zoom: 24, mapTypeId: 'satellite', disableDefaultUI: true, scrollwheel: false, draggable: true }); … -
Transient use of Django Model instances
I have a use case where a particular class can either be transient or persistent. Transient instances are build from a JSON payload on a PUT call, and may either be persisted to the database or used during the server call and then either returned or discarded. What is best practice for this case? My options seem to be: Write two classes, one of which is a models.Model subclass, and the other of which isn't, and make them implement the same API, or Use the Model subclass, but be careful not to call save(). Is either of these preferable, according to conventional use of Django models? -
How to have extra django model fields depending on the value of a field?
I have a model in my Django project called Job. Each Job has a category. An example of a category could be tutoring. This can be represented as what my model looks like right now: from __future__ import unicode_literals from django.db import models class Job(models.Model): # Abbreviations for possible categories to be stored in the database. TUTORING = "TU" PETSITTING = "PS" BABYSITTING = "BS" INTERIOR_DESIGN = "IND" SHOPPING = "SH" SOFTWARE_DEVELOPMENT = "SD" DESIGN = "DE" ART = "AR" HOUSEKEEPING = "HK" OTHER = "OT" JOB_CATEGORY_CHOICES = ( (TUTORING, 'Tutoring'), (PETSITTING, "Petsitting"), (BABYSITTING, "Babysitting"), (INTERIOR_DESIGN, "Interior Design"), (SHOPPING, "Shopping"), (SOFTWARE_DEVELOPMENT, "Software Development"), (DESIGN), "Design"), (ART, "Art"), (HOUSEKEEPING, "Housekeeping"), (OTHER, "Other"), ) created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) description = models.TextField() category = models.CharField(max_length=3, choices=JOB_CATEGORY_CHOICES, default=OTHER,) def __str__(self): return self.title Depending on the category of the Job, different fields are required. For example, if I take tutoring as the category again, then extra fields like address, subject, level of study and others are needed. If the category of the Job is software development however, extra fields like project_size and required_qualifications are needed. Should I create a separate model for each type of Job or is there some kind of model …