Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to manage devices on docker-compose automatically?
Here is the docker-compose.yml to map local USB cameras to container on a django web application. In this case, it works if 10 cameras are connected to the local PC, but cause errors if I take out any of them because the container can not map some of the cameras listed up. So for now, I need to comment out them depending on the number of cameras connected to the local. Is there any solutions for this case so that I do not have to comment out like I mentioned above? version: '3' web: build: . devices: # Here is the problem!!! - '/dev/video0:/dev/video0:mwr' - '/dev/video1:/dev/video1:mwr' - '/dev/video2:/dev/video2:mwr' - '/dev/video3:/dev/video3:mwr' - '/dev/video4:/dev/video4:mwr' - '/dev/video5:/dev/video5:mwr' - '/dev/video6:/dev/video6:mwr' - '/dev/video7:/dev/video7:mwr' - '/dev/video8:/dev/video8:mwr' - '/dev/video9:/dev/video9:mwr' ports: - '8000:8000' volumes: - '.:/code' tty: true stdin_open: true command: > bash -c 'python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000' Thank you in advance for my very first question in stack overflow! -
Why doesn’t Heroku add or remove database tables after initial launch for django app
So I punched my Django app on heroku and every thing has been going fine for about 3 weeks now. Now I want to update my models and add more fields but when I do so, it doesn’t seem to update the database. I run the following: heroku run python manage.pu makemigrations and the same for migrate. Every run through fine but the migrations doesn’t really go through although it says the fields have been altered. Anyone know how to update models for django app on heroku after initial launch? -
How can I run Javascript on Django without exposing static files?
On my Django site, I used Stripe to integrate payments in a .js file. I noticed that this file appears under Sources in the developer tools when you "Inspect Element" on any browser. Anyone can access this file (scary). How can I restructure my file organization so that apple-pay.js is not public facing? home.html {% load static %} <!DOCTYPE html> <html> <head> // Scripts for CSS and Stripe Pay </head> <body> <section> <div id="payment-request-button" data-amount="{{event.price}}" data-label=". {{event.public_name}}"> <!-- A Stripe Element will be inserted here if the browser supports this type of payment method. --> </div> <div id="messages" role="alert"></div> </section> </body> </html> apple-pay.js document.addEventListener('DOMContentLoaded', async () => { const stripe = Stripe('pk_mykeyishere'); //need to protect this information and the other functions from bad actors ///functions I run here }); My file structure: ├── Procfile ├── README.md ├── db.sqlite3 ├── interface │ ├── migrations │ ├── models.py │ ├── static │ │ ├── apple-developer-merchantid-domain-association │ │ └── interface │ │ ├── apple-pay.js <------------------ │ │ ├── CSS/other JS files │ ├── templates │ │ └── interface │ │ ├── home.html <------------------- │ ├── urls.py │ └── views.py ├── manage.py └── AppName ├── settings.py ├── urls.py └── wsgi.py -
cannot import name 'force_text' from 'django.utils.encoding'
Things suddenly started breaking when trying to use rest_framework_simplejwt. Now when I run python manage.py runserver I get the following: raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'force_text' from 'django.utils.encoding' (/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/encoding.py) Searching online, I found this post that seemed to work for some. However, when I tried that hack, I get the following exception: raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/db/models/fields/__init__.py) This is my requirements.txt algoliasearch-django>=2.0,<3.0 django>=4.0.0,<4.1.0 djangorestframework djangorestframework-simplejwt pyyaml requests django-cors-headers black isort -
Django SecurityMiddleware and
what is the correct way to configure? settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware' .... ] so that you can pass parameters from one window to another from javascript parent.window.opener.postMessage -
File Size of attachment becoming 0 (compressed) in Python Django email automation i.e. file name appears, no content shows in attached pdf
The code to send email in Django is written like this in views.py file - it sends the pdf fine, if the file size is large (~3mb), but for smaller files (~1 or 2mb) it does not send the file (it appears as a zero byte file) in the email, and hence we cannot access it. The code is as belows - Please let me know if there is a way to avoid such a compression of file and send small files to. def addbeast(request): if request.method == 'POST': form = BeastForm(request.POST, request.FILES) # print("here") # print(form.cleaned_data['name']) if form.is_valid(): # print("here") # print(form.cleaned_data['media']) form.save() # media = Beast.objects.get(name = '') name = form.cleaned_data['name'] media = form.cleaned_data['media'] media.seek(0, os.SEEK_END) filesize = media.tell() print(filesize) subject = "NDA IS Attached" message = "NDA Attachment from " + name sender = "-----@gmail.com" cc_myself = True cc_mail = "----!!!!!!@gmail.com" recipients = ['9999999999@gmail.com'] if cc_myself: recipients.append(cc_mail) try: mail = EmailMessage(subject, message, sender, recipients) mail.attach(media.name, media.read(), media.content_type) mail.send() return HttpResponse("FORM SUBMISSION IS SUCCESSFUL") except: return HttpResponse('no success') else: form = BeastForm() return render(request, "post_list.html", { "form": form }) Please help with how the code can be made right, on printing the variable media, I get 'filename.pdf'. -
While importing the URL file from my app to the main URL file (Django)
#I am trying to import the URL file from my app to the main file# #main url file# from django.contrib import admin from django.urls import path,include from django.http import HttpResponse urlpatterns = [ path('admin/', admin.site.urls), path('',include ('base.links')) ] the error i am getting: cannot import name 'path' from partially initialized module 'base.links' (most likely due to a circular import) (C:\Users\Sam\Desktop\studybudy\base\links.py) #the url file in my app# from base.links import path from . import views urlpatterns = [ path(' ',views.home), path('room',views.room), ] #the views file in my app# from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('home123') def room(request): return HttpResponse('Room') -
Why do I always get a message that there are insufficient money, even though the amount I'm withdrawing is less than my balance?
I intended to show the user the message "insufficient balance" when the amount he wants to withdraw is larger than the available balance, but the message appears even when the amount he wants to withdraw is less. What's the problem here, exactly? def create_withdrawal_view(request): if request.method == 'POST': withdraw_form = InvestmentForm(request.POST) if withdraw_form.is_valid(): investment = withdraw_form.save(commit=False) if investment.amount > investment.balance: messages.success(request, 'insufficient funds') else: investment.balance -= investment.amount investment.save() messages.success(request, 'your Withdrawal is successfull') else: withdraw_form = InvestmentForm() context = {'withdraw_form': withdraw_form} return render(request, 'create-withdrawal.html', context) -
Is there a way to use files uploaded in django in the template?
I have a django model form where I uploaded images for my app. I am just storing them temporarily locally since its not a real project. The Admin looks like this I'm wondering if there is a way to use the images uploaded with each object in the template. I cant find any articles. How can I make a link to what images are associated with what models? -
How to add counter that increments after an object is created in Django?
I am making a simple list website that displays a list of movies I want to watch. So, basically, I use a form to add a movie to my list. Nothing fancy, but I want to display a count variable alongside each movie I add to my list from like 1-10 and I want it to increase/decrease based on if I delete/add a new movie. Where would I need to add this? I have separate views for my addition/deletion of movies (objects) -
Passing variables from HTML to Javascript file that uses addEventListener
I'm using Stripe to accept Apple pay payments (not super important here). I'm using Django. The code works fine for processing the payments, but I'm having trouble passing in a variable to my separate .js file. (amount to charge) from my HTML file to the Javascript file that actually processes the payments. home.html {% load static %} <!DOCTYPE html> <html> <head> import more scripts here <script src="https://js.stripe.com/v3/"></script> <script src="{% static 'interface/utils.js' %}" defer></script> <script src="{% static 'interface/apple-pay.js' %}" defer></script> </head> <body> <header class="text-center"> <div id="rectangle"></div> </header> <section> <div class="text-center"> <div class="container container--narrow"> <script>amount=parseInt("{{event.price}}")</script> <div id="payment-request-button"> <!-- A Stripe Element will be inserted here if the browser supports this type of payment method. --> </div> </div> </div> </section> </body> </html> The Javascript file that gets called to process the payment: apple-pay.js document.addEventListener('DOMContentLoaded', async () => { const stripe = Stripe('pk_test_testkey'); const paymentRequest = stripe.paymentRequest() ({ currency: 'usd', country: 'US', requestPayerName: true, requestPayerEmail: true, total: { label: 'Test payment', amount: amount, //trying to pass the variable in here } }); // Other functions that get called go here }); The error I see in the console is that 'total' in the API call is no longer an object. Console.log(typeof amount) returns a … -
I get an error TypeError at /brand/5 get() missing 2 required positional arguments: 'self' and 'request'
Everything worked well until I made a brand details page for my online store. I never encountered this error, and it looks like there is no solution availble for my case. I think its unique for every developer. TypeError at /brand/5 get() missing 2 required positional arguments: 'self' and 'request' Here is my code: views.py from django.shortcuts import render, get_object_or_404 from .models import Product,ProductCategory, Brand # Create your views here. from django.views import generic class Brands(generic.ListView): model = Brand template_name = 'productcatalog/brands.html' def get_context_data(self, **kwargs): context = super(Brand, self).get_context_data(**kwargs) brands = Brand.objects.all() context['brands']=brands return context class Brand(generic.DetailView): model = Brand tempal_name = 'productcatalog/brand_details.html' def get_context_data(self, **kwargs): context = super(Brand, self).get_context_data(**kwargs) brand = get_object_or_404(Brand, id=self.kwargs['pk']) context['brand']=brand return context models.py class Brand(models.Model): name = models.CharField(max_length=300,blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_catalog') Can anyone assist? Thank you in advance! -
How and Where to put 10GB of content for a website?
I am making a Django website for our college's debating society. They have approx. 30GB worth of video content. Where should I store it in Database (PostgreSQL is being used) during development and when in production. Does it cost to have a certain amount of GB content when in production? If there is another way for the same, please feel free to share that as well! -
Django 4.0.5: How to properly link static files into templates
I'm following the CS50W course, and I noticed a weird behavior when going through the Django lecture. In summary, I was getting a 404 error when loading the styles.css file on one of the apps. After checking the lecture source code, the main difference was that the lecture used the following to define STATIC_URL: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = '/static/' And noticed that even Django's documentation defines STATIC_URL as STATIC_URL = 'static/', and somehow, adding that slash at the beginning fixes the 404 issues. Could someone explain to me why that is? For reference, this is the project structure I have (the issue is within the app called newyear): . ├── db.sqlite3 ├── manage.py ├── myapp │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── templates │ │ └── myapp │ │ ├── greet.html │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── … -
Django - API links shown as serializers instead
My API looks something liks this { "id": 7, "url": "http://127.0.0.1:8000/workers/7/", "first_name": "ellie", "last_name": "hodjayev", "email": "zenmyx@gmail.com", "phone_number": 502461700, "hire_date": "2022-06-18", "job": 1, "speciality": 5, "salary": 17000, "commission_pct": 0, "manager_id": 0, "department_id": 0 } 'job' and 'speciality' should be shown as links since they're configured to be serializers.hyperlinkedmodeserializers but instead we're seeing a serial number.. from here it looks everything is configured correctly. serialize.py from rest_framework import serializers from .models import Worker, Speciality, Job class WorkerSerializer(serializers.ModelSerializer): class Meta: model = Worker fields = ['id', 'url', 'first_name', 'last_name', 'email', 'phone_number', 'hire_date', 'job', 'speciality', 'salary', 'commission_pct', 'manager_id', 'department_id'] class SpecialitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Speciality fields = ['id', 'url', 'speciality'] class JobSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Job fields = ['id', 'url', 'job'] -
Como puedo poner mi moneda local en Django?
Tengo un problema con un proyecto , con un amigo sacamos codigo de otros proyectos y resulta que el formato de moneda es el de la india , alguien sabe como cambiar el tipo de moneda por otra? el problema -
Problem with permutations function in Django, how to make it work?
Hi i have problem with large amount of data while doing permutations teamA = [tournament.p1, tournament.p2, tournament.p3] teamB = [player.op1, player.op2, player.op3] for perm in permutations(teamA): result.append(list(zip(perm, teamB))) for pairing in result: score = [] total = 0 for i in pairing: if i == (tournament.p1, player.op1): i = player.p11 elif i == (tournament.p1, player.op2): i = player.p12 elif i == (tournament.p1, player.op3): i = player.p13 elif i == (tournament.p2, player.op1): i = player.p21 elif i == (tournament.p2, player.op2): i = player.p22 elif i == (tournament.p2, player.op3): i = player.p23 elif i == (tournament.p3, player.op1): i = player.p31 elif i == (tournament.p3, player.op2): i = player.p32 elif i == (tournament.p3, player.op3): i = player.p33 points.append(i) for s in points: if s == -3: mp = 1 elif s == -2: mp = 4 elif s == -1: mp = 7 elif s == 1: mp = 13 elif s == 2: mp = 16 elif s == 3: mp = 19 else: mp = 10 score.append(mp) total += mp data_list.append([pairing, score, total]) This is code i run for sets od pairs in teams of 3, but if i want to do teams of 8, and permutations of 8 where teamA … -
Django search returning Exception Value: object of type 'method' has no len()
Pretty new to Django Rest Framework and I'm not quite sure how to debug this error at the moment. When I set a breakpoint in the view search view. I see all my products in results <bound method QuerySet.distinct of <ProductQuerySet [<Product: Product object (4)>, <Product: Product object (8)>, <Product: Product object (9)>, <Product: Product object (10)>]>> Pagination is set in settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "api.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticatedOrReadOnly", # GET for everyone, all other calls need to be authenticated ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10, } Search view from rest_framework import generics from products.models import Product from products.serializers import ProductSerializer class SearchListView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) q = self.request.GET.get("q") results = Product.objects.none() if q is not None: user = None if self.request.user.is_authenticated: user = self.request.user results = qs.search(q, user=user) return results Products view from rest_framework import generics, mixins from django.shortcuts import get_object_or_404 from api.mixins import StaffEditorPermissionMixin, UserQuerySetMixin from .models import Product from .serializers import ProductSerializer class ProductListCreateAPIView( UserQuerySetMixin, StaffEditorPermissionMixin, generics.ListCreateAPIView ): queryset = Product.objects.all() serializer_class = ProductSerializer def perform_create(self, serializer): title = serializer.validated_data.get("title") content = serializer.validated_data.get("content") or None if content is None: content = title serializer.save(user=self.request.user, … -
How can I create the associated OneToOne Field in Django automatically?
I have tried Django Annoying as mentioned in this answer Create OneToOne instance on model creation But I still get NOT NULL CONSTRAINT FAILED on the OneToOne Field when creating my object, which I suppose means that the associated object is not created, hence NULL If I use A signal Handler, that will be activated every time the Model's save method will be called. I will end up creating a new Object even when updating the Parent object. My Profile structure is as follows: { "id": 3, "password": "pbkdf2_sha256$320000$5TQCdD5wIelYpO4ktpuuAk$oBC9xUT+8RjOxZHvE8C+eowS4PvdCT8vUAuS4Y2n7sM=", "last_login": null, "is_superuser": false, "username": "hamad", "first_name": "", "last_name": "alahmed", "email": "", "is_staff": false, "is_active": true, "date_joined": "2022-06-17T13:04:51.927199Z", "height": null, "weight": null, "createddate": "2022-06-17T13:04:52.362396Z", "date": null, "hobbies": null, "dailyRoutine": { "id": 8, "steps": 0, "diet": "No Specified Diet", "maintained": 0 }, "groups": [], "user_permissions": [], "friends": [ { "id": 1, "password": "pbkdf2_sha256$320000$YRcHWSjLi1CMbfrolZ0W7W$9LgjH2m5c8emE66pjdExmgep47BAdKTrCJ7MBiJx74w=", "last_login": "2022-06-17T17:50:48.410366Z", "is_superuser": true, "username": "super", "first_name": "Super1", "last_name": "Admin1", "email": "super@gmail.com", "is_staff": true, "is_active": true, "date_joined": "2022-06-17T12:27:37.575631Z", "height": 160, "weight": 75, "createddate": "2022-06-17T12:27:37.789754Z", "date": null, "hobbies": "Football", "dailyRoutine": 10, "groups": [], "user_permissions": [], "friends": [ 2, 3 ] } ] } The Object that I want to create automatically is DailyRoutine The Routine code: class Routine(models.Model): steps = … -
AttributeError: module 'colorama' has no attribute 'init'
i have python version 3.8 and trying to deploy django model to Apache2 server and getting this error. anybody can help me to resolve this? -
no such column: Blog_post.category_id
I’m trying to create a category for each post. I made another class with the same models.py and in the same class Post I made a category = models.ForeignKey But it keeps showing me this error when I run the server: (no such column: Blog_post.category_id) Ps: I did run the makemigrations and the migrate command. The tutorial I followed just added the model as it is in models.py but should I also make a function for the views.py or its just a model problem ? models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, default="Some random thing") -
Django : change the id with another field in the views page
my question is: How do I tell to Django to replace the Column type_id to the name field in the views (html page). and here I have foreignkey, it gave me id (type_id), and this screentshot of fabrication class: the column type_id is comming from the composant_type class, models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.base import Model from CentreCout.models import CentreCoutDB class fiche(models.Model): centre_cout = models.CharField(max_length=150) number = models.CharField(max_length=100) name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class unite(models.Model): name = models.CharField(max_length= 150, unique=True) def __str__(self): return self.name class composant_type(models.Model): name = models.CharField(max_length=150, unique=True ) def __str__(self): return f"({self.name})" class composant_fab(models.Model): type = models.ForeignKey(composant_type, to_field='name', on_delete=models.CASCADE) name = models.CharField(max_length=150, unique=True) def __str__(self): return f"({self.name})" class fabrication(models.Model): grade = models.ForeignKey(fiche, to_field='name',on_delete=models.CASCADE) type = models.ForeignKey(composant_type, on_delete=models.CASCADE, blank=True, null=True) composant = models.ForeignKey(composant_fab , to_field='name', on_delete=models.CASCADE, null=True, blank=True) unite = models.ForeignKey(unite, to_field='name',on_delete=models.CASCADE) composant_value = models.FloatField(blank=True, null=True) def __str__(self): return f"({self.grade}-{self.composant}-{self.composant_value}-{self.unite})" views.py from django.shortcuts import render from django import views from django.http import HttpResponse from .models import * import pandas as pd def fabrications(request): lesfichestab = fiche.objects.all() fabricationtab = fabrication.objects.all().values() df = pd.DataFrame(fabricationtab) context = { 'lesfichestab':lesfichestab, 'fabricationtab':df.to_html() } return render(request,'fabrications/fabricationpage.html', context) note : I use Pandas method, because i have … -
showcasing one attribut of multiple instances from a model django/python
i basically have 2 models with multiple attributes, i would like to showcase a specific attribute which has multiple instances, in another model basically : class Carnet(models.Model): ....multiple attributes class Consultation(models.Model): .... date_cons = models.DateTimeField(default=datetime.now, blank=True) There are multiple instances of date_cons, i would like to showcase the latest one added in an html code the view method i used was this ( probably here is the problem ) def consultation(request, carnet_id): consultation = Consultation.objects.all() context = { 'consultation' : consultation } return render(request, 'carnets/carnet.html',context) tried showcasing that attribute in an html code using this syntaxe {{consultation.date_cons}} but it doesn't showcase anything my question is probably all over the place i'm not very good at computer science nor english, i ask for your help -
Django: pass request and response as view parameters
I have a view which takes two parameters (request, response). But when this view is called i get an error which saying - "figure() missing 1 required positional argument: 'response' " views.py: def figure(request, response): print("request ->", request) figures = add_data_to_class(request) figures_dict = [] for figure in figures: figures_dict.append({ "date":figure.date, "price_new":figure.price_new, "price_used":figure.price_used, }) print(figures_dict) context = {"figures":figures_dict} return render(response, "app1/figure_data_page.html", context, RequestContext(request)) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.figure, name="figure") ] figure_data.html <form action="main\app1\views.py" method="post" id="figure_choice_form"> <label for="id">Enter ID</label> <input type="text" id="id"> </form> -
How to make a select field using Django model forms (using set values)?
I recently switched from using simple forms in Django to model forms. I am now trying to use a select field in my form that has set field names (eg:Europe,North America,South America...) I thought I would just add a select input type to the for fields but it shows up as just a regular text input. The select field is supposed to be "continent". Does anyone know how to to d this?? class TripForm(forms.ModelForm): # city = forms.TextInput() # country = forms.TimeField() # description = forms.Textarea() # photo = forms.ImageField() class Meta: model = Trip fields = ('city', 'country', 'continent', 'description', 'photo') widget = { 'city': forms.TextInput(attrs={'class': 'form-control'}), 'country': forms.TextInput(attrs ={'class': 'form-control'}), 'continent': forms.SelectMultiple(attrs= {'class':'form-control'}), 'description': forms.TextInput(attrs = {'class': 'form-control'}), # 'photo': forms.ImageField(attrs = {'class': 'form-control'}), } [![enter image description here][1]][1] This is the form continent should show as a select.