Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest framework, violates not-null constraint DETAIL
I have a question about my serializers. I have the following structure, summarizing. Consists of 3 models and a CreateAPIView view B contains OneToOneField = A C contains ForeingKey = B (many = True) [{List Image}] I don't understand much, how to perform create method in nested serializer. class A (serializer.ModelSerializer): class Meta: model = A class B (serializer.ModelSerializer): A = CreateASerializer () # OneToOneField to A C = CreateBSerializer (many = True) # ForeingKey to B List [{}] class Meta: model = B class C (serializer.ModelSerializer): class Meta: model = C #Can I separately create the Create method for each serializer? # For instance: class A (serializer.ModelSerializer): class Meta: model = A def create (self, validated_data): return models.A.create (** validated_data) class B (serializer.ModelSerializer): A = CreateASerializer () # OneToOneField C = CreateBSerializer (many = True) # ForeingKey List [{image}] class Meta: model = B fields = ('A', 'detail', 'C') def create (self, validated_data): A_data = validated_data.pop ('A') C_data = validated_data.pop ('C') date1 = models.B.objects.create (**validated_data) date2 = models.C.objects.create (**validated_data) for f in A_data: models.A.objects.create (date1=date1, **f) for nu in C_data: models.C.objects.create (date2=date2, **nu) return ? class C (serializer.ModelSerializer): class Meta: model = C def create (self, validated_data): C_data = … -
How to implement pagination in Django
I would like to implement pagination in my custom jsonresponse function. But I have no idea on how would i implement this. This is the code of my function. Any inputs will be a great help. Thank you. def json_response(data = {}, message = 'successful!', status = 'success', code = 200): data_set = {} status = 'success' if code == 200 else 'error' if status == 'success': data_set['code'] = code data_set['status'] = status data_set['message'] = message # data_set['data'] = data.data try: data_set['data'] = data.data except TypeError: data_set['data'] = json.dumps(data) except AttributeError: data_set['data'] = data else: data_set['code'] = code data_set['status'] = status data_set['message'] = message return JsonResponse(data_set, safe=False, status=code) -
Due to a loop before pagination Django paginator takes too much time. How can I solve this problem?
I was asked to map the object customer. I was trying to do the pagination before the loop but I don't know how to do it, because I think that you need to pass all the data to the paginator when creating. This is my view I think the problem is that when I call the function "get_customer_view_data" it runs the loop inside this function and I believe this happens everytime I change page on the paginator, causing the delay class CustomersView(AdminStaffRequiredMixin, TemplateView): template_name = 'customers/tables.html' def get(self, request, activeCustumers, *args, **kwargs): controller = CustomerViewController() date1 = request.GET.get('date1', 1) date2 = request.GET.get('date2', 1) customer_view_data = controller.get_customer_view_data(activeCustumers, date1, date2) page = request.GET.get('page', 1) paginator = Paginator(customer_view_data, 10) try: customers_data = paginator.page(page) except PageNotAnInteger: customers_data = paginator.page(1) except EmptyPage: customers_data = paginator.page(paginator.num_pages) context = {'object_list': customers_data, 'num': len(customer_view_data)} return render(request, self.template_name, context) And this is my controller where I map the data: class CustomerViewController(object): def get_customer_view_data(self, get_active_custumers,date1,date2): data = [] dates = self.set_dates(date1, date2) if get_active_custumers == 1: obj = Organization.objects.filter(organizationmainapp__application__appinfoforstore__status=2, deleted=False, status=True, to_deleted=False) else: obj = Organization.objects.all() for o in obj: customer_view_data = Customer() customer_view_data.Organization_id = o.id customer_view_data.Organization_name = o.name try: customer_view_data.monthly_price_plan = o.organizationmainapp.application.applicationselectedplan.price_plan.monthly_price except Exception as e: print(e) try: if … -
Printing multiple items using serializer
@api_view(['GET']) def selected_device(request,pk=None): if pk != None: devices = Device.objects.filter(pk=pk) devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk) cursor = connection.cursor() tablename= "dev_interface_" + str(pk) cursor.execute(f"SELECT interface FROM {tablename} ") righttable = cursor.fetchall() devserializer = DeviceSerializers(devices, many=True) devdserializer = DeviceDetailSerializers(devicedetail, many=True) interfaces = [] for i in righttable: interfaces.append(i[0]) for i in interfaces: data =[{"interface": i}] interserializer = InterfaceSerializers(data, many = True) results = { "device":devserializer.data, "device_details" : devdserializer.data, "interface":interserializer.data, } return Response(results) In interfaces, I have the following ['G0/1', 'TenGigabitEthernet1/1/3', 'TenGigabitEthernet1/1/5', 'TenGigabitEthernet1/1/20', 'TenGigabitEthernet1/1/21', 'TenGigabitEthernet1/1/22', 'TenGigabitEthernet1/1/23', 'TenGigabitEthernet1/1/24', 'TenGigabitEthernet1/1/25', 'TenGigabitEthernet1/1/26'] But the above codes just print the last item in interface, how do I ensure it to print everything in interface? -
How to pass value into another model based on conditional statement [Django]
I want to create a countdown timer target that will be added into date_target model, using override save method in models.py, the time will countdown differently based on it's variety. import datetime class CustomerVariety(models.Model): variety = models.CharField(max_length=100, null=True) def __str__(self): return self.variety class Customer(models.Model): cardnumber = models.CharField(max_length=15, null=False) name = models.CharField(max_length=100, null=False) date_in = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) date_target = models.DateTimeField(auto_now_add=False, null=True) variety = models.ForeignKey(PerihalPermohonan, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.pk: if self.variety == "Priority Customer": self.date_target = self.date_in + datetime.timedelta(days=3) elif self.variety == "Secondary Customer": self.date_target = self.date_in + datetime.timedelta(days=5) super(Customer, self).save(*args, **kwargs) when i pass value into form and save it, why date_target models doesn't full fill the value ? -
Django / React - JWT Auth: How to persist token in-memory OR utilize httpOnly cookie in request
How can I use my access token either (1) through persisting it in-memory or (2) utilizing httpOnly cookies with my React app? Context Pretty confused with this right now. I'm using dj-rest-auth and djangorestframework-simplejwt for authentication. When I call the login endpoint from my backend, I get the refresh_token and access_token + set-cookie for both of these. This is fine. Attempt 1 When I try to utilize the token with an Authorization header on another page, it's undefined. This means there's a flaw with my AuthContextProvider (probably because I'm using a state variable that resets it). AuthContext const AuthContext = React.createContext({ token: '', isLoggedIn: false, login: (token) => { }, logout: () => { }, refreshToken: () => { }, }); export const AuthContextProvider = (props) => { const [token, setToken] = useState(); const userIsLoggedIn = !!token; const loginHandler = (token) => { setToken(token); } const logoutHandler = () => { setToken(null) } const contextValue = { token: token, isLoggedIn: userIsLoggedIn, login: loginHandler, logout: logoutHandler, } return ( <AuthContext.Provider value={contextValue}> {props.children} </AuthContext.Provider> ); }; export default AuthContext; Using authContext.token (authContext being the local variable from useContext), the token is undefined on any other page. Attempt 2 Ok, so the token … -
Accessing matching entry of two models using ForeignKey
I have three models: a Game model, a Distributor model and a Relation model. The Relation model has two ForeignKeys. One linking to Game model and other to Distributor model. I need to access on template (on the same view) the data from the Game model and from the Relation model for the matching entry. Models.py class Game(models.Model): name = models.CharField(max_length=100, unique=True) class Distributor(models.Model): dist = models.CharField(max_length=30, unique=True) class Relation(models.Model): game = models.ForeignKey('Game', on_delete=models.CASCADE) distributor = models.ForeignKey('Distributor', on_delete=models.CASCADE) Views.py class GameDetailView(DetailView): model = models.Game context_object_name = 'game_detail' template_name = 'gamesDB/game_detail.html' def get_context_data(self, **kwargs): context = super(GameDetailView, self).get_context_data(**kwargs) context.update({ 'game_status': models.Relation.objects.all() }) return context I think my view isn't right. But I can't find the way to make it work. How can I access on template the data from the Relation model for the matching game added on the Game model? Thanks in advance. -
Why Django Updating object not triggering at first time?
I have two function. My first function updating an Boolean filed True to False. My first function working properly but my second function not updating object False to True. If I try two time then second time my second function updating object False to True. I am not understanding why it's not updating at first time? here is my code: function1 #this function working properly views.py def ForgetPassword(request): if request.method == "POST": .....my others code profile_obj = UserProfile.objects.get(user=user_obj) profile_obj.email_confirmed = False profile_obj.save() .....my others code function2 #this function not working properly If I try two time then second time my this function updating object False to True: class ChangePassword_link(View): #my others code.... if user is not None and account_activation_token.check_token(user, token): profile_obj = UserProfile.objects.filter(user=user).update(email_confirmed = True) messages.success(request, ('Your account have been confirmed. Now you can login')) return redirect('members:change-password-page') else: messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.')) return redirect('members:change-password-page') #my others code.... -
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