Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
html template is alright , but redirecting on the payments page is not working ... don't know why
`from django.shortcuts import render, redirect, HttpResponse from carts.models import CartItem from .forms import OrderForm import datetime from .models import Order Create your views here. def payments(request): return render(request, 'orders/payments.html') def place_order(request, total=0, quantity=0,): current_user = request.user cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('storx') delivery_charge = 40 grand_total = 0 tax = 0 for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity tax = (2 * total)/100 grand_total = total + tax + delivery_charge if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] data.zipcode = form.cleaned_data['zipcode'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax = tax data.delivery_charge = delivery_charge data.ip = request.META.get('REMOTE_ADDR') data.save() yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr,mt,dt) current_date = d.strftime("%Y%m%d") # 20230214 order_number = current_date + str(data.id) data.order_number = order_number data.save() order = Order.objects.get(user=current_user, is_ordered=False, order_number=order_number) context = { 'order': order, 'cart_items': cart_items, 'total': total, 'tax': tax, 'delivery_charge': delivery_charge, 'grand_total': grand_total, } return redirect('checkout') else: return redirect('checkout') return render(request, 'orders/payments.html', context) ` -
JWT always returns tokens of the superuser django, although normal user credentials are used
In my django application I have created two users a superuser and a normal one , the problem is that I always get the tokens of the superuser account even when I use the normal account credentials. I tried deleting the superuser and log in with the normal user account, I got a response saying no active user with credentials provided. Thank you , any help would be much appreciate -
Using autocomplete.ModelSelect2 with htmx functionality
I have a form in Django. Then, however, I tried to add autocomplete functionality. The search bar/autocomplete itself works, but the hx-get never fires the courses/ url. Version 1: Works as expected department = forms.ModelChoiceField( queryset=Department.objects.order_by('name'), initial = Department.objects.order_by('name').first(), widget=forms.Select(attrs={'class': 'custom-select mb-4', 'autocomplete': 'off', 'hx-get': '/courses/', 'hx-target': '#id_course'}) ) department = forms.ModelChoiceField( queryset=Department.objects.order_by('name'), initial = Department.objects.order_by('name').first(), widget=autocomplete.ModelSelect2(url='department-autocomplete', attrs={'class': 'custom-select mb-4', 'autocomplete': 'off', 'hx-get': '/courses/', 'hx-trigger': 'change', 'hx-target': '#id_course'}) ) -
Django render third argument
I am confused with Django renderring. In the code below the third argument used list name in strings and list name as a variable. Why so? from django.shortcuts import render my_playlists=[ {"id":1,"name":"Car Playlist","numberOfSongs":4}, {"id":2,"name":"Coding Playlist","numberOfSongs":2} ] def home(request): return render(request,'zing_it/home.html',{"my_playlists":my_playlists}) -
Django equivalent of sub query
I would like to ask if there is a different way to the following raw SQL query SQL query SELECT id, title, date_format(books.timestamp,"%%Y/%%m/%%d") AS timestamp, (SELECT count(*) FROM pages WHERE pages.book_id=books.id) AS page_count FROM books ORDER BY books.timestamp DESC LIMIT %s models.py class Book(models.Model): title = models.CharField(max_length=64) timestamp = models.DateTimeField(auto_now_add=True) class Page(models.Model): timestamp = models.DateTimeField(auto_now_add=True) book = models.ForeignKey(Book, on_delete=models.CASCADE) views.py def something(request): n_books = 10 books = Book.objects.raw(the_query, [n_books]) return render(request, "books/list.html", {"books":books}) I thought I could do this by using filter() but I don't know how to handle the sub query. Is there any Django equivalent way that uses only Python codes? Or is it better to use a raw SQL query? -
Trying to use an if statement that checks if user is friends and hide content on template page
I have a Friend model that has a variable to check if user is friends with another user. I've tested it out in shell and it works properly. When I try to implement this in my core app (they're in the same project, I just created a separate folder for my friend model), the template page only displays the 'send friend request' hyperlink even if the user is friends with the other user. I think there's an issue with my views.py snippet but I don't know how to debug it. When i try to use print() nothing shows up in my terminal. Could anyone please tell me how I can get this to work? Thanks class UserFriends(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='user') friends = models.ManyToManyField(User, blank=True, related_name='friends') def __str__(self): return str(self.user) def is_friend(self, friend): """ Check if its in your friend list """ if friend in self.friends.all(): return True return False shell: >>> from django.contrib.auth.models import User >>> from friend.models import UserFriends >>> user1 = User.objects.create_user(username='user1', password='password') user2 = User.objects.create_user(username='user2', password='password') friend_list = UserFriends.objects.create(user=user1) friend_list.friends.add(user2)>>> user2 = User.objects.create_user(username='user2', password='password') >>> friend_list = UserFriends.objects.create(user=user1) >>> friend_list.friends.add(user2) >>> friend_list.is_friend(user2) True my views: from friend.models import UserFriends def profile(request, username): profile = … -
Cannot Import Models In Django
I am trying to import my models file into my api.py file but, I get this error: > from dashboard.models import Customer, Lines, Devices > ModuleNotFoundError: No module named 'dashboard' My apps.py is: from django.apps import AppConfig class DashboardConfig(AppConfig): name = 'dashboard' My settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sessions', 'dashboard' ] My models: from django.db import models class Customer(models.Model ): account_name = models.CharField(default='', max_length=254, null=True, blank=True) accountNumber = models.CharField(default='', max_length=30, null=True, blank=True) accountType = models.CharField(default='', max_length=40, null=True, blank=True) allowDangerousExtensions = models.BooleanField(default=False) billingCycleDay = models.IntegerField(default=0) @property def customer_name(self): return (self.account_name) class Lines(models.Model): accountId = models.CharField(default='', max_length=30, null=True, blank=True) deviceName = models.CharField(default='', max_length=10, null=True, blank=True) deviceTypeId = models.CharField(default='', max_length=100, null=True, blank=True) def __str__(self): return self.accountId() class Devices(models.Model): uid = models.CharField(default='', max_length=30, null=True, blank=True) online = models.BooleanField(default=False) customer = models.ForeignKey(Customer, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.name() and api.py: from dashboard.models import Customer, Lines, Devices def create_customer(): customer = Customer.objects.create() But I cannot reference the models in the api.py file. I can reference it in my Admin.py but, api.py does not work. -
What does Django do between authentication and view dispatch?
I am trying to diagnose some performance issues I'm having with Django (3.2.18), Graphene (2.1.8), and Graphene-Django (2.14.0) using datadog. I'm also using gunicorn as my web server and postgres as my db. When looking at the trace for some oddly long-running requests, I'm seeing that there is a long delay between when the django.contrib.auth.authenticate call completes and when my view class gets setup and dispatch is called. This delay can sometimes take as long as 20 seconds but most of the time takes 10s of milliseconds. Unfortunately, datadog is not giving me any additional insight into what is happening between the authenticate call and the dispatch as can be seen in this screenshot of a trace. I don't think this is an issue where I'm running out of gunicorn workers because I'm assuming that a worker already has possession of the request in order to perform the authentication logic but I'm happy to be corrected about a bad assumption. Any pointers as to what might be happening here would be greatly appreciated as I'm not really sure where to begin looking. -
500 errors when deleting a many to many relationship using django
I am building a small scale application with a many to many relationship named 'river_rapid'. I am able to see the rapid cards on the river details view on my front end, but am not sure I am 'getting' them correctly. I am ultimately trying to DELETE the relationship (delete a rapid card from river details without deleting the rapid entirely), and previously had been getting an 'unbound local' error (hence the commented out code). After trying several things to solve that error I am now getting the error of: randrapi.models.rapid.Rapid.DoesNotExist: Rapid matching query does not exist. [05/Mar/2023 22:02:15] "DELETE /rapids/11 HTTP/1.1" 500 98330 Here are my river_rapid views and models: from django.http import HttpResponseServerError from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework import serializers, status from randrapi.models import River_Rapid, River, Rapid class RiverRapidView(ViewSet): def retrieve(self, request, pk): river_rapid = River_Rapid.objects.get(pk=pk) # river = River.objects.get(pk=pk) serializer = RiverRapidSerializer(river_rapid) print('retrieve') return Response(serializer.data) def list(self, request): # river = River.objects.all() # print(river) river_rapids = River_Rapid.objects.all() # print(river_rapids) # new_river_rapids = river_rapids.filter(river_id = river) # new_river_rapids = River_Rapid.objects.all() # new_river_rapids = request.query_params.get = ('river_rapids', None) # if new_river_rapids is not None: # new_river_rapids = river_rapids.filter(river_id = river) # print(new_river_rapids) # if … -
Where to securely store Google_Application_Credentials in Django project?
I have a Django project that uses the Google API. I created a docker-compose.yml which has my Django container and Nginx container. It builds successfully but when I run docker-compose up, I get following error: google.auth.exceptions.DefaultCredentialsError: File /file/path/credentials.json was not found. I have installed the Google SDK and ran 'gcloud auth application-default login' which creates the json file in my root directory. I then created an environment variable for it and configured my Django app. settings.py: GOOGLE_APPLICATION_CREDENTIALS = os.environ["GOOGLE_APPLICATION_CREDENTIALS"] I can open the credentials json file in my finder so I know it's there. The Google API is being used for secret manager to retrive secret keys: from google.cloud import secretmanager import environ env = environ.Env() environ.Env.read_env() def get_secret(secret_id, version_id="latest"): project_id = env("GOOGLE_PROJECT_ID") client = secretmanager.SecretManagerServiceClient() name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" response = client.access_secret_version(name=name) return response.payload.data.decode("UTF-8") Without running docker-compose up it works fine and I can retrieve keys but I want to test it out running my docker containers. My docker-compose.yml: version: '3' services: backend: build: context: ./ dockerfile: ./Dockerfile env_file: - ./backend/.env container_name: backend ports: - 8000:8000 nginx: build: context: ./nginx dockerfile: ./Dockerfile container_name: nginx ports: - 80:80 depends_on: - backend I even tried downloading the service account key which places … -
Django translation inside templates: unable to recognize variables from context dictionary and object attributes
I'm trying to use Django translation and {% translate %} tag inside my template files. Wherever I have some hard coded strings, things work just fine. The problem, however, occurs when I try to translate text from object attributes sent to the templates inside context dictionary. So I have a context dictionary like below: context = { 'object_list': <QuerySet[ <SiteDataKeyValue: some random text>, <SiteDataKeyValue: Some other random text>, <SiteDataKeyValue: and some more random text>, ], } And without translation, I access these objects very easily, for example: <h1>how I access the value of the objects:</h1> {% for object in object_list %} <p>{{ object.value }} </p> {% endfor %} Now, I try to use {% translate %} tag according to Django Docs, and I use the following syntax: <h1>how I access the value of the objects:</h1> {% for object in object_list %} <p>{% translate object.value %} </p> {% endfor %} But after running manage.py makemessages -l -i .venv command, Django fails to recognize {% translate object.value %} and show NO error message. After some research, I even tried using with command to render the object value inside a variable, as below: {% for object in object_list %} {% with value=object.value %} … -
Google Maps - How to draw a polygon and get vertex coords as result
I would like to implement google maps on my personal project (backend python-django). I have already read google maps platform documentations and I can't find the answer. How can I do (and is it possible?) that scenario: User draws a polygon on map. (I found drawing tool already, which seems perfect) At the same time or after finishing polygon, maps send vertex coords to backend. I do not have experience in front. At the beginning I need only basics. I thought using django template and implement google maps using html. But i don't know: How can I send that information (coords) to backend? Sorry for my poor English. -
Django - gettext_lazy not working in string interpolation/concatenation (inside list)
I have a dictionary of items with multiple properties. from django.utils.translation import ( gettext_lazy as _, ) {"item1": { "labels": [ _("label1"), "this is" + _("translatethis") + " label2", ] These items are then serialized in DRF. The problem is that _("label1") is being translated but "this is" + _("translatethis") + " label2" is not translated I tried also string interpolation, fstring and .format but nothing worked. When serializer fetches labels, _("translatethis") is not a proxy object. Is the only way to make this work surrounding whole strings in the gettext_lazy ? -
Django REST framework smiple jwt add custom payload data and access it in route
I am generating a custom jwt token for authentication using RefreshToken.for_user(user) at the time of login and registration. I can access user using request.user in the API endpoint but I also want to add user type in the payload data, so that I can access the user_type field in the API endpoint. This is what I am doing. def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), class UserRegistrationView(APIView): def post(self, request, format=None): serializer.is_valid(raise_exception=True) token = get_tokens_for_user(user) return Response({ 'token':token }) Now at endpoint class FileDetail(APIView): permission_classes = (IsAuthenticated,) def get(self, request, pk): user = request.user user_type = request.user_type // this data I want to save in the payload and get here. so I want user_type and other data at API endpoint from jwt payload data -
Store image with mongoengine django
I am working on a project in which I have a Company template which contains a name, url and an image under a Mongoengine Document. I would like to know how to store the image in the MEDIA folder without having to store it in DB as with the django model that allows direct image upload only in the folder. Thanks to all I didn’t find any documentation on the mongoengine website or internet without storing it into db -
Django crontab ModuleNotFoundError: No module named 'fcntl'
I'm trying to run a cron job using django-crontab with Django REST framework. I followed all the setup steps described in the library on GitHub, but when I run this command: python manage.py crontab add I get the following error: ModuleNotFoundError: No module named 'fcntl' I'm working locally on Windows, but the project will be deployed to a Linux server. I heard that "The fcntl module is not available on Windows." My questions are: Should I run the project on a Linux docker container instead? Should I search for package similar to fcntl for Windows? Should I try with another cron job package instead of django-crontab? Does anyone have any suggestions? -
Django Rest Framework authentication class override request.user
in my django App I have created a custom Authentication class using rest_framework: from business.models import BusinessToken from rest_framework.authtoken.models import Token from rest_framework import authentication, exceptions class AuthenticationMixin(authentication.BaseAuthentication): def authenticate(self, request): raw_token = request.META.get('HTTP_AUTHORIZATION') if not raw_token: return None token_key = raw_token.replace("Token ", "") user_token = Token.objects.filter(key=token_key).first() if user_token is not None: user = user_token.user request.user = user return user, None business_token = BusinessToken.objects.filter(key=token_key).first() if business_token is not None: business = business_token.business request.business = business user = business.owner request.user = user return business, None raise exceptions.AuthenticationFailed('No such user or business') As you can see the class has to authenticate the user or the business based on the token pass from http request. If the user authenticate itself through the business token in the api view I have to access to request.user as the business.owner and request.business as the business, but request.user is set to business, it's override somewhere. -
Is there any way to host django project with xampp?
I was trying to deploy it on apache24 lounge I was wondering if it is passible -
TypeError at /dj-rest-auth/google/ string indices must be integers
I wanted to do social authentication using dj-rest-auth with google. But getting an error like this doesn't understand anything. I want the advice of the experienced. I tried after submitting the access token it will return me a key for authentication. But I can't get it because of the error! -
How can i include multiple Plotly graphs in a webpage?
i am trying to build an application that shows plots generated out of data in the db . I want to publish these in a grid in same webpage now can i do this Here is my views.py unique_m = df['metric'].unique() hlist = [] for m in unique_m: df2 = df.loc[df['metric'] == m] fig = px.line(df2, x="date", y="value", title=m, width=700, height=500) file = fig.write_html("Templates/plots/%s.html" % m ) hlist.append(file) context1 = {'plotly_div': hlist} return render(request, 'index.html', context1 ) Here is my index.html {% extends "base.html" %} {% block content %} <div> <!-- {% autoescape off %} --> <div style="margin: 0 auto; width:855px; height:500px;"> {% for x in plotly_div %} <div style="margin: 0 auto; width:855px height:500px;"> <iframe src="{{ plotly_div }}" style="border:none;" style="height:500px;width:800px;" seamless="seamless" scrolling="yes"></iframe> </div> {% endfor %} </div> </div>` <!-- {% endautoescape %}} --> {% endblock content %} -
Django Many to Many (through) with three tables and extra attributes
I have an already existing database with 3 tables: Person, Card, and Permission. A user may have access to multiple cards, of which only some is owned by the person. How would I get all cards that the person has access to with the ownership status? Due to how the system should work, it's essential that the DB fetch is done in a single query. It's as if the usage of some magic values (such as objects.<table_name>_set....) is necessary to get this working? Ideal target query (including the person table) would be: SELECT card.id, card.text, permissions.owner FROM person.id JOIN permissions ON person.id = permissions.person_id JOIN cards.id = permissions.card_id WHERE person.id = <some person id>; Example target result from the query fetching cards for user id=1: [ { "id": 123, "text": "some random text", "owner": false }, { "id": 682, "text": "more random text", "owner": true } ] I've also tried some other solutions in some other threads, but most of them either don't include the extra data from the through-table, or don't work as they seem to require an extra table (such as Many-to-many relationship between 3 tables in Django which will throw an error "relation personcardpermissions does not exist" … -
How to implement consumer for voice chat app on Django?
I am currently working on a voice chat app as a personal project and this app will be like Discord, where users can hop into a chat room and start talking to people in that room. I am only going to make it voice only for now (I will implement text messaging later). I have been looking at examples on Github and I am having a little trouble with how to make the Consumer. Here is what I have right now: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class VoiceConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = "chat_%s" % self.room_name # join the room async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, closed_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) # Ask about this, how to receive voice ? voice_message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, {'type' : 'chat_message', 'message': voice_message} ) As you see, I am confused about the text_data_json['message'] part. This is based off an example I have seen where someone implements messages, but I want to implement voice only. What do I change about this to where I can implement voice only ? text_data_json = json.loads(text_data) # Ask about this, how to receive voice … -
Django - Error during inporting Excel csv file with Pandas
I am having error on this code which is for csv importing data into the database using Django. This is the error. Many thanks for your help MultiValueDictKeyError at /countyImportFromExcelPd/ 'countryList' #model.py ### For the list of the country class Country(models.Model): ### country_di = models.AutoField(primary_key=True) country_iso2 = models.CharField(verbose_name='Country ISO 2 codes', max_length=4, null=True, blank=False) country_iso3 = models.CharField(verbose_name='Country ISO 3 codes', max_length=4, null=True, blank=False) country_name_EN = models.CharField(verbose_name='English', max_length=256, null=True, blank=True) country_name_FR = models.CharField(verbose_name='Francais', max_length=256, null=True, blank=True) country_name_DE = models.CharField(verbose_name='Desch', max_length=256, null=True, blank=True) country_name_ES = models.CharField(verbose_name='Espagnol', max_length=256, null=True, blank=True) country_comment = models.CharField(verbose_name='Comments', max_length=1024, null=False, blank=True, help_text='Coments on the payment') country_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) #View.py def countyImportFromExcelPd(request): if request.method == 'POST' and request.FILES['countryList']: countryList = request.FILES['countryList'] fs = FileSystemStorage() filename = fs.save(countryList.name, countryList) uploaded_file_url = fs.url(filename) empexceldata = pd.read_excel(filename) dbframe = empexceldata for dbframe in dbframe.itertuples(): obj = Country.objects.create(country_iso2=dbframe.country_iso2, country_iso3=dbframe.country_iso3, country_name_EN=dbframe.country_name_EN, country_name_FR=dbframe.country_name_FR, country_name_DE=dbframe.country_name_DE, country_name_ES=dbframe.country_name_ES, country_comment=dbframe.country_comment ) obj.save() return render(request, 'students_management_app/country-import.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'country-import.html',{}) # url.py path('countyImportFromExcelPd/', views.countyImportFromExcelPd, name='county-import-ExcelPd'), -
TypeError: context must be a dict rather than str
I am newbie. I am currently learning django. I have a page with a meeting of goods: URLS.PY urlpatterns = [ path("productsHTML/<str:uuid>", productHTML, name = "productHTML"), path("productsHTML/", productsHTML, name = "productsHTML") ] VIEW.PY def productsHTML(request): all_products = {"products": Product.objects.all()} return render(request, "products.html",all_products) def productHTML(request, uuid): product = Product.objects.get(id = uuid) value = [product.name, product.category, product.marka, product.privod, product.loshad_sila, product.box_peredach, product.volume_dvigatel] values = {"values": value} return render(request, "product.html", uuid, values) PRODUCTS.HTML {% block content %} <h2>Продукты</h2> <hr> {%if products %} {% for product in products %} <p><b>Категоия: </b>{{ product.category}}</p> <p><b>Название: </b><a href="http://127.0.0.1:8000/productsHTML/{{ product.id }}">{{ product.name}}</a></p> <p><b>Цена: Бесплатно</p> <hr> {% endfor %} {% endif %} {% endblock %} PRODUCTS.HTML {% extends 'products.html' %} {% block title %}Продукт{% endblock %} {% block content %} {% if values %} {% for value in values %} <p><b>Категоия: </b>{{ value.category }}</p> <p><b>Название: </b>{{ value.name }}</p> <p><b>Марка: </b>{{ value.marka }}</p> <p><b>Привод: </b>{{ value.privod }}</p> <p><b>Лошадиные силы: </b>{{ value.loshad_sila }}</p> <p><b>Коробка передач: </b>{{ value.box_peredach }}</p> <p><b>Объём двигателя: </b>{{ value.volume_dvigatel }}</p> <p><b>Цена: Бесплатно</p> {% endfor %} <button>КУПИТЬ</button> {% endif %} {% endblock %} I need to click on the link contained in the product name to be redirected to the product page with the address http://127.0.0.1:8000/productsHTML/ product id. If needed, … -
installing chatterbot it raise spacy installation error in python- pip install chatterbot - not working
Ii have installed latest Redistributable Microsoft C++ and upgraded my pip but not resolved...anyone please give solution `pip install chatterbot` preshed/maps.cpp(181): fatal error C1083: Cannot open include file: 'longintrepr.h': No such file or directory **error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 [end of output]** note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure Encountered error while trying to install package. preshed ` × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─\> See above for output.`