Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to perform more/less than filter based on user choice using django-filter
I'm building an app using Django and django-filter. In the DB I have a table with a column named TOTALOFFERAMOUNT, it has integer values (I'm using -1 value to represent that this total offer amount is indefinite) Now for filtering, I use django-filter to filter results based on three fields, one of them is TOTALOFFERAMOUNT. I want to give the possibility that the user when enters a value for TOTALOFFERAMOUNT can decide if he wants the results to be less than or more than or 'Indefinite' Like the picture below: So I want to know how can I implement this. -
Installing 3 Django applications on a shared web server trough cPanel
I am trying to install my applications on a shared web server running phusion Passenger but after a week I am still unable to complete this "simple" task. I wrote a working Django application and now I hae to upload it on my shared web server so I wrote this simple passenger_wsi.py file: #--------------------------------------------------------------------------- # \file passenger_wsgi.py # \brief # # \version rel. 1.0 # \date Created on 2021-05-16 # \author massimo # Copyright (C) 2021 Massimo Manca - AIoTech #--------------------------------------------------------------------------- from DjHello.wsgi import app application = app and this is my DjHelloWorld.wsgi : """ WSGI config for DjHello project. It exposes the WSGI callable as a module-level variable named app. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ #!/opt/alt/python38/bin/python3.8 import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') app = get_wsgi_application() -
Hello, guys. I trying to run my first app in Django, have followed all instructions but isn't working, don't know where is the problem
Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(file).resolve().parent.parent Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-u%xm5q1bi(6t8iretu5s8(sv(0=ip!x-qk7wu1&ef=bhl^2i' SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] Application definition INSTALLED_APPS = [ 'hello', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Markdowned content not reflected in my html template (<em><strong>)
In my Django project, I am using markdownify to convert my markdown to HTML. I have a problem while rendering the HTML content to my template. some tags like <em>, <strong> are not getting reflected. I have tried using the safe filter as suggested in this stackoverflow post but I find no changes! Is there any other filter I can use or any method to render correctly in settings.py MARKDOWNIFY = { "default": { "STRIP": True, "BLEACH": True, "MARKDOWNIFY_LINKIFY_TEXT": True, "WHITELIST_TAGS": [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'em', 'i', 'li', 'ol', 'p', 'strong', 'ul' ], "WHITELIST_ATTRS": [ 'href', 'src', 'alt', ], "WHITELIST_STYLES": [ 'color', 'font-weight', ], "LINKIFY_TEXT": { "PARSE_URLS": True, "PARSE_EMAIL": True, "CALLBACKS": [], "SKIP_TAGS": ['pre', 'code',], }, "WHITELIST_PROTOCOLS": [ 'http', 'https', ], "MARKDOWN_EXTENSIONS": [ 'markdown.extensions.fenced_code', 'markdown.extensions.extra', ] }, } in my template: <div class="col-8"> {{ entry|markdownify|safe }} </div> the content: #This is the H1 tag for Heading but these are working - paragraph - all the headers - list tag things not getting converted - *Italics not working* - **And also bold text** In my template,this is what i get This is the H1 tag for Heading but these are working paragraph all the headers list tag things not … -
Django Celery Recursive Error With tasks.py, Not With views.py
I've created a recursive function to get all children of a certain object. def get_all_children(self): children = [self] try: child_list = self.children.all() except AttributeError: return children for child in child_list: children.extend(child.get_all_children()) return children It works fine when I call this function in my views.py file. But it gives me a RecursionError: maximum recursion depth exceeded in comparison when I call the same function in my celery tasks.py file -
django.db.utils.DataError: value too long for type character varying(4)
I added fields to my model but it's causing errors on migrate in production. I looked at various proposals on fixing this but couldn't get them working. Possible I'm not implementing them well. Would somebody be knowing the exact cause for this???? This is the error message. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 104, in database_forwards schema_editor.add_field( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 487, in add_field self.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 142, in execute cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", … -
Should I include /data folder created by docker-compose to Git?
I'm new to docker and docker compose. To be quiet honest, I'm new to programming in general. Currently I'm following a course in Web Development with Python (Django) and JavaScript. One of the project hinted that we should try to use docker. I use docker-compose to start Django server and connect them to a Postgres database. This configuration is copied from Docker documentation in Django version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db This resulted in a creation of a folder called /data under the root. Should I add this to the repository? Should I even use volumes for database? (In the course tutorial, the database part only include: services: db: image: postgres Thanks in advanced. -
How do I send QuerySets with Django using AJAX?
So, I have submitted a form using AJAX to a Django application but I am finding it a bit difficult to send the output back to my site... trips = Trip.objects.all() context = { "view":"trip", "listofTrips":zip(tripsData, tripsUserData), "noOfTrips":len(tripsData), "searched":True, } So I have QuerySets as well as ZIP files to send, and I cannot save it anywhere as the zip file is a queryset and saving it then downloading it would reduce my performance greatly. So is there any method by which I can get that done without refreshing...We can't use a JsonResponse since I get a (500) server error...so how can I send my data? Thanks! -
Django ORM substitute a field value with a calculation on it
I have this query in mu Django project: def calc_q(start_d, end_d, pr_code): start_d = start_date end_d = end_date pr_code = proj_code var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", "var_val", ) well i would to substitute the "var_val" value with a calculation on it's value, so i create a method like this one: def test_calc(c_val): return c_val*3 and i modify my ORM code : def calc_q(start_d, end_d, pr_code): start_d = start_date end_d = end_date pr_code = proj_code var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", test_calc(ast.literal_eval("var_val")[0]), ) i use ast becaus my var_val value is a string rappresentation of a list ("[112, 92]" for example) So when i run my code again i get: raise ValueError(f'malformed node or string: {node!r}') ValueError: malformed node or string: <_ast.Name object at 0x0000026C3F986DF0> How can i add a calculated field value diectly on my ORM code? So many thanks in advance Manuel -
Python console input from html form using django
i have a personality analysis python script, but I want to make it runs in html and get the input form from html page, and the shows the result back in html page. I already use a django framework to run html page. But i don't know how to connect it with python script I have have attached the python script. # -*- coding: utf-8 -*- import csv import os import pickle import re import string from collections import Counter import pandas as pd import tweepy from nltk.corpus import stopwords from nltk.stem import * from nltk.stem.snowball import SnowballStemmer from nltk.tokenize import word_tokenize from sklearn.feature_extraction.text import TfidfVectorizer from unidecode import unidecode ckey = 'ld6wr3Gt5ZdrKzQ4NGYCFCVA7' csecret = 'ErvYLR40biJWD0kr4wpjUUBK8vKDhGzdCwyzgiUOKdlyeYmaTG' atoken = '585075150-wFq2hQhw8x7oHEKjS4W9xVpsX3UGOtZvNblvSjuo' asecret = 'CwqO7p3esu6K45fNvQytitvXpCbrnKeRgGajs2qUsu74J' auth = tweepy.OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) emoticons_str = r""" (?: [:=;] # Eyes [oO\-]? # Nose (optional) [D\)\]\(\]/\\OpP] # Mouth )""" emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) "]+", flags=re.UNICODE) regex_str = [ emoticons_str, r'<[^>]+>', # HTML tags r'(?:@[\w_]+)', # @-mentions r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs r'(?:(?:\d+,?)+(?:\.?\d+)?)', # numbers r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and ' r'(?:[\w_]+)', # other words … -
Heroku : gunicon not identifying custom module in Django app
I am using a custom module in my Django app,when I tried to deploy this in Heroku, gunicorn is not detecting this module. Here is my code in manage.py where I have imported the module-relative import from .defs import log_transform Directory structure is below Link This is the build error am geting File "/tmp/build_2aedecf2/manage.py", line 6, in from .defs import log_transform ImportError: attempted relative import with no known parent package ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. Logs are as below return _getattribute(sys.modules[module], name)[0] 2021-06-26T07:11:29.515762+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 331, in _getattribute 2021-06-26T07:11:29.515763+00:00 app[web.1]: raise AttributeError("Can't get attribute {!r} on {!r}"2021-06-26T07:11:29.515763+00:00 app[web.1]: AttributeError: Can't get attribute 'log_transform' on <module '__main__' from '/app/.heroku/python/bin/gunicorn'> 2021-06-26T07:11:29.518944+00:00 app[web.1]: 10.7.237.91 - - [26/Jun/2021:07:11:29 +0000] "GET /result/?csrfmiddlewaretoken=rYlkcjC8Gx6y8zgXZ5cIABjg58UsmjuWzO9MqH3E1frADPTNY4pObgJ9itQMz8vj&FA=10.2&VA=0.32&CA=0.45&RS=6.4&CL=0.073&TSD=13&PH=3.23&SU=0.83&AL=12.6 HTTP/1.1" 500 89852 "https://wineprediction012.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36" -
How to override field name attribute in django model form?
I have a model form similar to the one below: class BookSearchForm(ModelForm): class Meta: model = Book fields = ['publisher', 'authors', 'category' How to override fields name attribute in the above model form? I tried this, but it did not work: class BookSearchForm(ModelForm): class Meta: model = Book fields = ['publisher', 'authors', 'category' widgets = { 'publisher': forms.SelectMultiple(attrs={'name': 'pub'}), 'authors': forms.SelectMultiple(attrs={'name': 'aut'}), 'category': forms.SelectMultiple(attrs={'name': 'cat'}), } -
CSS for TextField Django
I am developing a django website. I would like to know if there were any decent css stylings for text fields for forms in django. Thanks. -
how can i automatically assign user and image through spreadsheet as i'm getting errors in django
-->I'm using the stackoverflow for the first time and sorry for any mistakes. -->HI, there im developing a website as part of my final year project i.e exam hall seating arrangement system using django where the student registers and login to the website using his/her credentials after that they can view their exam hall seating arrangements. -->but the main thing during examinations i have to assign student examination hall and image of the his/her seating allocation. they are nearly 4k students where it is hectic task to done manually so i come through uploading a spreadsheet where it contains all the related details about the student username,examination hall and seating arrangement image i am getting error while uploading the spread sheet. -->how can i assign user and image through spreadsheet in django? errors -
Django server is not starting after importing custom declared class from a python file
I have written a custom class in a python file and trying to import it to another file.But once I import the class, django server is not starting after so much time, here is what I am doing .. helper.py def class GeneriMethod: @staticmethod def afunc1(): return "something" @staticmethod def bfunc2(): pass .... .... tasks/views.py from django_app_name.helper import GenericMethod generic_obj = GenericMethod() #method 1 def tsk_func1(): #call the imported class methods generic_obj.afunc1() #method 2 def tsk_func2(): #call the imported class methods GenericMethod.afunc1() After doing this when i do python manage.py runserver , why it is taking too much time like 5-10 minutes to run the server,when i remove the import then it works faster, i have no idea what is going on, please help me to resolve this -
Django Rest API unable to connect with React
I have two computers. I made a to-do app in one of them and I copied all of the code to the other. But when I run the code on the other PC, react is unable to find the Django rest API. I followed this tutorial: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react Failed to load resource: the server responded with a status of 404 (Not Found) App.js:27 Error: Request failed with status code 404 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62) -
How to search by different parameters with Django REST API?
Suppose I'm developing a backend for an application that will have products or something, and that application will communicate with the server through REST API. Each product will have multiple fields like title, description, price, rating... What are some of the good ways for filtering by multiple fields? Example: Search string: gaming laptop price: from 400$ to 1000$ rating: more than 3 stars ... I was planning to have a single string that confirms pre-defined rules for searching, taking it, parse it, and returning the result. So, the URL would look something like this: www.foo.com/products/search/contains=laptop&min_price=400&max_price=1000&min_stars=3. these filters are optional. Not sure if taking a single string then parsing it is the best way. -
How to update 2 tables in one page in django
Assuming there are 2 tables in one page. table 1 shows the list of all items and table 2 shows the list of all deleted items. whenever i click delete button the corresponding row from table 1 is moved to table 2. I am not sure how to do all these in one page! -
How to solve the problem to use request.user in custom profile fields
- models.py As you can see all code here. I want the user after athenticate had filled the all profile fields but there is 'AnonymousUser' object has no attribute '_meta' error. from django.db import models from django.contrib.auth.models import User class ProfileModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) age = models.PositiveIntegerField() city = models.CharField(max_length=50) country = models.CharField(max_length=50) def __str__(self): return self.name forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import * class UserProfileForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] class ProfileForm(forms.ModelForm): class Meta: model = ProfileModel fields = ['name', 'age', 'city', 'country'] views.py The userprofile is success and when profile request is post then the error arise def userprofile(request): if request.method == 'POST': form = UserProfileForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('App_Login:profile')) else: form = UserProfileForm() return render(request, 'App_Login/userprofile.html', {'form': form}) def profile(request): if request.method == 'POST': form = ProfileForm(request.POST, instance=request.user) if form.is_valid(): name = form.cleaned_data['name'] age = form.cleaned_data['age'] city = form.cleaned_data['city'] country = form.cleaned_data['country'] reg = ProfileModel(name=name, age=age, city=city, country=country) reg.save() else: form = ProfileForm(instance=request.user) return render(request, 'App_Login/profile.html', {'form': form}) -
Pull a column from sqlite3 and use those data in django dropdown
----models.py---- This model uses sqlite3 default database of django from django.db import models from django.contrib.auth.models import User class item_master(models.Model): item_name=models.CharField(max_length=200,null=False) item_price=models.IntegerField(max_length=5,null=False) ----views.py---- These are many pages in this django app... "abc.html" is the page which needs drop-down list and "showitems" is the related function. from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404, redirect from django.template import loader from django.http import HttpResponse from django import template from app.models import item_master from django import forms from django_select2.forms import ModelSelect2Widget from django.views import generic import sqlite3 @login_required(login_url="/login/") def index(request): context = {} context['segment'] = 'index' html_template = loader.get_template( 'index.html' ) return HttpResponse(html_template.render(context, request)) @login_required(login_url="/login/") def pages(request): context = {} try: load_template = request.path.split('/')[-1] print(load_template) context['segment'] = load_template html_template = loader.get_template( load_template ) if (load_template == "test.html"): items(request) return HttpResponse(html_template.render(context, request)) elif (load_template == "abc.html"): showitems(request) return HttpResponse(html_template.render(context, request)) else: return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template( 'page-404.html' ) return HttpResponse(html_template.render(context, request)) except: html_template = loader.get_template( 'page-500.html' ) return HttpResponse(html_template.render(context, request)) def showitems(request): if request.method == "GET": showdrop = item_master.objects.all() return render(request,'abc.html',{"showdrop":showdrop}) ----abc.html---- HTML code for the front end <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" /> <select id="selectitem" class="form-control" > <option selected disabled="True">--- select --- </option> {% … -
Django Product stock goes to 0 but we can still pay | other errors
If my product stock is 0 make sure they can't pay or continue even if it's already in the cart. For ex: We deleted this product from your cart due to it being out of stock or something like that or redirect them back to the home page. If you can explain or give me a tutorial that would help. Also if anyone can checkout my repository. In my cart.html I have it where if they want than more than 1 they can press the + button but they can keep adding more even if we don't have that much in stock it still goes through and they can pay. I know this one is basic but I can't seem to figure out how to do this lol so if anyone can please help I would appreciate that! If anyone wants to fix stuff or add stuff that would help plz do so lol. This is based on a paid course. My github: https://github.com/Gabriel7553/my_shop -
How to convert bytes to json in python
I'm trying to convert bytes data into JSON data. I got errors in converting data. a = b'orderId=570d3e38-d6486056e&orderAmount=10.00&referenceId=34344&txStatus=SUCCESS&txMsg=Transaction+Successful&txTime=2021-06-26+12%3A03%3A12&signature=njtH5Dzmg6RJ1KB' I used this to convert json.loads(a.decode('utf-8')) and I want to get a response like orderAmount = 10.00 orderId = 570d3e38-d6486056e txStatus = SUCCESS -
Why MERN better than React+Flask or React+Django?
I am a student and excited about ML stuff. But most of the time when I reach out to my fellow mates for any project they just tell me that they prefer MERN over React+Flask or React+Django. I haven't got any satisfying answer to this thing though that ,why they prefer MERN, as for me if I want to integrate my ML model with my website I would prefer React+Django/Flask for it. -
what are the best practices in accessing multiple apis in azure active directory
We have created an graphql api in django-graphene. In this api, we have use django-graphql-auth to provide authentication to the user. We have also vue js client application that will let sign up and sign in the user with the help of our created api. However, we've decided also to integrate microsoft to identity platform in order for us to let the user sign in using their microsoft account and we are planning to use microsoft graph. this means, that the user will have two tokens, one for microsoft graph and for our created api. How we should integrate this two apis? -
gunicorn Serve Error(500) in django 3.2 app on localhost
I'm trying to serve my Django 3.2 application using gunicorn on my localhost. First time, it ran correctly. Later, I changed DEBUG parameter to False in settings.py and I run it again. This time it gives me a server error. In terminal there is no error. See the pictures below. Why is this happening ? How to fix this ? Error Page settings.py terminal