Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i use FileResponse.set_headers() in my django application to enable .mp3 file download
I am trying to use FileResponse.set_header() to set Content-Disposition to attachment, so that Audio file can be downloaded rather than playing on the browser, in my python/django powered website. is there any way i can implement this code bellow to make it work? song = models.song.objects.filter(id__exact=song_id).first() file_name = ntpath.basename(song.songfile.url) content_type = 'audio/mpeg' with open(identify_song.songfile.path, 'rb') as my_f: file_like = my_f response = FileResponse(my_f, content_type=content_type, as_attachment=True, filename="{}".format(file_name)) response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name) size = response['Content-Length'] = os.path.getsize(identify_song.songfile.path) #print(file_name) return(response) this code does not give me any error but it's not working. So i discovered about FileResponse.set_header() in the django doc, so i tried using it like so. `song = models.song.objects.filter(id__exact=song_id).first() file_name = ntpath.basename(song.songfile.url) FileResponse.set_headers(file_name, filelike='audio/mpeg', as_attachment=True)` Then i got an error AttributeError: 'str' object has no attribute 'filename'. please can anyone help me out, or if there is another way to do that in django i will so much appreciate someone's help. Or any other possible way i can set my Content-Disposition, in django, Nginx or in Javascript. -
Why is my Django app not pushing to Heroku?
I am having trouble pushing my app to Heroku. I have upgraded psycopg2 already and that did not resolve this issue. Can anyone help me get this error fixed? Error: could not determine PostgreSQL version from '12.3' When I try to push my Django app onto Heroku it's trying to collect and then download psycopg2==2.6.2 and while downloading it errors out with this error: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-8hdlm266/psycopg2/setup.py'"'"'; file='"'"'/tmp/pip-install-8hdlm266/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-8hdlm266/psycopg2/pip-egg-info remote: cwd: /tmp/pip-install-8hdlm266/psycopg2/ -
How do I make a button to run code in Django?
I've been only recently venturing in the programming realm, and I'm attempting a website with Django. Now in this website there's this button "choose movie", and I would like this button when pressed to activate a code to randomly choose movie from a list. Now the tag seems to do nothing and it says it works with some form class but I don't want a form submission. And the tag will just redirect to another page, but I want the code to run within the same one. Anyone knows what to do? Thanks in advance. -
How can I remove tables that are created from an implicit model within an app in Django
I have installed an app called django-ads via "https://pypi.org/project/django-ads/" to my Django application. I have followed the guidelines : pip install django-ads python manage.py migrate ads This has created tables in my database as following : Ad Clicks Ad Impressions Ads Advertisers Categories Now, I don't have explicit access to the "models.py" for the django-apps, so I cannot do another makemigrations and delete the tables. Obviously when I remove the app, the tables still stay there. For the time being, what shall I do to remove those tables ? -
Fatal error when running django-admin, The system cannot find the file specified
enter image description hereI installed python3 and then installed Django. When I try to run django-admin I get a fatal error and it says it cant find the file specified "django-admin.exe". However when I navigate to that file location, the file is there. Here are the screen shots. enter image description hereenter image description here -
Django : Add JSON POST data into the database
I'm trying to make an API for a butcher. With this API and the website that I will build by the next, the client will be able to make his order remotly. Here is my probleme. With the order form, the client send me JSON data like here : { "user": 8, "orderDay": "2020-06-24", "deliveryDay": "2020-06-30", "deliveryAddress": "Place des Fêtes", "comment": "", "orderDetail": [ { "product": 2, "byProduct": 2, "quantity": 43 }, { "product": 3, "byProduct": 3, "quantity": 5 } ] } These data must be saved in the database. These are the models that I use : models.py class order(models.Model): user = models.ForeignKey(memberArea, on_delete=models.CASCADE) comment = models.TextField(null=True, blank=True) orderDay = models.DateTimeField(auto_now_add=True) deliveryDay = models.DateField() deliveryAddress = models.CharField(max_length=255) state = models.CharField(max_length=255) price = models.TextField(null=True, blank=True) response = models.TextField(null=True, blank=True) class orderDetail(models.Model): order = models.ForeignKey(order, on_delete=models.CASCADE) product = models.ForeignKey(product, on_delete=models.CASCADE) byProduct = models.ForeignKey(byProduct, on_delete=models.CASCADE) quantity = models.CharField(max_length=255) class product(models.Model): name = models.CharField(max_length=255) prix_uni = models.TextField(null=True, blank=True) prix_kg = models.TextField(null=True, blank=True) dispo = models.BooleanField(null=True, blank=True) category = models.ForeignKey(category, on_delete=models.CASCADE) redu = models.TextField(null=True, blank=True) class byProduct(models.Model): product = models.ForeignKey(product, on_delete = models.CASCADE) name = models.CharField(max_length=255) I make a serializer file like this serializer.py class orderDetailSerializer(serializers.ModelSerializer): order = serializers.PrimaryKeyRelatedField(many=False, queryset = order.objects.all()) class Meta: … -
OpenCV , Django for video
I was able to work with Django/OpenCV/python which works from the windows machine without any problem. My question is generic. I use the below code for video capture output which comes up in a window based on the size I define. My idea is to build a Progressive web app. I am trying to understand is there a way to realign the code which sets the window to display the video stream according to the size of the device. ex. if I access the website via mobile I want to adjust the video stream window accordingly. any help/pointers/alternatives is much appreciated import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() -
access django website hosted on home server from external IP - CONNECTION TIMEOUT
I am working on a django project which I was able to access from an external network. But this has recently stopped working. I have tried troubleshooting the problem but I can't seem to figure out the issue. Below are the steps I followed: Public IP: 86.40.54.24 Private IP: 192.168.1.18 OS: Ubuntu 20.04 Router: EIR Network default router. Allows the required changes to forward requests add routing rule in the router Allow connections from any IP on port 80 to 192.168.1.18 on port 12987 setup rules in ufw to allow connections ufw allow proto tcp from any to 192.168.1.18 port 12987 settings.py file ALLOWED_HOSTS ["*"] run django development server python3 manage.py runserver 0.0.0.0:12987 Note: An approach (similar to above) had worked for me and I was able to access my website from an external IP. But it suddenly stopped working. I have not been able to identify the problem. I have kept the restrictions to bare minimum to be able to get this working once again. I will harden the server after the issue is identified and fixed. -
Django Change Admin Logout To POST Instead Of GET
Django's admin interface uses GET requests to logout the users. This is convenient but the server does not see that the user has logged out. The server will see it if there is a POST request. How do you change the admin logout request to use POST? -
Django forms submit to Admin
I have a Django blog, and I was thinking about making a kind of survey about how the posts are. I am very new to Django, and I have no idea how to make a model, or anything like that. I would like the answers to the survey be submitted to the admin site. Please help!! -
Username in URL for Django DeleteUser
I want to use username in django url how i use can you tell me i am not using yet that time i used occure page not found error. In my template template.html <a href="/accounts/{{ user.username }}/delete/">Delete</a> In my urls urls.py path('<str:username>/delete/', views.delete_user, name='delete_user'), In my views views.py def delete_user(request, username): context = {} u = User.objects.filter(username=username) u.delete() messages.success(request,'your account delete') return redirect('home') -
Value error : Field 'id' expected a number but got 'create' while loading the form using CBV
I am creating a simple form that takes in basic info of school. I created it using 'CreateView' CBV but when I hit the URL , I get the value error: Value error : Field 'id' expected a number but got 'create'. error page Model.py: from django.db import models class School(models.Model): name=models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__ (self): return self.name def get_absolute_url(self): return reverse("basic_app:detail",kwargs={'pk':self.pk}) class Student(models.Model): name=models.CharField(max_length=256) age=models.PositiveIntegerField() school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE) def __str__(self): return self.name Views.py from django.views.generic import View,CreateView from . import models class SchoolCreateView(CreateView): fields=["name","principal","location"] model=models.School urls.py: from django.urls import path from basic_app import views app_name= 'basic_app' urlpatterns=[ path('create/',views.SchoolCreateView.as_view(),name='create') ] school_form.html: {% block body_block %} <h1> {% if not form.instance.pk %} Create school: {% else %} Update school: {% endif %} </h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class = "btn btn-primary" value="Submit"> </form> {% endblock %} Note: The url works if I replace the url path like 'create/school' (anything added after 'create/) path('create/school',views.SchoolCreateView.as_view(),name='create') then the page gets loaded. I could not figure out the issue , can anyone point out the mistake with previous URL path. -
AWS EBS django not able to deploy with migration error
I have Django app and able to deploy. Its always saying wrong application version please upload with expected version I debugged into it and found out that mysqlclient was not properly being installed. What can be done to install mysql on the ebs since i cant always logged into the instance and install mysql client manullay everytime. -
Allow fields to be valid or non-valid based on DateField ranges
I have a model called products, see below: class Product(models.Model): name = models.CharField(max_length=200, null=True) r_price = models.FloatField(null=True) d_price = models.FloatField(null=True, blank=True, default='') start_date = models.DateField(null=True, blank=True, default='') end_date = models.DateField(null=True, blank=True, default='') The datefields that I have in my model is called start_date and end_date. My intention is that if the current date falls within the range of start_date and end_date, d_price will be valid (submitting values within its form). If the current date is not within the range of start_date and end_date or if the current date surpasses the end date, the r_price field will be valid into taking values to be submitted and d_price will no longer be valid. See below for views based on the model of when creating and updating instances. When creating instances - def NewProductProfile(request): form = CreateProductForm() if request.method == 'POST': form = CreateProductForm(request.POST or None) if form.is_valid(): form.save() return redirect('product_list') return render(request, 'accounts/new_product_profile.html', {'form': form}) When updating instances - def EditProduct(request, pk): product = Product.objects.get(id=pk) form = ProductForm(instance=product) if request.method == 'POST': form = ProductForm(request.POST, instance=product) if form.is_valid(): form.save() return redirect('product_list') return render(request, 'accounts/edit_product_profile.html', {'form': form}) The start_date and end_date fields will be manual inputted by the intended user. How will this … -
Form request is not going through Ajax in Django. request.is_ajax() is always false
I have looked for this solutiona lot but none of the solution helps. i am learning AJAX via Django. In teh following setup, however, the code never enters my Ajax block and the form request is transferred directly thus giving request.is_ajax() always False. .PLEASE PLEASE HELP ME !!! This is my create_post.html <!DOCTYPE html> <html> <head> <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"> </head> <body> <div class="container pt-5"> <form method="POST" id="post-form"> {% csrf_token %} <div class="form-group"> <label>Title</label> <input type="text" class="form-control" id="title" placeholder="Title"> </div> <div class="form-group"> <label>Description</label> <textarea class="form-control" id="description" placeholder="Description"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <div class="row mb-2 posts"> {% for post in posts %} <div class="col-md-6"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <h3 class="mb-0">{{post.title}}</h3> <p class="mb-auto">{{post.description}}</p> </div> </div> </div> {% endfor %} </div> </div> </body> <script src="/static/jquery-2.2.4.min.js"></script> <script src="/static/bootstrap.min.js"></script> <script type="text/javascript"> $.ajaxSetup({ headers: {'X-Requested-With': 'XMLHttpRequest'} }); $(document).on('submit', '#post-form',function(e){ e.preventDefault(); var r = confirm("Are You sure we want to change status ?"); console.log("Its here atleast!!!"); $.ajax({ type:'POST', url:'{% url "create" %}' data:{ title:$('#title').val(), description:$('#description').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success:function(json){ document.getElementById("post-form").reset(); $(".posts").prepend('<div class="col-md-6">'+ '<div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">' + '<div class="col p-4 d-flex flex-column position-static">' … -
Django tutorial 5 testing "response = client.get(reverse('polls:index'))"
I get these errors when I run response = client.get(reverse('polls:index')) https://pastebin.com/wJU0zBZr https://docs.djangoproject.com/en/3.0/intro/tutorial05/ using tutorial What is wrong? -
Django Deployment in AWS Lightsail- static file not loading
I am having a problem with deployment of Django application using AWS lightsail referring to this video https://www.youtube.com/watch?v=ldUo5EcRyGw The static file is not being loaded. The static url and directory in my settings.py are as mentioned below: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') The static folder is in the base directory named as /static/. and the httpd-app.conf file in the conf folder has: Alias /static/ "/opt/bitnami/apps/django/django_projects/Project/static" <Directory opt/bitnami/apps/django/django_projects/Project/static> Require all granted</Directory> Alias /media/ "/opt/bitnami/apps/django/django_projects/Project/media" <Directory opt/bitnami/apps/django/django_projects/Project/media> Require all granted </Directory> I have run python3 manage.py collectstatic command and the static files are loaded in static directory but the site does not load it. -
How would I create a list of people attending an event using Django, Django Rest Framework and mysql
I'd like to add users to an event and be able to see this list of users who have registered to attend the event using django rest framework. I am having trouble creating this with the events and profile models and views I have already created. Any suggestions on how I should edit the the following code to be able to add multiple users to an event and then be able to see the users going to said event would be much appreciated! models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager from django.conf import settings # Create your models here. class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password=None): """create a new user profile""" if not email: raise ValueError('User must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): """Create and save a new superuser with given details""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser, PermissionsMixin): """Database models for users in the system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserProfileManager() … -
Django - How make multiple objects dynamic in the same page
Problem statement: Unable to make multiple elements dynamic in the same index page. Can you suggest me how to do it? I have almost 5 elements to be made dynamic in the same page. I am using the following code urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index_a, name='index'), path('', views.index_b, name = 'lunch') ] views.py from django.shortcuts import render from . models import breakfast, lunch # Create your views here. def index_a(request): brkfstn = breakfast.objects.all() return render(request, "index.html",{'brkfstn':brkfstn}) def index_b(request): lunchn = lunch.objects.all() return render(request, "index.html",{'lunchn':lunchn}) models.py from django.db import models # Create your models here. class breakfast(models.Model): name = models.CharField(max_length=100) ingrdnt = models.TextField() image = models.ImageField(upload_to='images') price = models.IntegerField() discount = models.BooleanField(default=False) offer_price = models.IntegerField() class lunch(models.Model): name = models.CharField(max_length=100) ingrdnt = models.TextField() image = models.ImageField(upload_to='images') price = models.IntegerField() discount = models.BooleanField(default=False) offer_price = models.IntegerField() -
What is the purpose of the UserManager class in django?
What is the purpose of the UserManager class in django? The documentation doesn't seem to really explain what it is for. -
Django succeed when no time conflicts for duration events
I haven't finalized any of my Postgres tables yet. The context is this: a user can sign up for any random event, and the events can last a variable amount of time based on the host's discretion. I want to verify that the user, when signing up for a second event, doesn't conflict with the first signed-up event. The user can sign up for as many events as they want; they just can't conflict. I can't seem to design my database correctly so that this can be done efficiently (and then if I did, I wouldn't know how to compare two records to see if there is a time conflict). A bonus would be to say there must be a 30 minute in-between, but that's not needed for now. -
Any reason why not to place SCSS and JS files in Django Template folder, then compile CSS/JS to static/
Currently I have a project folder structure like this: (In reality it is quite a bit complex, but I think this address the key problem) project/ |----assets/ | |----scss/ # Compiles to static/css/ | |----js/ # Minified to static/js/ | |----static/ | |----css/ | |----js/ | |-----app_a/ | |----templates/ | |----file_a1.html | |----file_a2.html | |----file_a3.html | |-----app_b/ |----templates/ |----file_b1.html |----file_b2.html |----file_b3.html At moment my SCSS files are broken up as follows (not consistent): Some SCSS file code for multiple templates (logically it makes sense for that instance, e.g. a group of widgets) Some embedded code in the templates Some SCSS files that correspond to a single template. I wish to refactor it to clean it up. I read this answer about multiple CSS files that explains the the advantage of one big CSS file is done away with thanks to HTTP2. And actually people recommend splitting files up as it's faster due to concurrency. So I am going to have one CSS file per (django) app. I find the hardest part to deal with is styles and javascript which is only applicable to a single page. (Disclaimer: Yes I use SCSS placeholders and extends, and have a framework in place). … -
How can I filter by date, time and second in django?
In my Database I have lots of entries with various Dates(including time, second). I need to find all the latest entries. So I tried like: arr = balance_sheet.objects.all().values('timestump') date_arr=[] for text in arr: if text.get('timestump'): date_arr.append(text.get('timestump')) if date_arr: latest_date = max(date_arr) else: latest_date = datetime.datetime.now() latest = balance_sheet.objects.filter(timestump__icontains=latest_date) But latest is empty in this case. But If I change the last line to query with only the date, it works fine. latest = balance_sheet.objects.filter(timestump__icontains=latest_date) I need to find all the latest minute:second entries. At latest last minute is entries. Am I doing something wrong? What can I do? -
Page not found 404 How i access username with delete url
Hello i want to access url with username after login but i am after login redirect on userhome then after i want to delete my account so i go to on help template and after i reached on help template then after i go to manage account template and i clicked on delete account then occure its error page not found because i reached delete account template then my username is not available in my url and my url like this http://127.0.0.1:8000/user_homeview/delete/ but i need for delete account username http://127.0.0.1:8000/user_homeview/username/delete/ but i didn't so any one tell me what can i do please tell me urls.py path('<str:username>/delete/', views.delete_user, name='delete_user'), path('help/', views.help ,name='help'), path('manageAccount/', views.manageAccount ,name='manageAccount'), my help template looks like these: help.html <a href="/user_homeview/manageAccount/" class="ml-4">Manage Accounts</a><Br> Delete template looks like these that time i reach this url i want http://127.0.0.1:8000/user_homeview/username/delete but not : delete.html <a href="/user_homeview/delete/" class="ml-4">Delete Accounts</a><Br> -
Wagtail, adding more fields while using AppPageMixin
if I have a Page class like this: class LocationPage(AppPageMixin, Page): template = 'locations/locations_list.html' url_config = 'location.urls' ... It allows me to create pages dynamically off of the LocationPage by entering objects into my Admin Model. It took me forever to get this to work but I got it. The issue that I am having now is that I can't seem to add custom fields to the LocationPage anymore. I just need a banner image, title, and subtitle. The rest of the content comes from a loop through my Admin Model. I did what one would normally do to add fields to a page model: class LocationPage(AppPageMixin, Page): template = 'locations/locations_list.html' url_config = 'location.urls' banner_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=False, on_delete=models.SET_NULL, related_name="+" ) page_title = models.CharField(max_length=200, null=True, blank=False) page_subtitle = models.CharField(max_length=300, null=True, blank=False) panels = [ FieldPanel('page_title'), FieldPanel('page_subtitle'), ImageChooserPanel('banner_image'), ] I migrated, but when I go to my current page using LocationPage, or if I create a new page, the fields do not show. this documentation (https://wagtailmenus.readthedocs.io/en/stable/index.html) does not mention anything about how to do this or if it is possible, but I'd say it's a pretty common requirement. Having to enter static content into the template defeats the purpose …