Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A QuerySet from a recursive Many-to-many model
Explanation There is a Tag model. Tags are used in relation to other tags. For example, "New Year Gift", "Birthday Gift" are marked with the "Gift" tag: Lvl1: Gifts / \ Lvl2: New Year Gifts Birthday Gifts / \ Lvl3: Card Toys Model Looks something like this: class Tag(models.Model): slug = models.SlugField(max_length=64) tag = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True, related_name='tags') Problem Now all tags in the system are organised in 3 levels: Top level Sub-level Sub-sub-level E.g.: Gifts > Birthday Gift > Toy Goal The goal is to construct a QuerySet which will return 3-level list, so it is passed into context and the template simply iterates over it and builds a 3-level DOM structure. The ultimate goal is to solve this in the most efficient way (in terms of DB/CPU load). I would think this could be done using annotating and some extra joins and values list. Any clues? -
How to pass value by request?
I have a middleware that maps websites for companies. I want to know which company the site belongs to and go through the request to be accessed in a view. The following example shows what I am wanting to do. #middleware.py virtual_hosts = { "www.example-1.com": "company1", "www.example-2.com": "company2", "www.example-3.com": "company3", } class HostMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): host = request.get_host() #How can I pass the value? request.atribute = virtual_hosts.get(host) response = self.get_response(request) return response How can I pass an attribute through the request? -
Sending multiple images from Django to React
I am working on project in which I am using Django as backend and React as frontend . I am using rest framework to feed the front end . I want to show multiple image on client side . One way is to the convert image into Base64 and send it using rest framework . But it is quite inefficient for multiple images (first converting those images and sending it ). Another way is I can pass my Django media url in response .The issue with this approach is that my images are private . This exposes my media url and maybe someone other can access those images. I would be grateful if someone can point me in right direction . -
Add clickable link to admin page List_view
I want to add a clickable link to admin list_view for a specific app that will redirect me to a html file i created, I have created a view.py like this from django.shortcuts import render from . models import * from django.contrib.auth.decorators import login_required @login_required def transaction_print(request, transaction_id): transaction = Transaction.objects.get(id=transaction_id) return render(request, 'report.html', {'transaction': transaction}) and my urls.py from django.urls import path from . import views urlpatterns = [ # path('', views.transaction_print, name='transaction_print'), path('transaction/<int:transaction_id>/', views.transaction_print, name='transaction_print'), ] I created the report.html at (root_dir/calculator/templates/report.html) Now im not sure how to make a method at models.py to return maybe my views as a link to be add to list_view, or what is the best approach to achieving that. Thanks! -
Heroku Environment Variables for S3 Bucket Not Being Read in Container Instance of Django App
I am pushing my Django app to Heroku as a container instance, but I am getting problems where it doesn't appear to be reading the environment variables. They are set using "heroku config:set AWS_STORAGE_BUCKET_NAME='my_bucket'" and so on. My python code working in development and uses the bucket storage successfully, but when pushing to Heroku I get the error shown which implies it is not passing the value for the bucket name. remote: if not VALID_BUCKET.search(bucket) and not VALID_S3_ARN.search(bucket): remote: TypeError: expected string or bytes-like object My settings file looks like this: AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_S3_CUSTOM_DOMAIN = '{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' I have a .yml file and I am thinking that I might need some configuration in there, but can someone help advise what that should be? It looks as below and I have tried adding environment variables under the config section to see if it makes a difference, but it didn't. setup: addons: - plan: 'heroku-postgresql:hobby-dev' as: DATABASE config: BUILD_WITH_GEO_LIBRARIES: '1' DISABLE_COLLECTSTATIC: '1' build: packages: - gdal-bin languages: - python run: web: gunicorn booksapp.wsgi --log-file - -
Django + plotly-dash: cannot render graphs side to side
I have followed this Subplot ( Side to side ) in python Dash and How to add multiple graphs to Dash app on a single browser page?, to find a way to get graphs rendering side to side in my template. I cannot get it to work, the size of the graphs are adjusting well, but they keep rendering one below the other. I am confused about what is going wrong, and as I am just picking up dash, I am struggling to identify the root cause of the issue. Here is my python file: import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go from django_plotly_dash import DjangoDash import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html import plotly.express as px from django_plotly_dash import DjangoDash external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] #external_stylesheets = app = DjangoDash('tryout', external_stylesheets=external_stylesheets) df_bar = pd.DataFrame({ "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"], "Amount": [4, 1, 2, 2, 4, 5], "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"] }) fig = px.bar(df_bar, x="Fruit", y="Amount", color="City", barmode="group") app.layout = html.Div(children=[ # All elements from the top of the page html.Div([ html.Div([ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application … -
Error with Django application deployment on Heroku
Please, help me fix this issue with Heroku. I wanted to host my Django & python application on Heroku but having this error coming up. This is the error getting from my browser: this is the error getting in my prompt after doing heroku logs --tail: 2021-01-29T19:05:21.512000+00:00 heroku[run.6267]: Starting process with command `python manage.py migrate` 2021-01-29T19:05:29.245349+00:00 heroku[run.6267]: Process exited with status 0 2021-01-29T19:05:29.281276+00:00 heroku[run.6267]: State changed from up to complete 2021-01-29T19:12:55.201869+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=grouppublishingindia.herokuapp.com request_id=1cd6be75-9711-4890-ac37-542c02731f37 fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:13:01.315149+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=grouppublishingindia.herokuapp.com request_id=9cb635ac-f755-437c-9706-b956967f9f32 fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:14:17.641461+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=grouppublishingindia.herokuapp.com request_id=d8ed6b4d-3fe4-4c3a-95d7-fc1a4bc7cd52 fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:14:20.774568+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=grouppublishingindia.herokuapp.com request_id=61570fe1-d1d3-41d0-846d-8f482e9f8bfe fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:16:09.470063+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=grouppublishingindia.herokuapp.com request_id=19bd2fb7-9739-4a80-b881-759f36c0e5b6 fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:16:13.909655+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=grouppublishingindia.herokuapp.com request_id=321e5a3a-798a-42ce-a9ab-39786097717f fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:25:36.896690+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=grouppublishingindia.herokuapp.com request_id=13206d28-14c4-4fc1-b57a-2d6b82ab05c9 fwd="103.252.25.76" dyno= connect= service= … -
How do I rank blog posts by sentiment in their comments in django?
I'm using TextBlob and I'm trying to add the polarity part of the result into the Comment model and then adding the average of the comments' polarities into the Post model so it can be sorted. I'm new to this stuff, that is why I'm stuck. Help will be appreciated. -
Django app on Windows Server 2012 - HTTP Error 500.0 - The FastCGI process exited unexpectedly
I setup a django "hello world" app IIS (Windows Server 2012). The application is run successfully using the Django web server. However, when I tried to install in on IIS (following the instructions provided here) I get an HTTP 500 error with the message "python.exe - The FastCGI process exited unexpectedly". I have seen numerous related posts on stackoverflow, but nothing seems to work for me. Based on the guidance I have checked file permissions on both the app and virtual environment folder but they in my opinion this should not be the issue as the users IUSR and IIS_IUSRS can Read & execute, Read and List folder contents. I have tried also to run wfastcgi-enable based on the instructions provided by this post but I get the error "ensure your user has sufficient privileges and try again". Please note that I tried running it both from an "elevated" command line and also power shell with no results. I have reinstalled python to make sure it is installed for "all users" (as suggested by this post) but I get an error "0x80070659 - This installation is forbidden by system policy". I looked in the Event viewer but I could not … -
Django urls.py + React router
I built a Django API and a react frontend to consume the API. I'm using react-router and can navigate just fine until I refresh the page. I then get a Not Found error form Django. I'm not sure how to set up these paths with Django so it knows what to serve. api/urls.py urlpatterns = [ path('', views.apiOverview, name='api-overview'), path('product-list', views.product_list, name='product-list'), path('product/<str:slug>', views.product_detail, name='product-detail'), path('images/<str:fk>', views.product_images, name='product_images'), ] urls.py urlpatterns = [ path('', TemplateView.as_view(template_name="index.html"), name='app'), path('admin/', admin.site.urls), path('api/', include('api.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app.js function App() { return ( <Router> <Nav /> <div className="App"> <Switch> <Route path="/products/:slug" exact component={ ProductDetail } /> <Route path="/products"> <Projects /> </Route> <Route path="/"> <div className='container'> <Header /> <hr /> <h2 className="section-title">Featured Products</h2> <ProductsListHome /> </div> </Route> </Switch> </div> <Footer /> </Router> ); } -
Is there a package in Atom IDE to help development/debugging Django projects as it is possible in VSCode/PyCharm?
Is there a package in Atom to help development/debugging Django projects as it is possible in VSCode/PyCharm? I went through many packages docs but I could not find any setting the packages autoimport and proper debugging tools (breakpoint, vars inspection, etc). Any suggestion? -
create_user() takes from 2 to 4 positional arguments but 5 were given django
I try to create user use User.objects.create_user. But it show error. create_user() takes from 2 to 4 positional arguments but 5 were given myuser = User.objects.create_user(username , email, password, friendid) -
Django Views redirect('homepage')
I'm stuck and don't understand why here my problem: I would like to return context if objects exists else redirect to homepage and raise error Objects.DoesNotExist. Here My Code : Views class PageDetail(TemplateView): """ Page View """ template_name = 'page_detail.html' def get_context_data(self, **kwargs): context = super(PageDetail, self).get_context_data(**kwargs) try: context['news'] = News.objects.filter(is_active=True).order_by('-date_created')[:4] except: pass try: context['page'] = Pages.objects.get(slug=kwargs.get('slug'), is_active=True) except Pages.DoesNotExist: return redirect('homepage') return context But I got this error : raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than HttpResponseRedirect. Tell me if you need more infos Thanks -
Get http://localhost:8000/Stack/script.js net:: Err_Aborted 404 / Django project
So I am attempting to build a simple to-do app, but when trying to work with some javascript to make the home page, I get the error detailed above (Get http://localhost:8000/Stack/script.js net:: Err_Aborted 404 ). I don't understand what I am doing wrong because this is my first time trying to work with javascript in my Django projects. Below is my code settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "Stack.apps.StackConfig", "crispy_forms", ] STATIC_URL = "/static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") CRISPY_TEMPLATE_PACK = "bootstrap4" base.py <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'Stack/styles.css' %}"> <title>Stack | Home </title> </head> <body> {%block content%} {%endblock content%} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> <script src="Stack/script.js" ></script> If I need to upload any more code to help solve this problem, please let me know. Thank you all. -
django app for loop: views.py or frontend?
I am building a django app which has a list of words. The app now tells the user the first word of the list via a speech function. Then the user can record an audio of a word he sais. This word gets turned into a string in the frontend. Now I want to compare the the word from the user with the first string of a second list that has the same amount of characters as the first list. And this whole process should be repeated with all characters of the first list. Can I do this kind of loop in my views.py or do I have to do it in the frontend? -
Is Django supposed to get so slow with around 250 000 model's objects?
I am doing some small project but with around 250 000 model's objects. I have my car model and I am importing data from external json. I talked with some people and they told me that 250 000 objects in django is not a big amount and it won't have much impact on performance. Loading up to models this data from json is takin around 5 - 10 min and I don't mind that. But, right now If I make any changes to the website (locally) while running runserver I have to wait around 1 minute (on macbook pro 2020 (not M1)). And it is pretty annoying. I ran command python -v manage.py check and apparently django.db.models.sql.compiler takes this whole time. I am wondering, if my approach with models is wrong, or it is normal with SQL Light? Or maybe I could safely turn off this check? Or I got wrong informations and workflow with this many model's object is totally wrong? -
TemplateDoesNotExit error when deploying project on heroku
am trying to deploy my project on heroku but am stumbling on the above error everything works fine when i run the code locally, kindly help out below are my setting and views file template settings 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', ], }, }, ] views of my Home app def Home(request): return render(request,'Home/index.html') -
Django - how can i call a model as a string?
I'm building a DRF api endpoint that should render some json data from my database. In my view, the name of the model to query to render the data is not fixed, it depends on what query does the user perform. So i have this: collection = 'MY_MODEL' queryset = collection.objects.filter(**filters) But this will give the following error: 'str' object has no attribute 'objects' This will work instead: queryset = MY_MODEL.objects.filter(**filters) Is there any way to get around this? -
Attribute Error - Model object has no attribute 'COOKIES'
I was initially having issues getting data from my API and it gave a "Forbidden" error, and now that I have fixed that with cookies and csrf token it's not working anymore. The Error: cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME] AttributeError: 'networthChart' object has no attribute 'COOKIES' [30/Jan/2021] "GET /api/networthchart/data/ HTTP/1.1" 500 102936 I am trying to data from an endpoint and this error comes up. here is the code: JS: <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); const request = new Request( "/api/networthchart/data/", {headers: {'X-CSRFToken': csrftoken}} ); $(document).ready(function(){ var endpoint = 'http://127.0.0.1:8000/api/networthchart/data/' var defaultData = [] var labels = [] $.ajax({ method:"GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: '# of Votes', data: defaultData, ....... </script> The … -
how to get date value in django template in format 1-7 day (weeks)
Please tell me if there is a way to transfer the day of the week, Monday -1, ... Sunday -7 to the django template. I found nothing among the tags and filters. -
How to send date based notification/ sms in djnago
I want to send date based notification/sms/email to user. I've created a dateBasedNotification model that contain title / date / recipent / message. Now data entry person can create the notifications. I want to send the contain message when date.today == smsDate. -
How can I add Redoc documentation to the Django using local yml schema file?
Does anyone know how can I add Redoc documentation endpoint using local schema.yml file? In the Swagger I do something like shown below unfortunately I have a problem with Redoc. Any ideas? urls.py: path('', TemplateView.as_view( template_name='swagger-ui.html', extra_context={'schema_url': 'openapi-schema'} ), name='swagger-ui'), swagger-ui.html: {% load static %} <html> <head> <title>Documentation</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% static 'schema.yml' %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], }) </script> </body> </html> -
How to make Django display compiled Angular index.html page
I have following structure of my Django and Angular app. Here in application I have complied angular project in dist folder. In dist - application I have index.html. What should I do to to make Django give me this index page then I request for example localhost:8000? I tried to manipulate with STATIC_ROOT but have a TemplateError. setting.py looks like this ANGULAR_DIR = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))).split('client')[0], 'application/' ) STATIC_ROOT = os.path.join(ANGULAR_DIR, 'dist', 'application') STATICFILES_DIRS = ( os.path.join(ANGULAR_DIR, 'dist', 'application'), ) and url.py looks like this from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('authentication.urls')), path('api/', include('api.urls')), url(r'^$', TemplateView.as_view(template_name='index.html')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to workout a logic, so that a user can send me a gift(point based) if they really like my blog? - In Django
hello guys/girls I am trying to figure out a logic similar to how we see in some social apps where the user is able to send gift points to the creator by paying some money. I am thinking of having a similar setup in my blog website, where the user can send me gifts if they find the blog useful. What's the best way to implement this? I want to store these information when the user sends a gift- the sender info (Only logged in users can send), for which blog post, how much points (There will be gift options like 10, 20, 50 points) and at what time. I am having trouble thinking about the logic as I have never done anything like this before. Should I go with the content types considering the future, if I plan to have vlogs section along with the current blogs for easier integration? Will using content type affect the performance greatly? Thanks -
django_crontab not working on production docker
I'm trying to run a scheduled script using django_crontab twice a day. I have tested it locally on ubuntu 18 and it works. However, when I'm trying to run it on the server (python Docker image that runs Django project on remote Ubuntu server) here is my code: setting.py: INSTALLED_APPS = ( . . 'django_crontab', . . . ) RONJOBS = [ ('25 8,21 * * *', 'appname.folder.file.start') ] I executed cron by: $ python manage.py crontab add . and see the active job: $ python manage.py crontab show f95300a5599dc7687ac79ab51c8bb33c -> ('13 9,21 * * *', 'appname.folder.file.start') def start(): logger.info(" process begins!") do_something() Note The function 'start' was tested in the production server and it works. I also tried to map the chronjob logs by adding path to the CRONJOB at setting.py: ('25 8,21 * * *', 'appname.folder.file.start','>> /Logs/crontab.log') but the file crontab.log wasn't created. Any suggestions? Thanks!