Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The 'video' attribute has no file associated with it. while uploading events videos and image in django
i tried to upload events videos and images but it does not work after when i leave one filed blank but also there is null=True , blank=True , default=None, in both ImageField and FileField can anyone help me to point out error ?? models.py class Events(models.Model): date = models.DateField(("Date"), default=date.today ,help_text='events date') Image = models.ImageField(upload_to = 'static/img/eventimg',null=True,blank=True default=None) video = models.FileField(upload_to='static/img/video' , default=None,null=True,blank=True , verbose_name = 'Video'') views.py def event_view(request): ev=Events.objects.all() return render(request,'event.html' , {'ev':ev } event.html {% for s in ev %} {% if s.Image %} <img style='max-height:20rem;' src="{{s.Image.url}}" > {% else %} <span>-</span> {% endif %} {% if s.video %} <video class='embed-responsive embed-responsive-16by9' controls="controls" controls > <source class="embed-responsive-item" src="{{s.video.url}}" name='video' type="video/mp4"></video> {% else %} {% else %} <span>-</span> It work when i just add single time but after more it show the error The 'video' attribute has no file associated with it. -
Open WebSocket stream(s) based on content of Django page
First off, I'm very open to hearing design decision fixes if I'm just doing this wrong. Setup: Django-based stock market app with Celery using a redis broker. I'm pulling live data from alpaca.markets API. I also have a Python-based background service running that kicks off asynchronous tasks based on various events. Overall dream: I want to open a websocket stream of live data for each symbol that shows up on a page. I want to have my background service kick off that live feed so it can return it to the page but also compare it to algorithms on the backend. Current (failing) design: When a page loads, Django will successfully kick off a Celery task that returns what stocks show up on that page. I can look at the data in Admin under django_celery_results/taskresult/ and in the DB under result of the django_celery_results_taskresult table. I can't get my service to see the new task and the corresponding symbols returned. Other information: I have ASGI with daphne set up and working I have successfully displayed live data on a page My background service is asynchronous I can see the raw data when I follow the accepted answer here: How can … -
django.template.exceptions.TemplateDoesNotExist: customer/base.html
My customers urls.py ''' urlpatterns = [ path('', views.base ,name= 'customer-base'), path('Hall/', views.Hall ,name= 'customer-Hall'), path('Food_item/', views.Food_item ,name= 'customer-food'), path('About_us/', views.About_us ,name= 'customer-about'), ] ''' My Web_project urls.py ''' urlpatterns = [ path('admin/', admin.site.urls), path('', include('customer.urls')), ] ''' My views.py ''' def base(request): return render(request, "customer/base.html", {"title":"base"}) def Hall(request): return render(request, "customer/Hall.html", {"title":"Hall"}) def Food_item(request): return render(request, "customer/Food_item.html", {"title":"Food"}) def About_us(request): return render(request, "customer/About_us.html", {"title":"About"}) ''' I have tried everything but did not work for me. -
Remote host forcibly terminated existing connection
I'm trying to send an actual email to myself from my website using send_mail. I had used localhost and the following cmd command, python -m smtpd -n -c DebuggingServer localhost:1025 in order to test it. It intercepts with no problem, but I don't see anything in my inbox. My email provider works with SSL, so I turned it to True and enabled 'access to the mailbox using mail clients' in my mail settings. Here is the settings.py file: EMAIL_HOST = '178.68.164.41' # My current ip address EMAIL_PORT = '465' # Port of the email host EMAIL_HOST_USER = 's...6@rambler.ru' # Here is my actual email EMAIL_HOST_PASSWORD = '.....' # Here is my actual password from my email login EMAIL_USE_TLS = False EMAIL_USE_SSL = True Here is the views.py file: from django.shortcuts import render from django.core.mail import send_mail from .forms import ContactForm def contact(request): form = ContactForm if request.method == 'POST': message_name = request.POST.get('name') message_email = request.POST.get('email') message = request.POST.get('message') send_mail(message_name, message, message_email, ['s****6@rambler.ru']) return render(request, 'contact.html', {'form': form}) Here's the exception: Internal Server Error: /contact/ Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
do the same thing with diffrent urls
I'm totally new in Django. I want to do the same thing when the user type "student/" or "student/en" or "student/ttttttttttttt" in the URL. I want to handle if the user type "student/en" the whole page translate to English or if it was "student/de" it translated to german. if it was "student/" it translate to dutch(default). just it is important for me to get "en" or "de" or none from the end of its URL. thanks for helping -
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 …