Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What common approaches do I have to scaling data imports into a DB where the table structure is defined by Django ORM?
In the current project I'm working on we have a monolith Django webapp consisting of multiple Django "apps", each with many models and DjangoORM defining the table layout for a single instance Postgres database (RDS). On a semi-regular basis we need to do some large imports, hundreds of thousands of rows of inserts and updates, into the DB which we use the DjangoORM models in Jupyter because of ease of use. Django models make code simple and we have a lot of complex table relationships and celery tasks that are driven by write events. These imports have grown, and cause performance degradation or can be rate limited and take weeks, by which time data is worth a lot less - I've optimized pre-fetching and queries as much as possible, and testing is fairly tight around this. At other places I've worked, there's been a separate store that all ETL stuff gets transformed into and then some reconciliation process which is either streaming or at a quiet hour. I don't understand how to achieve this cleanly when Django is in control of table structures. How do I achieve a scenario where: Importing data triggers all the actions that a normal DjangoORM … -
Django Stripe Attribute Error - module 'requests' has no attribute 'Session'
I'm trying to get a basic Stripe set up in Django project but cannot get past this error. I am able to submit the initial Stripe form (get the green check) but I can't complete the payment and get successful payment template to show. I used an online tutorial that got me this far. Have been trying to use the Stripe docs and looking everywhere I can think of online but can't get anything to work. If someone help me with how to define a 'Session' that would be really appreciated. Django error ('stripe_payment' is the successful payment html template): Exception Type: AttributeError at /stripe_payment/ Exception Value: module 'requests' has no attribute 'Session' Settings: # Stripe Settings STRIPE_SECRET_KEY = '<secret key>' STRIPE_PUBLISHABLE_KEY = '<publishable key>' urls: from django.urls import path from . import views from .views import StripeCharge app_name = 'requests' urlpatterns = [ path('stripe_charge/', StripeCharge.as_view(), name='stripe_charge'), path('stripe_payment/', views.stripe_payment, name='stripe_payment'), ] views: from django.shortcuts import render, redirect from django.conf import settings from django.views.generic.base import TemplateView import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class StripeCharge(TemplateView): template_name = 'requests/stripe_payment.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context def stripe_payment(request): if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='usd', description='Test Charge', source=request.POST['stripeToken'] … -
Django 3, Python 3.8 Can't Find My Templates
I'm running Python 3.8 and Django 3.0.5 on Windows 10. I'm using JetBrains PyCharm 2(Professional Edition) to create and deploy my Django apps. Here's the code in my views.py: from django.shortcuts import render # Create your views here. def index(request): return render(request, "firstapp\homes.html") Views.py Here's the line in my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'y******** # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'firstapp', ] 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', ] ROOT_URLCONF = 'Hello.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Hello.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
URL error in {% url ... %} when breaking line in source code
I'm working on an app in Django (2.2) and I've run into an issue with one of my html templates, where the URL doesn't work when the source code line breaks inside a {% url ... %} tag. This is the code that doesn't work: <small><a href="{% url 'learning_logs:edit_entry' entry.id %}">edit entry</a></small> This is the error I get: Page not found (404) Request Method: GET Request URL: http://localhost:8000/topics/2/%7B%25%20url%20'learning_logs:edit_entry'%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20entry.id%20%25%7D Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ users/ [name='index'] topics/ [name='topics'] topics/<int:topic_id>/ [name='topic'] new_topic/ [name='new_topic'] new_entry/<int:topic_id>/ [name='new_entry'] edit_entry/<int:entry_id>/ [name='edit_entry'] The current path, topics/2/{% url 'learning_logs:edit_entry' entry.id %}, didn't match any of these. This is the code that works: <small><a href="{% url 'learning_logs:edit_entry' entry.id %}"> edit entry</a></small> Does it mean you can't break the line in source code inside {% url ... %} tags? Are there any workarounds for this? -
Django custom user with AbstractUser
from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): pass class Landlord(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) #other fields def __str__(self): # **Error is here** return self.user.email When I use email field of my user it has give this error: "Instance of 'OneToOneField' has no 'email' member" what is the reason for error?(And what fields are there in AbstractUser class?) How can I fix the error. -
Django template iterate over context list
I can't find a clear answer on this. I have a view that shows multiple models. In my template, I have written out everything to manually display what I want but it doesn't really stick to DRY so I'd like to iterate over the context. What I can't find is what the context object is referenced as in my template? I have written pseudo code in the template snippet below of what I want to achieve. views.py class ConfigurationDetailView(LoginRequiredMixin, TemplateView): ''' Returns a view of all the models in a configuration ''' template_name = 'configurator/configuration_detail.html' def get_context_data(self, **kwargs): ''' Uses a list of dictionaries containing plural strings and models to filter by the configuration ID to only show items in the config. ''' context = super(ConfigurationDetailView, self).get_context_data(**kwargs) context_dict = [ {'string':'integrations', 'model': IntegrationInstance}, {'string':'control_groups', 'model': ControlGroup}, {'string':'endpoints', 'model': Endpoint}, {'string':'scenes', 'model': Scene}, {'string':'actions', 'model': Action}, {'string':'smart_scenes', 'model': SmartScene}, {'string':'buttons', 'model': Button}, {'string':'button_actions', 'model': ButtonAction}, ] for item in context_dict: for key, value in item.items(): if key == 'string': string = value else: model = value context[string] = model.objects.filter(config_id__exact=self.kwargs['config_id']) return context template.html - pseudo code {% extends "base_generic.html" %} {% block content %} <div class="container"> <h1>Configuration Details</h1> {% for object in … -
How to return multiple values in Django Select2 autocomplete form
I am using Select2 for django to create autocomplete form. I would like for autocomplete form to return more fields from database. For example: in models i have this: class Places(models.Model): r_name = models.CharField(max_length=200, default=None) r_country = models.CharField(max_length=20, default='Englands', blank=True, null=True) r_place = models.CharField(max_length=200, default=None, blank=True, null=True) I want form to return r_name + r_country + r_place. When i was using jquery autocomplete, i wrote it like that and it worked: def PlacesNameAutocomplete(request): if request.is_ajax(): q = request.GET.get('term', '').capitalize() search_qs = Places.objects.filter(r_name__startswith=q) results = [] print(q) for r in search_qs: results.append(r.r_name + ' (' + r.r_country + ' - ' + r.r_place + ')') data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) Right now i am using this Select2 code for autocomplete, form returns r_name, but I don't know how to add country and place to return results. Views.py from dal import autocomplete from places.models import Places class PlaceAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): queryset = Places.objects.all() if self.q: queryset = queryset.filter(r_name__istartswith=self.q) return queryset Forms.py class newActivityForm(ModelForm): route_id = forms.ModelChoiceField( queryset=Places.objects.all(), widget=autocomplete.ModelSelect2(url='place-autocomplete', attrs={'data-placeholder': 'Start typing name ...', 'data-minimum-input-length': 3, 'style': 'width: 100%' },)) -
Django Crispy Forms / Adding my own classes
I want to change the design of crispy form field with my own classes. I read some information about it but could no find the solution. Let me add my files and explain: forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from django.core.exceptions import ValidationError class UserRegisterForm(UserCreationForm): ...some code... email = forms.EmailField(label='İTÜ Maili') class Meta: model = User fields = [...'email'] widgets = { 'email': forms.EmailInput(attrs={'class': 'myClassName'}), } This is how I wanted to add my class to email field. register.html <div class="container-fluid mt-5"> <div class="row justify-content-center text-center"> <div class="col-4"> </div> <div class="col-4"> <form class="mt-5" id="registerForm" method="post"> {%csrf_token%} {{ form.email|as_crispy_field }} <button type="submit" value="SIGN UP" class="button is-secondary">Submit</button> </form> </div> <div class="col-4"> </div> </div> </div> This is my template. I added background-color:black; to my css class to check whether it works, but unfortunately it did not work. I tried to write the template with labels and inputs but messed up with validation errors and etc. Is there any way doing this only using crispy form code like I have written: ({{ form.email|as_crispy_field }}) -
Using Jinja2 MemcachedBytecodeCache With Django
I apologize if this answer is obvious, but I can't seem to figure out how to enable Jinja2's MemcachedBytecodeCache in Django (I'm using version 3.0, but generally either). Jinja's documentation makes it sound like it a relatively straightforward setting: class jinja2.MemcachedBytecodeCache(client, prefix='jinja2/bytecode/', timeout=None, ignore_memcache_errors=True) This class implements a bytecode cache that uses a memcache cache for storing the information. It does not enforce a specific memcache library (tummy’s memcache or cmemcache) but will accept any class that provides the minimal interface required. The goal, obviously, is to enable Jinja's bytecode caching with Memcached, which is already enabled on my site. Any assistance in implementing this in settings would be much appreciated. Thank you! -
How can I create multiple objects with one view/form in Django
So here's what I'm attempting to do, and if there's a better way, please let me know. I am creating a dating app and am attempting to create a message form that displays once a user has matched with another user. I already have the matching down and the users displaying correctly, but I need this messaging component. This will be in the form of a link beneath the user's profile that my user has matched with. Now, my InstantMessage model has a foreign key to Conversation which should contain 2 members, whom are having a conversation and contains at least one message exchanged between each other . Now, I what I want to do, when a user hits a link to start messaging, to have my code check if there is already a conversation object between the two users, and if so, then use that conversation object pk for my conversation field in Instant Message and then create a form for that. And if there isn't, then I want a conversation object to be created first, and then a message object to be created. I want this all in one view and with one link, so I assume I … -
Django Python: can't open file 'manage.py': [Errno 2] No such file or directory
I'm having the same issue as this question regarding deploying a Django project to Heroku. I've followed the comments to investigate further, but there's no additional feedback from the original poster to finish the conversation. Following on the Mozilla instructions I make it to the heroku run python manage.py step, which returns the error below: Running python manage.py migrate on ⬢ fast-oasis-14644... up, run.2316 (Free) python: can't open file 'manage.py': [Errno 2] No such file or directory Following the comment from Chris in the referenced question, I ran heroku run bash to get a shell on a one-off dyno. Looking at the structure there, the manage.py file is two levels down in the clmp folder, which is the name of my Django app. ~ $ ls Procfile README.md requirements.txt runtime.txt src ~ $ cd src ~/src $ cd clmp ~/src/clmp $ ls assets clmp contracts manage.py templates I'm assuming that this means something is misaligned with what Heroku is looking for vs my Procfile setup, but I've used web: gunicorn clmp.wsgi --log-file - following on the Mozilla instructions referenced above. My git push to Heroku master is successful. Thanks in advance for the help. -
Counting number of records in database: Django
I'm trying to output the count of the number of "subscribers" in my database in Django, I've found count in my view and then I think I'm using it correctly in the html, but it always just outputs "there are subscribers" without the number, when I use "|length" in the html it always outputs 0, so I'm not sure what my error is. views.py def list_todo_items(request): context = {'todo_list' : Todo.objects.all()} count = Todo.objects.count() context2 = {'count': count} # context = {'count': Todo.objects.count()} # count = Todo.objects.count() return render(request, 'index.html',context,context2) def insert_todo_item(request: HttpRequest): todo = Todo(content=request.POST['content']) try: todo.full_clean() except ValidationError: # pymsgbox.alert('ValidationError! Phone number must be entered in the format: +999999999. Up to 15 digits allowed.', 'Title') return redirect('/main/list/') todo.save() return redirect('/main/list/') def delete_todo_item(request,todo_id): todo_to_delete = Todo.objects.get(id=todo_id) todo_to_delete.delete() return redirect('/main/list/') index.html {% for todo in todo_list %} <li class="list-group-item> {{todo.content}} <form action="{% url 'delete_todo_item' todo.id %}" method="post" class="float-right d-inline"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i> </button> </form> </li> <li class="list-group-item"> <span class="font-italic">There are {{ count }} subscribers.</span> </li> {% empty %} <li class="list-group-item"> <span class="font-italic">No current subscribers.</span> </li> {% endfor %} -
Plotting map with python
I am trying to get a map to plot coordinates which i have saved in my csv file using python and have output it to my django site. This is what i'm trying, using the OSM which I found a tutorial on import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('D:\Desktop\map.csv') g=df.head() BBox = ((g.longitude.min(), g.longitude.max(),g.latitude.min(), g.latitude.max()) > (116.0561,116.1235,5.9611,5.9981) fig, ax = plt.subplots(figsize = (8,7)) ax.scatter(df.longitude, df.latitude, zorder=1, alpha= 0.2, c='b', s=10) ax.set_xlim(BBox[0],BBox[1]) ax.set_ylim(BBox[2],BBox[3]) ax.imshow(plt.imread('D:\Desktop\map.osm'), zorder=0, extent = BBox, aspect= 'equal') However im getting an error, invalid syntax on fig. Please give me any other suggestions of how to implement this (plotting coordinates on a map and also having it output to a django site) -
Django prevent data from passing in URL
I am new to Django and web dev. I am currently working on a textbox that a user will input data. Then they will click submit and I want that data to go to another page. However when they click the submit button, all the text ends up in the URL. The amount of text that will be passed in this text area is going to be thousands of characters. Is it possible to not allow it to appear in the url? This is my textbox and submit button: <form action="{% url 'parsed' %}"> <textarea name="fulltextarea" cols=40 rows=10></textarea> <br /> <input type="submit" value="Submit"/> </form> urls.py urlpatterns = [ path('', views.home, name='jsonparser-home'), path('parsed/', views.parsed, name="parsed") ] views.py def parsed(request): data = request.GET.get('fulltextarea') print(data) return render(request, 'jsonparser/parsed.html', {"json":data}) Now when I enter text into my text box and click the submit button my URL gets the data in it as: http://localhost:8000/parsed/?fulltextarea=wefwefallmydatasubmittedishere Is it possible to remove all of that in the URL? -
How to post a list of objects containing file input with Axios post and Django
I want to create a web app that allows users to upload a list of files with an associated file name that the user chooses. I want my POST to look as below. {"user": "ME", "files": [{"file":"InMemoryFileUpload", "name": "file_name"}, {"file":"InMemoryFileUpload", "name": "file_name1"}]} I cannot find a way of extracting the files from the POST for this particular use case. I can extract the elements from the list if there are no file objects, and I can extract files if they are not stored in a list. Here is my simplified React script import React, { Component } from "react"; import axios from "axios"; class SomeForm extends Component { handleSubmit(e) { e.preventDefault(); const user = '3' const selectedFile = e.target.input.files[0]; const selectedKey = e.target.keyName.value var formData = new FormData(); formData.append('user', user) formData.append('files', [{'name': selectedKey, 'file': selectedFile}, {'name': 'TEST', 'file': selectedFile}]) axios.post("http://localhost:8000/api/handle_user_input/", formData) } render(){ return( <form onSubmit={this.handleSubmit}> <label>Upload File:</label> <input type="text" name="keyName" /> <input type="file" name="input" /> <button type="submit">Upload</button> </form> ); } } export default SomeForm; The request POST.data is like below <QueryDict: {'user': ['3'], 'files': ['[object Object],[object Object]']}> How can I POST the files correctly in this format? Also, this is my first Django project so any other feedback is … -
HTTP Error 403 on pafy package for python
I have a Django app in which I am using pafy. It worked perfectly fine until today. Now when I try to play a song I get this error: Access to r1---sn-uxaxiv0nxx5q-nv4l.googlevideo.com was denied The page also says "HTTP ERROR 403". The thing is that I haven't changed anything in my code to get this error. What can be causing this? My code is: views.py def more(request,song_url,title): url = 'http://www.youtube.com/watch?v=' + str(song_url) video = pafy.new(url) s = video.getbestaudio(preftype='m4a') audio_stream = {'extension': s.extension, 'video_url': s.url + "&title=" + video.title} context = {'stream': audio_stream, 'title': video.title, 'song_title': title}] more.html <a href="{{ stream.video_url }}" style="text-decoration: none;" download="{{ song_title }}.{{ stream.extension }}" target="_blank" >Play/Download</a> -
Problem configuring react inside a drf project
I'm trying to create auth scheme for my API using this tutorial: JWT auth guide When trying the react part of the tutorial I ran 'npm run build' and got the following error: yovel@YovelBeastPad:~/PycharmProjects/Triangulation$ npm run build > triangulationapi@1.0.0 build /home/yovel/PycharmProjects/Triangulation > webpack --config webpack.config.js /home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/cli.js:93 throw err; ^ ReferenceError: triangulationapi is not defined at Object.<anonymous> (/home/yovel/PycharmProjects/Triangulation/webpack.config.js:20:9) at Module._compile (/home/yovel/PycharmProjects/Triangulation/node_modules/v8-compile-cache/v8-compile-cache.js:192:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10) at Module.load (internal/modules/cjs/loader.js:996:32) at Function.Module._load (internal/modules/cjs/loader.js:896:14) at Module.require (internal/modules/cjs/loader.js:1036:19) at require (/home/yovel/PycharmProjects/Triangulation/node_modules/v8-compile-cache/v8-compile-cache.js:161:20) at WEBPACK_OPTIONS (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/utils/convert-argv.js:114:13) at requireConfig (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/utils/convert-argv.js:116:6) at /home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/utils/convert-argv.js:123:17 at Array.forEach (<anonymous>) at module.exports (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/utils/convert-argv.js:121:15) at /home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/cli.js:71:45 at Object.parse (/home/yovel/PycharmProjects/Triangulation/node_modules/yargs/yargs.js:567:18) at /home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/cli.js:49:8 at Object.<anonymous> (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/cli.js:366:3) at Module._compile (internal/modules/cjs/loader.js:1147:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10) at Module.load (internal/modules/cjs/loader.js:996:32) at Function.Module._load (internal/modules/cjs/loader.js:896:14) at Module.require (internal/modules/cjs/loader.js:1036:19) at require (internal/modules/cjs/helpers.js:72:18) at Object.<anonymous> (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack/bin/webpack.js:156:2) at Module._compile (internal/modules/cjs/loader.js:1147:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10) at Module.load (internal/modules/cjs/loader.js:996:32) at Function.Module._load (internal/modules/cjs/loader.js:896:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! triangulationapi@1.0.0 build: `webpack --config webpack.config.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the triangulationapi@1.0.0 build script. I understand that the error has something to do with webpack but where is the error is coming from, and what does it mean? Project structure: My 'front' Django app inside … -
How to style specific django form field in html and css
How do I style the form in CSS and without using bootstrap or crispy forms, any help is appreciated, Thanks. .field1 { font-family: inherit; margin-bottom: 25px; display: flex; justify-content: space-between; } label { font-family: Segoe UI; font-size: 18px; color: #1E1E1E; padding-left: 60px; } .holder { padding-right: 60px; } <div class="field1"> <label>Username</label> <span class="holder">{{ form.username }}</span> </div> [1]: https://i.stack.imgur.com/CxfoX.png what it looks right now [2]: https://i.stack.imgur.com/GgHlz.png what it should look like -
How to resize images with Django when uploading to AWS S3?
I am uploading and storing my media files on DigitalOcean Spaces (which is built on AWS) with Django using the Boto 3 package. Everything works fine and I am able to view my images on my site, however, I get an error when trying to modify the image using Pillow on upload. I would like to convert the images to JPEG and resize and optimize them. This is how my model's current save function looks: def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.image: img = Image.open(self.image.path) if img.mode != 'RGB': img = img.convert('RGB') if img.width > 100: ratio = img.width / img.height height = 100 / ratio output_size = (100, height) img.thumbnail(output_size) img = ImageOps.exif_transpose(img) img.save(self.image.path, optimize=True, quality=90, format='JPEG') If anyone can help me, I would really appreciate it! -
How to add disable attribute to a Django <select> form?
I have a Django choice form: SEASON_CHOICES = ( ('running', 'Running season'), ('next', 'Next season' ) ) class DeterminingForm(forms.Form): season = forms.ChoiceField(widget=forms.Select, choices=SEASON_CHOICES) I want a disabled option in my form. Something like a placeholder with 'Choose an option', just like you see on almost any select form. I don't know how to do this. Any idea? -
Aborting long running request in Django
I want to abort a request to an API which takes longer than 5 seconds. I know the client-side code can have a timeout of 5 seconds and that will ensure it doesn't wait any longer than that to get a response, but the Django server would still be processing the request even though the client won't be receiving it at the end. As far as I know, even if I configure this on nginx or gunicorn, those will still act as clients for the Django server app and the same problem will occur - that nginx will not wait for more than 5 seconds, but Django will continue processing the request. Is there any way I can somehow abort this request processing in Django (application server code level) itself? -
css script working but js script not working in Django
My index.css script located at Project/static/css/index.css is working fine and effect is seen in index.html page. But window alert from index.js script is not seen. Since .css script is working fine, I assume that there is no issue with settings.py so problem might be with linking. I tried two alternatives: Both not working. Please help! Html page: Project/templates/index.html <!DOCTYPE html> {%load static%} <html lang="en" dir="ltr"> <head> <script src="{% static "jss/index.js" %}" type="text/javascript"></script> <link rel="stylesheet" href="{% static "css/index.css"%}"> <meta charset="utf-8"> <title>Base Html</title> </head> <body> {%block body%} {%endblock%} </body> </html> Javascript Page: Project/static/jss/index.js alert("Hello, Welcome to my page"); settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '&cq=^n*t!55h)0c@3f+7*ilrvr$066)*n)&-8v6rokna4-yd30' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', ] 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', ] ROOT_URLCONF = 'Project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N … -
Safest and driest way to filter query_set depending on some user info
I have a Post model with a boolean field, is_draft. If the user is logged and is member of the staff, then I want to displays all posts; otherwise, only the posts for which is_draft is false. My first thought was to use a custom model manager and use request.user as following: class PostManager(models.Manager): def get_queryset(self): if request.user and request.user.is_staff: return super().get_queryset() else: return super().get_queryset().filter(is_draft=False) but request is not available in the model. I saw some people use a middleware to access the user in the model. It seems to me the safest way to address my need (ie it's done once, in the custom manager; people modifying the views.py don't have to bother, no risk of forgetting it) but this solution seems controversial. I have of course the possibility to add some logic in the view, but I feel this is not DRY (as I query Post many times) nor safe (risk somebody forgets it at some point). According to you, what would be the cleanest and safest way to address this need? PS: I've found a similar question for which a solution was proposed for Class-based views, but my views are function-based. Thanks a lot! -
How to change href in django based on the current page url?
As I said in the title, what would be the correct syntax to change the href of a link according to the current url the user is on? I tried this, but it doesn't work. {% if url == '' %} href='/cookies' {% else %} href='' {% endif %} What would be the correct syntax to do this? -
djnango DoesNotExist at /medical-basics
this is what i see instead of the table contents.the code is completely fine and the server is running fine too.The Microsoft Edge console shows "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" DoesNotExist at /medical-basics Tutorial matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/medical-basics Django Version: 2.1.7 Exception Type: DoesNotExist Exception Value: Tutorial matching query does not exist. Exception Location: C:\Users\JShaikh\anaconda3\envs\djangoenv\lib\site-packages\django\db\models\query.py in get, line 399 Python Executable: C:\Users\JShaikh\anaconda3\envs\djangoenv\python.exe Python Version: 3.7.7 Python Path: ['C:\Users\JShaikh\Desktop\apple\mysite', 'C:\Users\JShaikh\anaconda3\envs\djangoenv\python37.zip', 'C:\Users\JShaikh\anaconda3\envs\djangoenv\DLLs', 'C:\Users\JShaikh\anaconda3\envs\djangoenv\lib', 'C:\Users\JShaikh\anaconda3\envs\djangoenv', 'C:\Users\JShaikh\anaconda3\envs\djangoenv\lib\site-packages'] Server time: Tue, 21 Apr 2020 16:45:23 +0000