Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why are browsers refusing to load my .js files and complaining about MIME types?
I'm trying to learn Django from a (very good) book. It's just got to the chapter where some Javascript is being added. I am not really a newb when it comes to Javascript. But I've hit the complete buffers with this. We are told to put these lines towards the end our Django template file base.html: <script src="/static/jquery-3.3.1.min.js"></script> <script src="/static/list.js"></script> <script> initialize(); // NB this is a simple function in the list.js script </script> All the browsers I've tried (Firefox, Chrome, Opera) fail to load these JS files. In the case of Chrome (console) I get Status 404 for these two files, whereas two .css files in the same directory get Status 200. In the case of FF (v. 72) the console messages are slightly more cryptic: for both files the console first gives a baffling MIME-related message: "The script from “http://localhost:8000/static/jquery-3.3.1.min.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type." and then immediately afterwards says "Loading failed for the with source “http://localhost:8000/static/jquery-3.3.1.min.js”." I have done quite a bit of searching to find out what might be going on. I have tried lines like this in the Django template file in question: <script type="text/javascript" … -
Installing latest version of GDAL with Dockerfile to deploy django app in gcloud
I'm trying to deploy my django app in gcloud, however it's failing to run due to the version (version 1.11.3) of GDAL that is being installed when I run the dockerfile, because I need to have GDAL version superior to 2 (according to what I've read about the error in other posts). I've seem similar issues with different suggestions, but I haven't been able to fix my problem. Any ideas what I could do? The error I get when running with the attached app.yaml and Dockerfile is the following: Updating service [default] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Application startup error! Code: APP_CONTAINER_CRASHED [2020-04-19 17:56:40 +0000] [6] [INFO] Starting gunicorn 20.0.4 [2020-04-19 17:56:40 +0000] [6] [INFO] Listening at: http://0.0.0.0:8080 (6) [2020-04-19 17:56:40 +0000] [6] [INFO] Using worker: sync [2020-04-19 17:56:40 +0000] [9] [INFO] Booting worker with pid: 9 [2020-04-19 17:56:44 +0000] [9] [ERROR] Exception in worker process Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, … -
How to use linebreak in Django templates
Hi I am new to python Django. I want new line in specific places, So I tried def abc(request): text = "This is\n a good example" return render(request, 'test.html', {'text' : text}) In HTML part Hello {{ text|linebreaks }} And this is working perfectly fine with output Hello This is a good example Here is my question I store some 400 - 800 words in my database which has approximately 4-5 paragraph. I want to new line here. So, I store data like "This is\n a good example" in my database. And simply call it in django template(Html side) but it prints Hello This is\n a good example In here why line break is not working? My HTML true code {% for essay in eassays %} {{ essay.description|linebreaks }} {% endfor %} I have changed name. Also, I am loading 100 such data. Any possible solution or other logic! Thankyou! -
How to open a project folder in Spyder IDE?
I am new to Spyder after VS Code and now want to open my Django project folder. I'm following these steps: Projects > New project > Existing directory > Create but Spyder opens some temp.py which after closing opens untitled0.py,untitled1.py,untitled2.py and so on. How can I see my project structure, files as in VS Code ? -
How can I use id as foreign key in django?
Product Model with fields Name, Description, Price Stock model with ProductID(foreignkey Reference), Name, Description, Price, Quantity -
Django Middleware is not able to process view functions correctly
I am trying to do login/logout using Django Middleware. I have gone through few tutorials but all are posted with old versions. I am trying to hardcode the except function inside middleware instead of having in setting.py as follow: middleware.py: EXEMPT_FUNC = ['Accounts:login', 'Accounts:logout', 'Accounts:register'] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') path = request.path_info.lstrip('/') url_is_exempt = any(url.match(path) for url in EXEMPT_FUNC) if path == reverse('Accounts:logout').lstrip('/'): logout(request) if request.user.is_authenticated() and url_is_exempt: return redirect('User:home') elif request.user.is_authenticated() or url_is_exempt: return None else: return redirect('Accounts:login') url.py: app_name = 'Accounts' urlpatterns = [ path('login', views.login_view, name='login'), path('logout', views.logout_view, name='logout'), path('register', views.register_view, name='register') ] Above code is not working as intended, please help on what am I doing wrong. Really appreciate your help. -
count same value in one column of database and display in template Django
I am having trouble to count same value in one column of database and display in template Django template image in template image {{bestofartists.0.artist_name}} gives 'Alessia Cara' and {{bestofartists.1.artist_name}} gives Coldplay database image now by seeing database image, i need to take that value 'Alessia Cara' again from template and do query to count total 'Alessia Cara' in 'album_artist' and display in same template, value is '2' as per image. can it be done in template only? sorry for long question. noob here. need help. thank you -
Deploying Django+React to Heroku - Uncaught SyntaxError: Unexpected token '<'
I am trying to deploy my Django + React application to Heroku. (Django for only api and React for frontend.) I followed this video, but cannot resolve this problem for several days. There is no error during deploy process, but after deploy, only white blank screen is showed up. This is the only clue I can find until now... I tried adding type="text/babel" to your script tag, adding base href tag to index.html, and changing several package.json and settings.py options. This is my package.json file. { "name": "frontend", "version": "0.1.0", "homepage": "https://myapp.herokuapp.com/", "private": true, "proxy": "http://localhost:8000", "dependencies": { "@material-ui/core": "^4.9.5", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "^4.0.0-alpha.46", "@material-ui/styles": "^4.9.0", "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.5.0", "@testing-library/user-event": "^7.2.1", "babel-preset-react": "^6.24.1", "react": "^16.13.0", "react-dom": "^16.13.0", "react-redux": "^5.0.7", "react-scripts": "3.2.0", "redux": "^4.0.0", "redux-thunk": "^2.3.0" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "postinstall": "npm run build" }, "engines": { "node": "12.14.0", "npm": "6.13.4" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "axios": "^0.19.2", "react-router-dom": "^5.1.2" } } And this is settings.py file. """ Django … -
django Model filter by list
i am getting list of value from checked checkbox , Now i want to filter the list with my model and get only filter result of value in list views.py def ResultTest(request): var = request.POST.get('selectedTests') var1 = BookTest.objects.filter(test=v) return render(request, 'posts/result.html',{'var1':var1}) html file <input type="hidden" id="selectedTests" name="selectedTests"> i am getting the selectedTests a list of values now i want the list of values to filter in models and get all data of the values. -
response change on every GET request in django
I am trying to implement a load balance in Django using a round-robin technique by getting a different response on every GET call. My Model: class Load_Balancing(models.Model): instance_name = models.CharField(max_length=100) sequence = models.IntegerField() algorithm = models.CharField(max_length=100) I have tried: class Get_Instance(APIView): def get(self, request): ins = Load_Balancing.objects.all().order_by("-sequence")[:1] print(type(ins)) data = {} for r in ins: data["instance_name"] = r.instance_name return Response(data) Here instance_name is random URL and I'm trying to make it dynamic so that on every GET request I get the last instance and then other instances in order i.e the 1st instance in the database and so on. -
I'm trying to use stripe payment. But having some issues on submitting card details
Im following just django tutorial. I'm unable to get any success message or error message after clicking submit button. the page is not even getting redirected after clicking submit button. dont know where i went wrong with my post method. P.s. Ive created my stripe acc and Ive used those public and private keys. Any help is appreciated. TIA payment.html {% extends 'base.html' %} {% block content %} <main class="mt-5 pt-4"> <div class="container wow fadeIn"> <h2 class="my-5 h2 text-center">Payment</h2> <div class="row"> <div class="col-md-12 mb-4"> <div class="card"> <script src="https://js.stripe.com/v3/"></script> <form action="." method="post" id="stripe-form"> {% csrf_token %} <div class="stripe-form-row"> <label for="card-element" id="stripeBtnLabel"> Credit or debit card </label> <div id="card-element" class="StripeElement StripeElement--empty"><div class="__PrivateStripeElement" style="margin: 0px !important; padding: 0px !important; border: medium none !important; display: block !important; background: transparent none repeat scroll 0% 0% !important; position: relative !important; opacity: 1 !important;"><iframe allowtransparency="true" scrolling="no" name="__privateStripeFrame5" allowpaymentrequest="true" src="https://js.stripe.com/v3/elements-inner-card-fbfeb5b62d598125b16ab6addef894d6.html#style[base][color]=%2332325d&amp;style[base][fontFamily]=%22Helvetica+Neue%22%2C+Helvetica%2C+sans-serif&amp;style[base][fontSmoothing]=antialiased&amp;style[base][fontSize]=16px&amp;style[base][::placeholder][color]=%23aab7c4&amp;style[invalid][color]=%23fa755a&amp;style[invalid][iconColor]=%23fa755a&amp;componentName=card&amp;wait=false&amp;rtl=false&amp;keyMode=test&amp;apiKey=pk_test_i0vc3rYRd3tcPmIsJIIQOiiI00khWr20iQ&amp;origin=https%3A%2F%2Fstripe.com&amp;referrer=https%3A%2F%2Fstripe.com%2Fdocs%2Fstripe-js&amp;controllerId=__privateStripeController1" title="Secure payment input frame" style="border: medium none !important; margin: 0px !important; padding: 0px !important; width: 1px !important; min-width: 100% !important; overflow: hidden !important; display: block !important; height: 19.2px;" frameborder="0"></iframe><input class="__PrivateStripeElement-input" aria-hidden="true" aria-label=" " autocomplete="false" maxlength="1" style="border: medium none !important; display: block !important; position: absolute !important; height: 1px !important; top: 0px !important; left: 0px !important; padding: 0px !important; margin: … -
debugging a django app (locally) in VS Code can't find my database container db
When I run a debug configuration in VS Code: "configurations": [ { "name": "Django Tests", "type": "python", "request": "launch", "program": "${workspaceFolder}/src/manage.py", "args": [ "test", "src" ], "django": true } I get this error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known I don't have this problem when I run the app normally: ./src/manage.py runserver db is my containerized postgresql database. services: db: container_name: db build: ./postgresql expose: - "5432" ports: - 5432:5432 ... Perhaps I'm not using the proper python path? I should be running this from within my python virtual environment but I'm not sure how to set that in the VS Code configuration, if that's the problem. Here's my settings.py POSTGRES_HOST = os.environ.get('POSTGRES_HOST', '127.0.0.1') POSTGRES_PORT = os.environ.get('POSTGRES_PORT', '5432') -
Djnago Excel file loading and performing function
I have created a django Library app to manage Authors and their books. I have also created a script that when run extracts data from a excel file and converts it into JSON format and then I have to run another script in django shell to load the json file to the database and saving it. Is there any way from where I can load the data in django itself and create a view to manage all the functions, such as extraction and data loading. Following is the models.py file: from django.db import models from django.db.models.signals import pre_save from books.utils import unique_slug_generator, unique_slug_generator_author, unique_slug_generator_genre from django.urls import reverse # Create your models here. class BookManager(models.Manager): def is_read(self): return self.filter(read='y') def is_not_read(self): return self.filter(read='n') class Genre(models.Model): name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') slug = models.SlugField(max_length=250, null=True, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('books:genredetail',kwargs={'id': self.slug}) class Author(models.Model): first_name = models.CharField(max_length=100, help_text="Enter first name of the author",default="Unknown") last_name = models.CharField(max_length=100, help_text="Enter last name of the author",blank="true") slug = models.SlugField(max_length=250, blank=True) def __str__(self): return f'{self.first_name} {self.last_name}' def get_absolute_url(self): return reverse('books:authordetail',kwargs={'id': self.slug}) class Meta: unique_together = ("first_name", "last_name") class Book(models.Model): YES = 'y' NO = 'n' DID_READ_CHOICES = [ … -
django output as django json array
Can we return it as json array with the code I wrote below? So output as json array I'm actually printing. but I want it to result as a json array ` class DebtFinancialReceivedAmountListAPIView(ListAPIView): permission_classes = [IsOwner] filter_backends = [django_filters.rest_framework.DjangoFilterBackend] def get(self, request): spending = Spending.objects.filter( createdDate__gt=(self.request.query_params.get('startingDate')), createdDate__lt=(self.request.query_params.get('endDate'))) \ .aggregate(spendingAmount=Sum('spendingAmount'), spendingKdv=Sum('spendingKdv'), spendingTotal=Sum('spendingTotal')) debtsReceived = Debt.objects.filter( paymentDate__gt=(self.request.query_params.get('startingDate')), paymentDate__lt=(self.request.query_params.get('endDate'))) \ .aggregate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount')) constantSpending = ConstantSpending.objects \ .filter(user=self.request.user) \ .aggregate(constantSpendingAmount=Sum('constantSpendingAmount'), constantSpendingTotal=Sum('constantSpendingTotal')) result = {**debtsReceived, **spending, **constantSpending} return Response(result) ` code output as follows ` HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "totalDebt": 290.0, "receivedAmount": 53.0, "spendingAmount": null, "spendingKdv": null, "spendingTotal": null, "constantSpendingAmount": null, "constantSpendingTotal": null } -
Django not detecting new changes to models
I just added a new field to my model, but when running python manage.py makemigrations it won't detect anything and when visiting the admin interface the new field won't show up. I'm using postgresql as database. class Movies(models.Model): title = models.CharField(max_length=30, blank=True, null=True) ###(...)### director_name = models.CharField(max_length=30, blank=True, null=True) keywords = models.ManyToManyField('Keywords', through='MoviesKeywords', related_name='movies')# This is the new field class Meta: managed = False db_table = 'movies' (keywords is the new field) I already tried passing the name of the app into the command like this: python manage.py makemigrations recommendations But I also get nothing in response. -
How to use a variable or change href in HTML using javascript (Django)
So right now in my navbar I have it as the following: <a class="nav-link" href="/home/{{applicant}}">Home </a> {{applicant}} returns the applicant's id (int). For security purposes I've decided to use a basic encryption so that someone can't easily guess a persons id. The encryption is simply some math done to the id ((((((id * 3) + 5 ) * 63 ) - 1 ) * 218 ) - 5) which while obviously not secure is good enough for the project. How would I apply this in the html using either django or javascript to modify the real id so that the href points to their encrypted id? I'm looking for something like below: <a class="nav-link" href="/home/" + encrypted id>Home </a> -
How to color html table in django based on condition
class11=[10,20,30,76] class12=[23,45,23,45] <table> <tr> <th>Class11</th> {% for class1 in class11 %}<td>{{class1}} </td> {% endfor %} </tr> <tr> <th>Class12</th> {% for class2 in class12 %}<td>{{class2}} </td> {% endfor %} </tr> </table> How to color Class 11 based on conditions : if value > 20 to color to red if value > 40 to color orange if value > 50 to color green I serached web they recomedn js but i am not good with js quite new. Is there nay way to do in CSS? -
Error: Using the URLconf defined in mysite.urls, Django-3 tried these URL patterns, in this order:,
I'm doing tutorial "Blog" from "Django 3 by example" and I got error. What i'm doing wrong? Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/ amd alsp TemplateDoesNotExist at /blog/. Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current URL, blog/, didn't match any of these. BLOG ADMIN mysite/urls.py from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), ] mysite/blog/views.py from django.shortcuts import render, get_list_or_404 from .models import Post # Create your views here. def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'post': posts}) def post_detail(request, year, month, day, post): post = get_list_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) mysite/blog/admin.py from django.contrib import admin from .models import Post # Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') prepopulated_fields = {'slug':('title',)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ('status', 'publish') mysite/mysite/urls.py from django.urls import path, include from mysite.blog import admin from . import views app_name = 'blog' urlpatterns = [ # post views path('', views.post_list, name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), ] … -
How to remove unwanted css and js from your django application?
I'm making a Fullstack application which uses Django as a backend and javascript and jquery as a frontend.The app is finished now I want to remove unwanted css,images,js which just lie there in static files but are not used in templates is there a way to remove all of this unwanted code,files.I checked on the internet and there are solutions like purgecss but they use npm for running and I don't have npm Is there any other way to it easily or if I have to do it by using purgecss.Can you guide me all the way in the answer section. Thank you -
Django - Message translation in template does not work
Translations in the same function for form.error work and messages are displayed in a different language, but for "messages" the text is still displayed in English in the template views.py from django.utils.translation import ugettext_lazy as _ form.errors['__all__'] = form.error_class([_('Bad pin')]) Works messages.add_message(self.request, messages.INFO, _('Bad pin')) Did not work, in the template after entering {{message}}, I see the English version Settings.py 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "account.middleware.LocaleMiddleware", 'django.middleware.common.CommonMiddleware', "account.middleware.TimezoneMiddleware", -
How to design an app with djano and node to make an appointment app/webapp
Where can I get proper tutorials or the steps/reference to develop an django app with node and google calendar integrated. for booking purpose. -
why flask app is not updating the browsing after reloading?
I am beginner in flask, I am facing issue in updating the template when i run the app flask run for the first time it works currently, but when I update the html or the python code and then reload the page the update does not effect in the browser i tried different browser but still doesn't work then i have to restart the IDE and run the app again this is my code from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') if __name__ == "__main__": app.run(debug=True) -
How to obtain multiple values from the drop down box django?
I am trying to obtain 2 values from an HTML dropdown menu as follows: <form action="POST"> <select name="season" id="season"> <option value="" selected disabled>Choose an option</option> <option value="Running">Running</option> <option value="2021">Summer 2021</option> </select> <h4>Select The Enrollment Batch:</h4> <select name="level" id="level"> <option value="" selected disabled>Choose an option</option> <option value="class-9">CAIE O Level (class 9)</option> <option value="class-10">CAIE O Level (class 10)</option> <option value="class-11">CAIE AS Level</option> <option value="class-12">CAIE A2 Level</option> </select> <button type="submit" class="btn deep-orange darken-2">Submit</button> </form> Is that even the proper way to obtain the data? Does the data come in as a tuple? What should the Django form be like and how do i save it in views? -
Django hosting for web development [closed]
How to host Django website in Google Cloud platform? -
keep getting this error{relation "profiles_user" does not exist}
I am a beginner programmer working on my own project on Django. I am trying to make a model create itself whenever a user is created. but i keep getting this error {relation "profiles_user" does not exist}. I am using PostgreSQL as my DB. from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save class User(AbstractUser): is_expert = models.BooleanField(default=False) is_student = models.BooleanField(default=False) EDUCATION=( ('Collage','Collage'), ('Post_Graduate','Post_Graduate'), ('Masters','Masters'), ('PHD','PHD'), ) class Expert(models.Model): expert = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(max_length=12, null=True, default='') last_name = models.CharField(max_length=20, null=True) discription = models.TextField(null=True) education = models.CharField(max_length=200, choices=EDUCATION, null=True) field = models.CharField(max_length=200, null=True) company = models.CharField(max_length=50,null=True) position = models.CharField(max_length=20, null=True) experience = models.TextField(null=True) charge_per_hour = models.IntegerField(default="0") def __str__(self): return (f'{self.first_name} {self.last_name}') def create_profile(sender,**kwargs ): if kwargs['created']: user_profile=Expert.objects.create(expert=kwargs['instance']) post_save.connect(create_profile,sender=User) Thank you for your help in advance