Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate InvoiceCreator into the checkout flow
Im following the instructions on how to utilize django-oscar-invoices on https://django-oscar-invoices.readthedocs.io/en/latest/quickstart.html , but I dont understand how to integrate oscar_invoices.utils.InvoiceCreator into the checkout flow. Can anyone explain how to do this? -
Building a complex User Schema for website
I have made my first website using Django. Currently, I just have a simple custom user model with name, email etc. Now I want to integrate a payment gateway wherein users can pay and then access the website. The caveat is, I have two types of users, let's say A and B. User type A pay an amount that I have negotiated with them so I have to manually charge them. B pays the amount as per the subscription plans I have set. Now, I want that people A should be able to 'Sponsor' users from their firm or their clients. User type B should be able to collectively apply for a set number of accounts and get a discount based on the number of accounts they purchase. (I know its a bit too complicated but that's what my boss asked of me) I'm using a token payment system linked to a third party service. Does anyone have a good schema recommendation for this problem? My current best idea for this schema is User Details (name address etc) is Sponsor (boolean field - if the user is a sponsor) Sponsored by (if user is not the sponsor, who's sponsoring) - … -
How to remove user using Django Allauth API?
When a user in my Django app cancels their account, I set is_active=False in the auth_user table. However, if that use signs up again, Allauth complains that the email is already in use, even if I manually change the email field to something else in the auth_user table. Allauth is going by the email addresses in the 'account_emailaddress' table. So what's the correct API call to tell Allauth to forget that email, while also setting the auth_user table to not active? Is it safe to delete the entry from the 'account_emailaddress' table myself? Or maybe there's a signal that listens for the record in the auth_user table being completely deleted by my app, and just unsetting 'is_active' isn't enough? I see no such signal listed in the docs, though there is one for changing the email. In short, what's the Allauth way to a) suspend and/or b) delete a user? I'm not using a social account. The following answer implies it's enough to set is_active=False as I describe above, but I've found that more is needed if you want to allow that email to be reused. How to allow user to delete account in django allauth? -
Django how to improve security of password reset?
I setup an password reset option for my users. But I found few security risk: 1) password reset link not expiring: Right now my password reset link not expiring. I want password reset link can be use only one time. User can't use it second time for change his password 2) How to prevent password change if user change the value of HTML : Let you explain. I have an html hidden input filed like this <input type="hidden" name="user_id" value="{{user_id}}"> if user change the html value of user_id then I want to prevent password changing. here is my code: token.py for sent password reset link to mail def send_forget_password_mail(email,token): subject = 'EXAMPLE.COM Password Reset Link' message = f'hi your forgot password link http://127.0.0.1:8000/change-password/{token}' email_from = 'noreply@EXAMPLE.com' recipient_list =[email] send_mail(subject,message,email_from,recipient_list) return True views.py This is the forget password view where user submit mail for get password reset link. Here I also saving token in user profile. def ForgetPassword(request): if request.method == "POST": email = request.POST["email"] User = get_user_model() if not User.objects.filter(email=email).first(): messages.success(request, "Invalid mail") return redirect('members:rest-password') user_obj = User.objects.get(email=email) print(user_obj) token = str(uuid.uuid4()) profile_obj = UserProfile.objects.get(user=user_obj) profile_obj.forget_password_token = token profile_obj.save() send_forget_password_mail(user_obj.email,token) messages.success(request, "An password reset link sent to your email") return … -
How to query overlapping dates on Postgres DateRange field
I have a model with a PostgreSQL DateRange field: class MyModel(models.Model): date_range = DateRangeField() If I want to query this to see if another date overlaps, that's easy enough: MyModel.objects.filter(date_range__overlap=other_date) But if I have built a list of DateRange objects, how can I perform the same query: mylist = [DateRange([2021-10-04, 2021-10-05]), DateRange([2022-10-04, 2022-10-05])] for dr in mylist: dr.overlap(query_date) # fails -
Tableau server hosted on AWS and Embedding with Django
I have my tableau server configured on an AWS instance. I have published a dashboard into the server(Using the trial version). I am trying to display that in a web page locally as of now. I have tried the following steps: Note: I have replaced my code with original ec2 instance with "ec2-server" just for confidential purpose. I copied the embedded code from the share option in the server and pasted in the html file that i am rendering in django. It requests me to log in to the server and then displays the same login page again and again. ( I tried this method with tableau online and instantly i was able to display my dashboard). It says to login again but nothing happens... I then read into the Trusted Authentication from tableau docs and came up with this code to get the ticket and embed in the view that renders my home.html page : from django.shortcuts import render from django.http import HttpResponse from rest_framework import status from rest_framework.response import Response import requests from rest_framework.decorators import api_view import sys def home(request): #I have replaced my code with original ec2 instance with "ec2-server" just for confidential purpose. url = 'http://ec2-server.compute-1.amazonaws.com/trusted/' … -
i can't use python python .\manage.py makemigrate
when i run it i get this: C:\Users\owen pierce\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe: can't open file 'C:\Users\owen pierce\desktop\galeana.biz\pagina-base\manage.py': [Errno 2] No such file or directory -
django calculate total hour from datatimefield
I have a model that looks something like below which has a field called datetime. This field holds the record of date and time. What I want to do is to calculate the total number of hours per month and week. I need direction on how to go about doing that. class Clockin_Transaction(models.Model): id = models.AutoField(db_column='id', primary_key=True) clockinusers = models.ForeignKey(Clockin_Users, on_delete=models.CASCADE) lid = models.IntegerField(db_column='LID', null=True, default=0) userid = models.IntegerField(db_column='UserID') temid = models.IntegerField(db_column='TemID') datetime = models.DateTimeField(db_column='DateTime', help_text='eg:2021-07-21') inout = models.IntegerField(db_column='InOut') def __unicode__(self): return self.clockinusers.name -
Django compressor is not effective
I've successfully set everything in the setting.py and when running py manage.py compress it runs without errors and I see that 2 blocks have been compressed. Here is the template: {% compress css %} <link rel="stylesheet" type="text/css" href="{%static 'project/main.css' %}"> {% endcompress %} When opening the site from the browser I see something happened (the filename changed to output.6a62b0ce8790.css and the Accept-Encoding: gzip, deflate is also shows up). However the filesize is not changing. COMPRESSION_ENABLED = True is set and I also use DEBUG = True (I don't know if it matters). -
How to see keys set by django-ratelimit in redis server?
I am using the following django==3.1.3 django-ratelimit==3.0.1 django-redis==4.12.1 djangorestframework==3.12.2 I am trying to set up a rate-limit to limit the number of times a POST request is called. I have this in my settings: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, "KEY_PREFIX": "my_app" } } I have this in views.py. (A very simplified version) @ratelimit(key='ip', rate='1/5m', method=['GET', 'POST']) def rate_limit_func(request): if request.method == 'POST': return Response(status='200') The rate limit is working as expected. But I cannot see any keys getting stored in the redis server 127.0.0.1:6379> ping PONG 127.0.0.1:6379> get ip (nil) 127.0.0.1:6379> keys * (empty list or set) I also tried searching the key using django shell >>> from django.core.cache import cache >>> 'ip' in cache False I am not sure if I have set this up correctly and it will work in production. Also, where are the cache values being set? -
Django Object gets created twice
So I have a big app and was able to find out where the "error" is located (That's why I don't need to upload more of my code) image_model = Image_model( user = user, lan = lan, lon = lon, width = width, height = height, image_name = image_name, image_name_preview = image_name_preview, image = original_image, preview_image = preview_image, whatisseen = whatisseen, timestamp_create = timestamp_create ) image_model.save() RoomChatMessage.objects.create( room = room, user = user, content = message, image = image_modal, ) payload = {"Success": "Message successfully added"} So when I call the function around the two objects the image object is created and after that the RoomChatMessage object. But now I have a problem: When I commend the image_modal out (the full object) and only create the RoomChatMessage (without the image) it works fine. But if I call the function like this I get one Image Object and two Message Objects - but why? -
How to get category id and display the product which is under the category in django
Here is my models.py. from django.db import models # Create your models here. class Category(models.Model): cateId = models.AutoField(primary_key=True) cateName = models.CharField(max_length=200) def __str__(self): return self.cateName class Product(models.Model): prodCategory = models.ForeignKey(Category, on_delete=models.CASCADE) prodId = models.AutoField(primary_key=True) prodName = models.CharField(max_length=200) def __str__(self): return self.prodName views.py from django.shortcuts import render, get_object_or_404 from product.models import Category, Product def category(request, *args, **kwargs): category = Category.objects.all() ctx = {'category': category} return render(request, 'category.html', ctx) def category_product(request, cateId, *args, **kwargs): product = Product.objects.get(prodCategory=cateId) ctx = {'product': product} return render(request, 'product.html', ctx) urls.py path('category/<int:cateId>/', views.category_product, name='category_product') this is my product which is after i click the category link product.html <body> <div class="container"> {% for product in product %} <a href="#"> <div class="product"> <h2>{{ product.prodName }}</h2> </div> </a> {% endfor %} </div> </body> here is my category page which give a clickable link to view the product which is under this category. category.html <div class="container"> {% for category in category %} <a href="#"> <div class="category"> <h2>{{ category.cateName }}</h2> </div> </a> {% endfor %} </div> -
How to access user profile in templates Django
How do you access user profile model in template. I have related name set to "profile", and I use {{user.profile.id}} and it returns nothing. -
Django Admin CSS not loading up
Iam trying to get my Django admin to have the css as it look in development, but nothing seems to work for me. I tried following things: Have following static value in settings.py # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' STATICFILES_DIRS = [os.path.join(BASE_DIR,'staticfiles')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/' Add mimetypes.add_type("text/css", ".css", True). Since the console error was showing "Refused to apply style from 'https://example.org/admin/login/?next=/static/admin/css/base.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." I ran python manange.py collectstatic. (Admin static files are available in static folder as well). I set Debug=False as well I cant figure out the problem. Any ideas are welcome. Thanks in advance -
How to display multiple images in a django template img element
I am having a challenge displaying multiple images users post to one img template element, for one reason if i try fetching images with the default related name it wouldn't show in the template and i wonder what i am doing wrong. Can anyone be of help! Here is my model for post. class Post(models.Model): page = models.ForeignKey(Page, on_delete=models.CASCADE, related_name="page") username = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE ,related_name="page_user") description = models.TextField(max_length=500, blank=True) video = models.FileField(upload_to="PageVideos", blank=True) pic = models.ImageField(blank=True) date_posted = models.DateTimeField(auto_now_add=True) tags = models.CharField(max_length=100, blank=True) class Mete: ordering = ['-date_posted'] def __str__(self): return self.description class PostImage(models.Model): #page = models.ForeignKey(Page, on_delete=models.CASCADE, related_name="pg") post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) images= models.ImageField(upload_to="postimages/") Here is my Detail view def page_detail(request,id): post = get_object_or_404(Post, id=id) photos = PostImage.objects.filter(post=post) context = { 'post':post, 'photos':photos } return render(request, 'page/detail.html',context) These my Template to display users images <div class="p-3 border-b dark:border-gray-700"> {{ post.description }} </div> <div uk-lightbox> <div class="grid grid-cols-2 gap-2 p-2"> {% for p in photos.images_set.all %} <a id="images" href="{{ p.images.url }}" class="col-span-2" > <img src="{{ p.images.url }}" alt="" class="rounded-md w-full lg:h-76 object-cover"> </a> <a href=""> <img src="" alt="" class="rounded-md w-full h-full"> </a> <a href="" class="relative"> <img src="" alt="" class="rounded-md w-full h-full"> <div class="absolute bg-gray-900 bg-opacity-30 flex justify-center items-center text-white rounded-md … -
How to see the logs of django-docker deployed on digitalocean via github
I deployed my django docker via GitHub actions to Digital Ocean. How can I see the logs since I am not able to see my django live on the link? -
How to fetch clients id and clients secret key in models using django for social media login
Hey how to fetch user credentials from database models for Facebook login in django. And how to get token_access of Facebook graph API for each user -
How to deploy flutter web with Django?
when I build flutter web app : flutter build web I want to deploy this with dango server, what should i do? thanks !! -
Django FileResponse through nginx error ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION
django use FileResponse and runserver in 8000 port. # this add Content-Disposition header in response response = FileResponse(file, filename="file.txt", as_attachment=True) nginx proxy_pass to django: location /api/v1/download { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_set_header X-Real_IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } when I access django directly, I download file successfully, but when I access django through nginx, chrome throw error ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION. Use curl to send request to django directly: curl -v http://django:8000 < HTTP/1.1 200 OK < Server: WSGIServer/0.2 CPython/3.9.2 < Content-Type: application/octet-stream < Content-Disposition: attachment; filename="filename.txt" # django add < Vary: Accept, Cookie < Allow: GET, HEAD, OPTIONS < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Connection: close Use curl to send request to nginx, it shows duplicate Content-Disposition response header: curl -v https://nginx < HTTP/1.1 200 OK < Server: nginx/1.20.1 < Date: Mon, 04 Oct 2021 16:39:01 GMT < Content-Type: application/octet-stream < Transfer-Encoding: chunked < Connection: keep-alive < Content-Disposition: attachment; filename="filename.txt" # django add < Vary: Accept, Cookie < Allow: GET, HEAD, OPTIONS < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Content-Disposition: “attachment” # nginx add Why nginx auto Content-Disposition: "attachment" In response header? Is there some way to avoid this? -
How to do nested Group By with django orm?
I have the following data: publisher title -------------------------- ----------------------------------- New Age Books Life Without Fear New Age Books Life Without Fear New Age Books Sushi, Anyone? Binnet & Hardley Life Without Fear Binnet & Hardley The Gourmet Microwave Binnet & Hardley Silicon Valley Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Here is what I want to do: I want to count the number of books published by each author in a single object. I want to get the following result: {publisher: New Age Books, titles: {Life Without Fear: 2, Sushi Anyone?: 1}}, {publisher: Binnet & Hardley, titles: {The Gourmet Microwave: 1, Silicon Valley: 1, Life Without Fear: 1}}, {publisher: Algodata Infosystems, titles: {But Is It User Friendly?: 3}} My solution goes something along the lines of: query_set.values('publisher', 'title').annotate(count=Count('title')) But it is not producing the desired result. -
multiple websocket instances for chat application
I'm building a Django-Vue chat applicaton, I already builded the core functionallity of the app. When the SideBar component is mounted a HTTP request is maded to get all rooms that the user is a participant, when some room is clicked a WebSocket instance is created on the Chat component. My doubt is, if I send a message to that room but the others users are not connected in the same room (suposse that they are connected in other room) they will not receive the message right? So how I send him a notification about the new message? like Whatsapp sidebar notifications. I was thinking in create two WebSocket connections, one on the SideBar that will be the user endpoint (ws:127.0.0.1:8000/chat/$Username) and other for the actually chat room (ws:127.0.0.1:8000/chat/$ChatId), is that a good approach? My django models => from django.db import models from account.models import CustomUser class Message(models.Model): sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='messages') message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'message from {self.sender.username}' class Chat(models.Model): name = models.CharField(max_length=24) participants = models.ManyToManyField(CustomUser, blank=True) messages = models.ManyToManyField(Message, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
Can you break a for loop in django?r
{% if user.is_authenticated %} {% for robot in object_list %} {% if user.id == robot.username.id %} <div style="color: #3b2063; outline: 3px solid #3b2063;"> <ul> <li><a href="{% url 'robot-detail' robot.pk %}"><h1>{{ robot.name }} - Current Status: {{ robot.current_status }} - Current Path: {{ robot.path_options }}</a></li> </ul> </ul> <hr> </div> {% else %} <h1>You have no robots.</h1> {% endif %} {% endfor %} {% else %} <div style="color: #3b2063; outline: 3px solid #3b2063;"> <ul> <li><H1><a href="{% url 'login' %}"> Log in </a> to get started.</h1></li> </ul> <hr> </div> {% endif %} where it says you have no robots. it runs the the amount of robots there are in object_list, i was thinking that i could break the for loop right after the any suggestions? -
How to retrieve the ids from the array of objects using python and django?
Hi i have an array of objects like below, const arr_obj = [ { 'id': 1, 'items': [ { 'id':'1', 'data': { 'id': 3, } }, { 'id': '2', 'data': { 'id': 4, } } ] }, { 'id': 2, 'items': [ { 'id':'3', 'data': { 'id': 5, } }, ] }, ] I want to retrieve the id property of items array and put it an array so the expected output is ['1','2','3'] below code works in javascript arr_obj.map(obj=>obj.items.map(item=>item.id)).flat() how can i do the above in python and django. could someone help me with this. I am new to python and django thanks. -
django "Field 'id' expected a number but got 'yoavlv'."
I want to create a page where the user can see the details he posted on the site. The problem I get "Field 'id' expected a number but got 'yoavlv'." I already searched for solution and try to solve it with "slug" but it didn't work.. def my_items(request, user): user_items = get_object_or_404(Add_Item, user=user) items = Add_Item.objects.filter(user =user_items) return render(request, 'my_items.html',{"items":items,}) model : class Add_Item(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, default=None, null=True) title = models.CharField(max_length=255) categories = models.CharField(max_length=255 , choices=all_categories) description = RichTextField(blank=True,null=True) condition = models.CharField(max_length=100, choices=cond) city = models.CharField(max_length=50, choices=cy.city, blank=True) street = models.CharField(max_length=100, blank=True) home_number = models.CharField(max_length=100, blank=True) header_img = models.ImageField(null=True, blank=True, upload_to='img/') more_img = models.ImageField(null=True, blank=True, upload_to='img/') Pub_date = models.DateField(auto_now_add=True) -
Django admin form raises IntegrityError for model with conditional UniqueConstraint
I was asked to add some logic to model uniqueness. Each Payment must have either transaction_id or payment_id filled. Each Payment is identificated by (transaction_id, operation, payment_created_date) or (payment_id, operation, payment_created_date). On database level this works fine. Inserting Payment with same transaction_id, operation, payment_created_date twice causes unique constraint violation. For this model i created admin page. But inserting same row with admin page causes IntegrityError at /admin/finance/payment/add/ duplicate key value violates unique constraint "unique_finance_payment_without_payment_id" DETAIL: Key (transaction_id, operation, payment_created_date)=(dasdasd, Refund, 2021-10-04) already exists. instead of simple user-friendly admin error Please correct the error below. Payment with this Transaction id, Operation and Payment created date already exists. How to make Django admin catch this IntegrityError and show it in admin form? here is my models.py class ReportName(DiModel): name = CharField( max_length=50, blank=False, null=False) def __str__(self): return self.name class Payment(DiModel): class Meta: unique_together = ('transaction_id', 'payment_id', 'operation', 'payment_created_date') constraints=[UniqueConstraint(fields=['transaction_id', 'operation', 'payment_created_date'], condition=Q(payment_id=None), name='unique_finance_payment_without_payment_id'), UniqueConstraint(fields=['payment_id', 'operation', 'payment_created_date'], condition=Q(transaction_id=None), name='unique_finance_payment_without_transaction_id'),] OPERATION_TYPE = [ ('Refund', 'Refund'), ('Charge', 'Charge'), ] CURRENCY_CODE = [ ('EUR', 'EUR'), ('RUB', 'RUB'), ('USD', 'USD'), ('GBP', 'GBP'), ('AUD', 'AUD'), ('PLN', 'PLN'), ('SGD', 'SGD'), ('MYR', 'MYR'), ('RON', 'RON'), ('ZAR', 'ZAR'), ] report_name = ForeignKey(ReportName, on_delete=models.PROTECT, blank=False, null=False, help_text="Processor and report type") operation = …