Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am having problems in displaying images in django project
I am trying to display an uploaded image on my Django website, but it seems I am unable to display it. Can anyone tell me what I am doing wrong? in settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' image is stored in project/core/media/images/image_name.jpg And the url i am getting after opening image in new tab is: http://127.0.0.1:8000/media/images/Bill_JcVkQAX.jpg DEBUG is true (if that helps somehow) Any help will be greatly appreciated. settings.py in urls.py and image link -
Django - Loggers are overwriting the previous log file along with the new one
I am using Django logger for logging along with gunicorn workers. Currently, I am testing with 3 workers and I am using the TimedRotatingFileHandler. I configured when = m and interval = 1, I tried sending some 1000 requests and it is writing in the new file and overwriting the old file as well. Here is my config from settings.py 'debug': { 'level': 'DEBUG', 'filename': BASE_DIR + '/Log/debug.log', 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'M', 'interval': 1, 'formatter': 'verbose' }, This will happen only if i use more than 1 gunicorn worker. But if I use 1 gunicorn worker this is not happening. -
How to use filepond with Django
As the title suggest. I have searched Google and stackoverflow, so far I don't find any tutorial that doesn't involve (https://github.com/ImperialCollegeLondon/django-drf-filepond). While this library seems maintain, at 68 stars, too much risk and I prefer to do without it. What I tried When you use filepond input tag with class file-uploader file-uploader-grid, in browser, it will compile and generate a div tag. The issue is that the id in input will be generated under the div instead of input tag. Without that id, when the form is submitted, self.request.FILES will be empty dictionary. So I tried writing a JavaScript to add id to input tag, which don't work unfortunately. Anyone successfully do it in Django without additional library? Thanks -
No procfile found in app image Error when deploying django app on aws ec2 instance
Im using dokku to deploy my images. Im using the following command to run the image dokku ps:start <app_name> but im getting the following error I already have a procfile in my project source file: web: daphne -b 0.0.0.0 -p $PORT lifeline.asgi:application worker: celery -A lifeline worker -l info beat: celery -A lifeline beat -l info Im a beginner on dokku. Can anybody help on this? -
How does Python import a module of big Github project?
I can't understand how the python import works for big projects on the Github. Everyone knows the import statement - "from packageName import moduleName". But for some big projects, for example Django. I've got tutored "from django.urls import path". (https://docs.djangoproject.com/en/3.2/topics/http/urls/) But couldn't find any path.py file under /django/urls directory from its Github structure. (https://github.com/django/django/tree/main/django/urls) Did I miss any advanced import mechanism? -
AttributeError: 'Serializer' object has no attribute 'Meta' in django rest framework
I am using serializers.Serializer instead of ModelSerializer which doesn't require Meta class but it keep saying object has no attribute Meta. Iam not sure what is the issue but when I run the localserver, the main page gives error saying api fetch error and in terminal it says AttributeError: 'Serializer' object has no attribute 'Meta'. My view: class ExampleView(viewsets.ModelViewSet): queryset = Example.objects.all().order_by('-created_at') serializer_class = ExampleSerializer serializer_action_classes = { 'get_all_students_of_a_class': ExampleDetailSerializer, } def get_serializer_class(self): """ returns a serializer class based on the action that has been defined. """ try: return self.serializer_action_classes[self.action] except (KeyError, AttributeError): return super(ExampleView, self).get_serializer_class() def get_employee_instance(self): /........../ return teacher def get_details_of_employee(self,request,pk=None): id = pk person = Person.objects.get(employee__id=id) data = { "employee": self.get_employee_instance(), "person": person } serializer_class = self.get_serializer_class() serializer = serializer_class(data) return Response(serializer.data, status=status.HTTP_200_OK) My serializer: class ExampleDetailSerializer(serializers.Serializer): employee = serializers.StringRelatedField() person = PersonSerializer() /................/ However it works and I can perform action if I go to localhost/admin and other api calls from localhost. -
Can a beginner learn Python and Javascript at the same time [closed]
I am new to Web Development and I want to learn both MERN and Django stacks. But i found it very hard to learn python and javascript at the same time. For me, the syntax looks very different and i always confuse where to put that : or ;. are there any way i can follow to learn both at the same time. Sorry for the grammer mistakes. -
pdfencrypt with Reportlab
I want to add password protection for opening the pdf file from a Django project. def pdf_view(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="members.pdf"' elements = [] doc = SimpleDocTemplate(response, rightMargin=0.5 * cm, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0) rows = [] users = User.objects.all() for user in users: rows.append(( user.username, user.email, user.first_name, user.last_name, formats.date_format(user.date_joined, "SHORT_DATETIME_FORMAT"), formats.date_format(user.subscriptions.current_period_end, "SHORT_DATETIME_FORMAT") )) table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1) table.setStyle([ ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ("ALIGN", (0, 0), (-1, -1), "LEFT"), ]) table = Table(rows, colWidths=46 * mm, rowHeights=30, repeatRows=1) elements.append(table) doc.build(elements) return response where can I add this line of code to do encryption pdfencrypt.StandardEncryption("password", canPrint=0) any help will be much appreciated -
Django - Return dict of posts grouped by hash tags
I'm working on a search function where the user can search Post by Hash_Tag. As in each post has a hash_tags and I want the the user to be able to do partial search of hash tags and for it to return the results. So for example let's say my Hash_Tag table has [goDawgs, godGiven, goGetEm] as hash tags stored and the user searches "go" then the results should return something like: {'goDawgs': [list of posts with this hash tag], 'godGiven': [list of posts with this hash tag], 'goGetEm': [list of posts with this hash tag]} As you can see in my models.py file below I have the hash tags parsed out and foreign keyed for each post. So it'll have a foreign key reference to hash tags if it's inside the post. How can I return a dict of hash tags and all the posts that contain that hash tag? view.py from drf_yasg.utils import swagger_auto_schema from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from cheers.models import * @swagger_auto_schema( method='get', operation_description="icontains search hash_tag table for <input> then retrieves all posts" "with the hash tags" ) @api_view(['GET']) def get_search_posts_by_hash_tag(request, input): partial_fit_hash_tags_list = list(HashTag.objects.filter(hash_tag__icontain=input).values('hash_tag')) filtered_posts = Post.objects.filter(hash_tags__in=partial_fit_hash_tags_list) pass … -
Django default run for every current object
models.py class Subscription(models.Model): #... many fields ... # I added this field when I already had many objects uniqueSubscriptionId = models.CharField(default=generateUniqueSubscription, max_length=30) generateUniqueSubscription from django.utils.crypto import get_random_string def generateUniqueSubscription(): return get_random_string(20) The Problem is that, when I run migrations, all of my old objects get the same uniqueSubscriptionId. I want each and every single old object to get a unique uniqueSubscriptionId. How can I do that? -
django manage.py loaddata : CommandError: No fixture named 'mydb' found
I want to populate DB with values into the deployed django app on heroku. So, I first deploy the app then I run it's one instance with heroku ps:scale web=1. Next, I start working on the populating the DB with: heroku run python manage.py migrate Then, I run the following two commands: **$ python manage.py dumpdata > dogpark/dumps/mydb.json** (socialapp) nikhi@DESKTOP-M2OFJPB MINGW64 ~/Documents/workspace_dogpark_2/dogpark_social_app (master) $ **heroku run python manage.py loaddata dogpark/dumps/mydb.json** Running python manage.py loaddata dogpark/dumps/mydb.json on nameless-sea-67566... starting, run.8999 (Free) Running python manage.py loaddata dogpark/dumps/mydb.json on nameless-sea-67566... connecting, run.8999 (Free)Running python manage.py loaddata dogpark/dumps/mydb.json on nameless-sea-67566... up, run.8999 (Free) I have been debugging the issue but solution is not found. I found the following two links but they did not resolve my problem : CommandError: No fixture named 'myapp' found and Cannot populate database table during Heroku deployment? Please suggest. -
Django DRF APITestCase post url results in 404 error
I'm learning DRF test cases, and in my test.py file, my URL in the client post-call is coming back in a 400 status error: Here's my urls.py: from django.contrib import admin from django.urls import path, include #from rest_auth.views import LoginView, LogoutView urlpatterns = [ path('admin/', admin.site.urls), path("api/", include("profiles.api.urls")), path("api-auth/", include("rest_framework.urls")), path("api/rest-auth/", include("rest_auth.urls")), path("api/rest-auth/registration/", include("rest_auth.registration.urls")) ] from django.conf.urls.static import static from django.conf import settings if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's my test.py file import json from django.contrib.auth.models import User from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from rest_framework import status from profiles.models import Profile from profiles.api.serializers import ProfileSerializer class RegistrationTestCase(APITestCase): def test_registration(self): data = {"username": "testuser1", "email": "test@localhost.app", "password1": "A41&14all", "password2": "A41@14all"} response = self.client.post("/api/rest-auth/registration/", data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) It appears that the line self.client.post.... fails to find the endpoint. What am I missing? thanks! -
How to deploy dockerized app to a server using CircleCI
Trying to dockerize my Django REST API app which uses a postgres db, as well as integrating CI/CD. I have spent all day watching videos, reading tutorials, etc and am still a bit confused but feel like I am getting close. The docker-compose.yml file works using docker-compose up: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres server: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - db I also can push my code to github and CircleCI will run my automated tests: version: 2.1 orbs: python: circleci/python@1.2 workflows: main: jobs: - build-and-test - deploy jobs: build-and-test: docker: - image: cimg/python:3.8 - image: circleci/postgres:9.6.2-alpine environment: POSTGRES_USER: example POSTGRES_PASSWORD: example POSTGRES_DB: example steps: - checkout - python/install-packages: pkg-manager: pip - run: sudo chown -R circleci:circleci /usr/local/bin - restore_cache: key: deps9-{{ .Branch }}-{{ checksum "requirements.txt" }} - run: name: Install Dependencies command: | pip install --user -r requirements.txt - save_cache: key: deps9-{{ .Branch }}-{{ checksum "requirements.txt" }} paths: - ".venv" - "/usr/local/bin" - "/usr/local/lib/python3.6/site-packages" - run: name: Run tests command: python manage.py test - store_test_results: path: test-results - store_artifacts: path: test-results destination: tr1 deploy: docker: - image: circleci/python:3.7.3 working_directory: … -
Django ckeditor Dynamic, Different, image upload path
I have two apps and models, news and blogs Both using ckeditor and ckeditor_uploader, I want whenever I upload from "addblogpost" , The images go to uploads/blog and whenever I upload from "addnewspost", The images go to uploads/news I searched the web seen this question being asked years ago with no clear answers and I tried to modify it from the views.py in ckeditor_uploader folder The idea being to get current url, If "blog" in url, add "blog/" to settings.CKEDITOR_UPLOAD_PATH, Same with news, But the current url from ckeditor_uploader/views.py is "ckeditor/upload" even though clearly the url on the browser bar says "blog/addblogpost" It doesn't have to be from the url, Any other ways to achieve this I'm all in -
django PWA serviceworker Failed to execute 'addAll' on 'Cache': Request failed
Uncaught (in promise) TypeError: Failed to execute 'addAll' on 'Cache': Request failed serviceworker.js:1 Above is the error from my dev tools console upon launching a django progressive web app. Below is my full serviceworker.js file var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/index', ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('/index')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); I tried keeping cache.addAll empty but I still get the same error. I have not put in any offline support because I do not intend to use the app offline. I want to fix this but these posts were not helpful Uncaught (in promise) TypeError: Failed to execute 'Cache' on 'addAll': Request failed on progressive web app and Django - ServiceWorker, Uncaught (in promise) TypeError: Failed to execute 'addAll' on 'Cache': Request failed -
How do I create link for details in each post
I am doing a project in which I display the listing of all the major dealerships in your region but also allows the user to sell their car independently. I am working on the user selling it independently part and I am stuck in one thing. As of right now, the user can create a post and it will display it in the website, along the post there is also a "View" button in which shows the detail of the car such as mileage, contact, date published etc. The problem is that I don't know how to make each post to have its own view page. How do I make each post have its own detail page? That's my code as of right now: views.py from django.shortcuts import render from .models import * from django.http import HttpResponse def home(request): context = {} return render(request, 'store/home.html', context) def store(request): context = {} return render(request, 'store/store.html', context) def cart(request): context = {} return render(request, 'store/cart.html', context) def checkout(request): context = {} return render(request, 'store/checkout.html', context) def posts(request): cars = Userpost.objects.all() context = {'cars':cars} return render(request, 'store/userposts.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name … -
How to add crispy forms to bootstrap4 in Django?
I'm having a trouble to combine bootstrap upload form with django form (crispy forms). Any idea how to put crispy forms to bootstrap form. This is django crispy forms <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Upload and Download!</button> </form> This is bootstrap form where I want to put crispy form. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <div class="custom-file"> <input type="file" class="custom-file-input" id="customFile"> <label class="custom-file-label" for="customFile">Choose file</label> </div> Any idea how to combine these two? -
Making changes to django PWA
I had a all good working website in django and I was running that at http://127.0.0.1:8000/ with python manage.py runserver command. Then, I followed all steps at https://www.geeksforgeeks.org/make-pwa-of-a-django-project/ link, used their serviceworker.js as is and converted my website to a PWA. The issue is for the first time , the app loaded, I refreshed the page, the app loaded again. Since after, the app does not load but the code of serviceworker.js is shown on my screen every time I run server. What is going wrong? Here is the screenshot of the render: -
Websocket TOKEN Authentication in Django Channels (front end Flutter)
I am implementing websocket usage with my flutter app. in the back end, I have regular Django rest framework token auth for my http requests. What are some ways to authenticate the websocket and what are best practices (security wise) for production? I know I have to possibly write a middleware to address authenticating the websocket. as per: How to access user infos from consumer.py django? Is it secure to do it in that manner in which I send my token from the url???: ws://localhost:8000/<route>/?**token=<token_of_the_user**> Another way I came across was that you can send the token as the first message after you connect? any guidance would be appreciated, thanks in advance! -
apollo client subscription pass JWT token handled by DjangoChannelsGraphqlWs on the server side
I use Graphql subscriptions with Apollo client on a Vue3 app using DjangoChannelsGraphqlWs and DjangoGraphqlJWT packages in my backend app. I'm trying to pass the JWT token in the subscription, but the user on the Django app is always anonymous (it means it does not get the token). However, when I'm using the GraphiQL interface, it does catch the token. It seems to me I'm doing something wrong on the client-side. Note that on queries and mutations the JWT token is passed with the key "authorization", and works as intended on the Django app. CLIENT SIDE: Note that I succeed at logging the token in the connectionParams. I commented all the key value pair I tried so far (through diverse searches on Stackoverflow and else). import { setContext } from "apollo-link-context"; import { Storage } from "@capacitor/storage"; import { ApolloClient, createHttpLink, InMemoryCache, split, } from "@apollo/client/core"; import { getMainDefinition } from "@apollo/client/utilities"; import { WebSocketLink } from "@apollo/client/link/ws"; const authLink = setContext(async (_: any, { headers }: any) => { const { value: authStr } = await Storage.get({ key: "auth" }); let token; if (authStr) { const auth = JSON.parse(authStr); token = auth.token; } // return the headers to the … -
django-ckeditor {{ form.media }} not working in html
I am trying to get ck-editor look from forms.py . After reading docs and even on YouTube, I didn't get my desired result. I am sharing my different file. Please solve this. HTML FILE <form method="post" enctype="multipart/form-data"> <div class="col me-2"> {% csrf_token %} {{ notes_form.media }} {{ notes_form.as_p }} </div> <div class="col-auto"> <button class="btn btn-outline-success btn-sm border rounded-pill border-success float-end todo-submit" type="button"> <i class="fas fa-check"></i> </button> </div> </form> Form.py class NotesForm(ModelForm): class Meta: model = Notes fields = ['description'] def __init__(self, *args, **kwargs): super(NotesForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs.update({ 'class': 'form-control' }) views.py def index(request): if request.user.is_authenticated: params = { "notes_form": NotesForm() } return render(request, 'dashboard.html', params) else: return render(request, 'home.html') output (html file) output image -
Django run a task at specific time
I am implementing a payment system and I would like to schedule the payment at a specific time. Let's say I want to charge the user 5 days after they place an order. My approach is to schedule a task whenever a user places an order and set it to process the payment after day 5. I am thinking of using celery or APScheduler or Jobs Scheduling or cron.( It will be used on windows) This is not a recurring event but rather a one time thing. Is it the correct approach and are there any better methods available? which one is more appropriate ? -
What is the best way dealing with important information that is fetched by client from Django server
I'm building an API that handles users clicking on submit/delete requests to join a sports club. When a request is created/deleted I need the club's PK in order to find the instance of the club (when the ClubRequest instance is created) or the request (when the request for the specific club is deleted). Model of request class ClubRequest(models.Model): athlete = models.ForeignKey(User, [...]) timestamp = models.DateTimeField(auto_now_add = True) club = models.ForeignKey(Club,[...]) I fetch a list of all instances of the clubs, then create EventListeners that have one of the parameters the PK of the clubs. The client should receive an encrypted PK. for (club in list) { res = list[club]; name = res["name"] id = res["id"] createDivs(requested, id) document.querySelector("#search-name").onclick = null } Function that handles submitting/deleting requests if (new_request == "true") { fetch("createRequest", { method: "POST", body: JSON.stringify({ "id": club_id }) }) .then(response => response.json()) .then(result => { changeIcons(self, new_or_old) self.classList = "button is-info" self.setAttribute("new_or_old", false) }) } else { fetch("undoRequest", { method: "POST", body: JSON.stringify({ "id": club_id }) }) .then(response => response.json()) .then(result => { changeIcons(self, new_or_old) self.classList = "button is-primary" self.setAttribute("new_or_old", true) }) } Should I use a public/private key system or is there a better way to do … -
Django - 'An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.' on very simple test
I'm running Django 3.2.9 with postgres. I have a very simple test below which generates a few data from a list as you can see the except is being caused by GoalCategory.objects.create(name=goal_name, emoji='url'). I see there are some solutions posted here: TransactionManagementError "You can't execute queries until the end of the 'atomic' block" while using signals, but only during Unit Testing An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block My test as you can see is very very simple and the solution is to wrap the create in a transaction.atomic that seems kind of unnecessary given how simple my test data generation is. Is there a better solution to this? I don't like wrapping it in a try and except, because then the data I expect the test to generate might not be generated, it might just skip because it's caught by the try except. Another solution suggested was to change TestCase to TransactionTestCase, which did solve the issue, but you can't set self with TransactionTestCase as you can see I set a access_token variable. This attribute gets removed from self when I get to test_search_categories. So the error I'm … -
How to display different Charfields into one sentence?
I'm doing a Django project that it is basically an ecommerce but for cars. My model is the following: class Userpost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length = 500) Year = models.CharField(max_length = 4) Mileage = models.CharField(max_length = 8) Make = models.CharField(max_length = 50) Model = models.CharField(max_length = 50) Price = models.DecimalField(max_digits=15, decimal_places=2) email = models.EmailField() date_published = models.DateField(default = timezone.now) and my template is the following: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> {% for car in cars %} <div class="col-lg-4"> <img class="thumbnail" src="{% static 'images/placeholder.png' %}"> <div class="box-element product"> <h6><strong>{{car.title}}</strong></h6> <hr> <button class="btn btn-outline-secondary add-btn">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 style="display: inline-block; float: right"> <strong>${{car.Price|floatformat:2}}</strong></h4> </div> </div> {% endfor %} </div> {% endblock content %} I was wondering if there is a way that i could remove the title from my model and instead of displaying {{car.title}}, I would display something like {{car.Year + car.Make + car.Model}}