Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing Django variable to an accordion attribute in HTML
I am newbie to Django and apologize in advance for such a basic question to most of you, but I looked for similar questions all over and haven't encountered a workable solution. I am trying to create a Bootstrap Accordion for each item of a Django for-loop. So a list of items is displayed, and when you click on one item, the description of it will collapse to show. The segment currently looks like this using this template: <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </head> <body> {% for item in items %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="headingOne"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-parent="#accordion" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> {{ item }} </button> </h2> <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="accordion-body"> {{ item.description }} </div> </div> </div> </div> </body> Now, this is giving the same value (collapseOne) to data-bs-toggle, aria-controls and id of accordion-collapseclass(collapsing element) for every for-loop item, resulting in all the accordion items collapsing when one of them is clicked though I want only the clicked one to collapse. So I tried to pass the Django variable as such: {{ item }} in place of collapseOne {{ forloop.counter }} in place of collapseOne The … -
db.sqlite3 continues working after having been deleted
I recently deleted my db.sqlite3 file because some data had become corrupted. I though that at the next run of python manage.py migrate it would have simply been recreated from stratch. Instead, Django is contuining to work off the old db.sqlite3 despite the file not existing anymore - I assume it's somehow cached? Specifically: python manage.py migrate works fine but it doesn't create a new db.sqlite3 file. There is no db.sqlite3 file anymore in my root. I already manually deleted all migrations. The app continues to work okay with all the previous data still there (e.g., users). In case it's useful, I'm coding on Replit. -
Is it impossible upload file in the different region from the region of s3 bucket? (IllegalLocationConstraintException)
I deployed my django project using AWS Elastic beanstalk and S3, and I tried to upload the profile avatar but it shows Server Error(500) My Sentry log shows me, "An error occurred (IllegalLocationConstraintException) when calling the PutObject operation: The eu-south-1 location constraint is incompatible for the region specific endpoint this request was sent to." I think this error appeared because I put my bucket on eu-south-1 but I try to access it and to create a new object in Seoul, Korea. Also, the AWS document said IllegalLocationConstraintException indicates that you are trying to access a bucket from a different Region than where the bucket exists. To avoid this error, use the --region option. For example: aws s3 cp awsexample.txt s3://testbucket/ --region ap-east-1. (https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html) but this solution might be just for when upload a file from AWS CLI... I tried to change my bucket policy by adding this but doesn't work. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::{BucketName}/*" } ] } I don't know what should I do and why they do not allow access from other regions? How to allow access to create, update and remove an object in my bucket from all … -
Login works in Django Rest Framework but not on frontend
I have the following views: login_view: @api_view(['POST']) def login_view(request): try: user_data = request.data username = user_data["username"] password = user_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) serializer = UserSerializer(user) return Response( { "user":serializer.data, "login": True }) else: return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) except: raise Http404 logout_view: @api_view(['POST']) def logout_view(request): if request.user.is_authenticated: logout(request) return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_403_FORBIDDEN) and fetch function on frontend: const onSubmit = () => { fetch('http://127.0.0.1:8000/api/login/',{ method:"POST", headers: { 'Accept': 'application/json, text/plain', 'Content-Type': 'application/json; charset=UTF-8' }, body: JSON.stringify({ "username": values.Username, "password": values.Password }) }).then((response) => {response.json().then(data => { if(response.ok){ setError(''); console.log(data); } else{ setError(''); setError('Invalid Username or Password'); } })}); }; and the following problem: When I try to sign in on frontend I get an expected response: { user: {id: 4, username: 'Tester_1', date_joined: '2021-12-02T22:38:29.323393Z', trust_index: 0} login: true } but my user is not logged in Rest Framework and I can't use logout view on Frontend: After login on Frontend When I use Rest Framework panel for login, everything works fine, user is logged in and I can use logout view: After login in Rest Framework I've been struggling with this for a while. Any ideas how to solve this problem? -
Django unittest unique constraint failed for no reason
My problem is that when im creating users in unittest, it shows me UNIQUE CONSTRAINT FAILED. In this scenario, It's happening when Im creating user in setUp I have no idea what the problem is, especially that credentials are different for both users in both tests. When im not creating user in setUp it actually works with same credentials from picture above Also it throws me CONSTRAINT error in scenario when I want to create user with same credentials but in different test: I cant also create 2 users with same credentials in 2 different tests. I have absolutely no idea why this is happening. Especially that I've been doing same thing in different project and everything worked. Here is my user model: Please help me out, I am out of ideas why this might be happening. -
take screenshot of a website and return token screenshot for download in django?
i want to take a screenshot from a website and return token screenshot as https for download. I am using Html2Image lib. i am tring this code: def certification1(request, *args, **kwargs): hti = Html2Image() image = hti.screenshot(url='https://www.python.org', save_as='screenshot.png') response = HttpResponse(image, content_type='png') return response but it return url of saved image. like this how can i return token image for download? -
How to handle multiple ModelForm with CreateView (class based views) in Django
I have three models GalleryAlbum, GalleryImage and GalleryVideo. These models have their corresponding ModelForm. I want to handle these forms with a single CreateView model in views.py. Models GalleryImage and GalleryVideohave one-to-many relations with model GalleryAlbum models.py from django.db import models INSTITUTE_CHOICES = [ ("SC", "Shrinathji College"), ("SS", "Shrinathji School"), ] class GalleryAlbum(models.Model): title = models.CharField(max_length=255) date = models.DateField() thumbnail = models.ImageField( upload_to="gallery", default="gallery-album-default.jpg" ) institute = models.CharField(max_length=5, choices=INSTITUTE_CHOICES) def __str__(self): return self.title class GellaryImage(models.Model): album = models.ForeignKey( GalleryAlbum, on_delete=models.CASCADE, related_name="images" ) image = models.ImageField() class GellaryVideo(models.Model): album = models.ForeignKey( GalleryAlbum, on_delete=models.CASCADE, related_name="videos" ) url = models.URLField() forms.py from django import forms from django.forms.fields import DateField from django.forms.widgets import DateInput from gallery.models import GalleryAlbum, GellaryImage, GellaryVideo class GalleryAlbumForm(forms.ModelForm): created = DateField( input_formats=["%Y-%m-%d"], widget=DateInput(attrs={"type": "date"}), ) class Meta: model = GalleryAlbum fields = "__all__" def __init__(self, *args, **kwargs): super(GalleryAlbumForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs["class"] = "form-control" class GalleryImageForm(forms.ModelForm): class Meta: model = GellaryImage fields = "__all__" def __init__(self, *args, **kwargs): super(GalleryImageForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs["class"] = "form-control" class GalleryVideoForm(forms.ModelForm): class Meta: model = GellaryVideo fields = "__all__" def __init__(self, *args, **kwargs): super(GalleryVideoForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs["class"] = "form-control" views.py from django.urls import reverse_lazy … -
Avoid overwriting of cell in excel using python
I run my python file everyday, and each day when I run it it overwrites old previous rows and columns of 'daily.xlsx' excel file. It needs to continue where the last row stopped at. In excel file has 8 columns. (numbers, text, user_id,username,first_name,last_name,date,work). So, 'numbers' column's last number needs to be continued when I run python file. import telebot import openpyxl as xl API_TOKEN = '1111111111:BBBBBBBBBBBBBBBBAAAAAAAAAA-CCCCCCCC' bot = telebot.TeleBot(API_TOKEN) counter = 1 wbAll = xl.load_workbook('C:/Users/Administrator/PycharmProjects/TelegramBot/ActivationKey/daily.xlsx') sheetAll = wbAll['Sheet1'] wbActivation = xl.load_workbook( 'C:/Users/Administrator/PycharmProjects/TelegramBot/ActivationKey/activationKey.xlsx') sheetActivation = wbActivation['Лист1'] # Handle '/start' @bot.message_handler(content_types=['text']) def send_welcome(message): if (message.text[:4] == 'DGGA' or message.text[:4] == "KLAT") and message.text[4:6] == "03" and len( message.text) == 16 and message.text[7] == "1": global counter k = 0 # sending Activation code for i in range(1, sheetActivation.max_row + 1): if message.text == sheetActivation.cell(i, 1).value: print("Activation code place: {}".format(i)) bot.send_message(message.chat.id, sheetActivation.cell(i, 2).value) k += 1 print( "There is a key\tText: {}\tUsername ID: {}\tUsername: {}\tFirstName: {}\tLastname: {}".format( message.text, message.chat.id, message.chat.username, message.chat.first_name, message.chat.last_name)) print(counter) # for Daily report sheetAll.cell(counter, 1).value = counter sheetAll.cell(counter, 2).value = message.text sheetAll.cell(counter, 3).value = message.chat.id sheetAll.cell(counter, 4).value = message.chat.username sheetAll.cell(counter, 5).value = message.chat.first_name sheetAll.cell(counter, 6).value = message.chat.last_name wbAll.save('C:/Users/Administrator/PycharmProjects/TelegramBot/ActivationKey/daily.xlsx') counter += 1 if k == 0: print( "There is no … -
pagination in POST request in django rest api
in one of my django (rest api) project i have one requirement in which mobile team is passing some keys and data including page number through post request, according to that i need to return listing via pagination of their need. i know how to achieve above operation via GET request, but can not use it as mobile team will be passing very lengthy data, which will not be suitable for GET request Here is my code how do i do it via get request: from rest_framework.pagination import PageNumberPagination paginator = PageNumberPagination() paginator.page_size = 10 result_page = paginator.paginate_queryset(songs, request) if result_page is not None: songs_data = [] next = paginator.page.next_page_number() if paginator.page.has_next() else None previous = paginator.page.previous_page_number() if paginator.page.has_previous() else None for item in result_page: # required operation if anyone can help me how do i do it using page number received from the body of POST request, will be appreciated -
xhtml2pdf fonts for latin characters to renders pdf template
I am rendering pdf template dynamically using xhtml2pdf library in Django. The problem is with softening marks like ā, š, ķ etc. I have tried to use all suggested fonts from documentation. I can get fonts but not this softened characters. it looks like preview of pdf from django.template.loader import get_template from xhtml2pdf import pisa from io import BytesIO def quote_preview_pdf(request, pk, pk2): # subscription = stripeInfo(request) user = request.user user_company = UserCompany.objects.get(company_user=user) client_company = user.clientcompanies_set.get(id=pk) quote_nr = user_company.quotenumber_set.get(id=pk2) quote_nr = user_company.quotenumber_set.get(id=pk2) get_quoted_products = CompaniesQuote.objects.filter(quote_nr = quote_nr) get_only_quoted_products = CompaniesQuote.objects.filter(quote_nr = quote_nr).values_list('item__id', flat=True) calc_totals = get_only_quoted_products.annotate( calc_total_profit=(F('item__selling_price') * (1 - (F('discount') / 100)) * F('quantity')) - (F('item__buying_price') * F('quantity')), calc_total_sales_price = (F('item__selling_price') * F('quantity')), calc_total_sales_price_disc = (F('item__selling_price') * (1 - (F('discount') / 100)) * F('quantity')), calc_total_sales_price_vat = (F('item__selling_price') * ( 1 + (F('item__vat') / 100)) * F('quantity')), calc_total_sales_price_vat_disc = (F('item__selling_price')* (1 - (F('discount') / 100)) * ( 1 + (F('item__vat') / 100)) * F('quantity')), calc_total_vat = (F('item__selling_price')* (1 - (F('discount') / 100)) * ( 1 + (F('item__vat') / 100)) * F('quantity')) - (F('item__selling_price') * (1 - (F('discount') / 100)) * F('quantity')) ).aggregate( thesum=Sum('calc_total_profit'), sumsalles=Sum('calc_total_sales_price'), sumsallesdiscount=Sum('calc_total_sales_price_disc'), sumsallesvat=Sum('calc_total_sales_price_vat'), sumsallesvatdiscount=Sum('calc_total_sales_price_vat_disc'), sumvattotal = Sum('calc_total_vat'), ) template_path = 'quote_preview_pdf.html' context = { 'user_company': user_company, 'client_company': … -
Is there any way to set lifetime of refresh token to infinite in django-rest-framework-simplejwt?
I am using django-rest-framework-simplejwt for authentication for my Django project. I have done some research but could not find a solution for that. In the documentation, the format to set refresh token is in time delta. Is it possible to set the refresh token to not expire at all? -
How to escape HTML tags in NextJS
I have Django backend and Nextjs frontend. When I try to render content = models.TextField() from my Django backend to Nextjs frontend <p>{data.content}</p> , I get following rendered: <p>first&nbsp;first&nbs</p> I use django_summernote as the editor. Django has | safe method, that escapes rendering HTML, but I don't know what to use for NextJS. Any help is appreciated -
Django queryset filtering, comparing fields with fields
I would like to filter a queryset where the homecountry is the same as the residentcountry. I try to do something like this: users = User.objects.filter(homecountry=residentcountry) How can I make this work? -
How to add users with username using mozilla-django-oidc to auth_user table upon SSO login?
I'm using mozilla-django-oidc for SSO login with one of my django application. When each user logs in to the application using SSO, then the user is added to the auth_user table of postgres database(if the user is not already saved). The username column of the auth_user table is filled with the hash value of the email id. How can we save the actual value of the email id in the auth_user table instead of the hash value? A direction to achieve this is mentioned here in the official documentation page. -
How to display a ChoiceField's text through Django template to a user?
models.py: class Person(models.Model): title=models.CharField(max_length=11) name=models.CharField(max_length=100) gender=models.CharField(max_length=11) forms.py: class PersonForm(ModelForm): GENDER_SELECT = ( ('f', 'Female'), ('m', 'Male'), ('o', 'Other'), ) TITLE_SELECT = ( ('0', 'Mr.'), ('1', 'Mrs.'), ('2', 'Ms.'), ('3', 'Mast.'), ) title=forms.CharField(widget=forms.RadioSelect(choices=TITLE_SELECT, attrs={'class': 'form-check-inline'})) gender=forms.CharField(widget=forms.RadioSelect(choices=GENDER_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=Person fields='__all__' Now, below are the two ways that I tried to get the data-output to the web-page through but the first one returns nothing and the second one returns the database value of the choice, rather than the text that the user selected. I want the user to see Mr. or Mrs. or Ms. or Mast. and not 0/1/2/3. What is wrong here? template: 1 {% for rp in report %} <td class="design">{% if rp.title == 0 %} Mr. {% elif rp.title == 1 %} Mrs. {% elif rp.title == 2 %} Ms. {% elif rp.title == 3 %} Mast. {% endif %}</td> {% endfor %} 2 {% for rp in report %} <td class="design">{{rp.title}}</td> {% endfor %} -
How to resolve error code: RelatedObjectDoesNotExist
class Following(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='following', unique=False, verbose_name=('User'), on_delete=models.CASCADE) following_user = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name=('Following'), related_name='following_user') created_on = models.DateTimeField(default=timezone.now) class FollowingSerializer(serializers.ModelSerializer): new_following = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),required=True,write_only=True) class Meta: model = Following fields = [ 'id', 'user', 'following_user', 'new_following', 'created_on' ] read_only_fields = ['following_user'] def create(self, validated_data): user = validated_data['user'] new_following = validated_data['new_following'] user.following.following_user.add(new_following) new_following.followers.following_user.add(user) return user.following class FollowingAPIView(mixins.CreateModelMixin, mixins.DestroyModelMixin,generics.GenericAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = FollowingSerializer def get_queryset(self): queryset = Following.objects.all() return queryset def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(self, request, *args, **kwargs) -
Django Azure Logout Session
Is there any formal way to log out of both Django + Azure AD B2C Session? Clicking "Logout" redirects to the default logout page. After that, clicking "log back in" or simply entering the home page in the url takes the user right back to the home page because the Azure session is not actually ended. Using django-oidc-provider + mozilla-django-oidc packages. Azure App Config Front Channel URL: https://my-site:myport/admin/logout Settings.py OIDC_SESSION_MANAGEMENT_ENABLE = True OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY = 'test' OIDC_OP_LOGOUT_URL_METHOD = "testmodule.auth.logout" logout function def logout(request): print("custom logout request reached") **# Never Reached** # I'm not sure if this is the correct token to be accessing id_token = str(request.COOKIES['csrftoken']) id_token_hint = f'id_token_hint={id_token}' redirect_url = "https://login.windows.net/my-tenant-id/oauth2/v2/logout?" redirect_url = redirect_url + id_token_hint + "&post_logout_redirect_uri=" + request.build_absolute_uri("/admin/logout/") print(f'redirect_url: {redirect_url}') return redirect_url urls.py class LogoutView(OIDCLogoutView): print("LogoutView Reached") def get(self, request): print("Get Call") **# Never Reached** return self.post(request) def post(self, request): print("Post Call") **# Never Reached** """Log out the user.""" logout_url = self.redirect_url #if request.user.is_authenticated: print("Reached Authenticated") **# Never Reached** # Check if a method exists to build the URL to log out the user # from the OP. logout_from_op = self.get_settings('OIDC_OP_LOGOUT_URL_METHOD', '') if logout_from_op: logout_url = import_string(logout_from_op)(request) # Log out the Django user if they were logged in. … -
Soap signature with JKS in Django
I am working on a project using Django and i need to send a soap request but i have to sign it using a 'JKS' file and it's password and alias. I've tried working with suds and zeep packages. But I can't find any example in python to help me understand how to do that. Can some one help me? -
Elastic Beanstalk Django app deployment 502 Bad Gateway Server not running (No module named: 'application')
I deployed an application to AWS via Elastic Beanstalk, and when I finished pushing the project to aws (Elastic Beanstalk), I am faced with perpetual 502 Bad Gateway errors (probably because the Django app server never actually started, and Nginx can't proxy us through). Looking at the logs, I found a weird error that seems very specific, and erroneous. It looks like so: Traceback (most recent call last): Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Dec 13 09:00:10 ip-172-31-35-65 web: worker.init_process() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/workers/gthread.py", line 92, in init_process Dec 13 09:00:10 ip-172-31-35-65 web: super().init_process() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process Dec 13 09:00:10 ip-172-31-35-65 web: self.load_wsgi() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Dec 13 09:00:10 ip-172-31-35-65 web: self.wsgi = self.app.wsgi() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Dec 13 09:00:10 ip-172-31-35-65 web: self.callable = self.load() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load Dec 13 09:00:10 ip-172-31-35-65 web: return self.load_wsgiapp() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Dec 13 09:00:10 ip-172-31-35-65 web: return util.import_app(self.app_uri) Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/util.py", … -
Django DATABASES settings
I understand if you connect to your MongoDB database via pymongo, you should remove the DATABASES section in your settings.py file, which I have done, but I get this: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Apparently, pymongo does not replace a relational database with MongoDB. It is simply a facility allowing you to access a MongoDB in addition to your regular database; meaning I still need my databases settings... I know my connection string and database name and collection name, but what should the DATABASES section look like in my settings.py file? On https://docs.djangoproject.com/en/2.0/ref/settings/#databases and a few other posts and articles, only settings for sqlite3 and postgresql and mysql and oracle are mentioned. I cannot seem to find the right setting for 'ENGINE': 'django.db.backends.mongodb' How can I use a MongoDB database then? What goes in the xxx.backends.xxx section? -
What is the proper method to pass data in class-based django views?
I'm looking for a proper or a basic method to pass the result of a filter in a class to another page which is in another class and temporarily use it for a purchase class home(View): def get(self, request): return render(request,'home.html') def post(self, request): # rm = room.objects.all().filter(#filter) class results(View): def get(self, request): rm #from home return render(request,'result.html',{'rm':rm}) def post(self, request): # -
How to use prefetch_related 2 times?
view.py def CompanyAdDetail(request, post_id): ad_detail = get_object_or_404(Ad_company, idx=post_id) is_display = ad_detail.is_display if is_display != '1': return redirect('/') ad_detail.hits += 1 ad_detail.save() if ad_detail.user_idx == request.user: #작성자가 글을보면 q = Q() q &= Q(project_idx = post_id) apply_list = Ad_company_apply.objects.filter(q).select_related('user_idx').prefetch_related('userportfolio').order_by('-idx') else: apply_list = None return render(request, 'project/company_ad_detail.html', {"ad_detail":ad_detail, "apply_list":apply_list}) model.py class Ad_company_apply(models.Model): idx = models.AutoField(primary_key=True) project_idx = models.ForeignKey( Ad_company, db_column='project_idx', on_delete=models.CASCADE ) user_idx = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE, ) content = models.TextField() date = models.DateTimeField(default=datetime.now, blank=True) budget = models.BigIntegerField() term = models.IntegerField() class UserPortfolio(models.Model): idx = models.AutoField(primary_key=True) user_idx = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE ) subject = models.CharField(max_length=255) client_name = models.CharField(max_length=255) client_service = models.CharField(max_length=255) client_category = models.CharField(max_length=255) start_date = models.DateTimeField() end_date = models.DateTimeField() content = models.TextField() write_date = models.DateTimeField(auto_now = True) update_date = models.DateTimeField(auto_now = True) is_file = models.CharField(max_length=1) class Meta: managed = False db_table = 'account_user_portfolio' I want to count apply list in users portfolio. but I think I need to use prefetch_related 2 times. and I did it. but Always showed error. is an invalid parameter to prefetch_related() How can I use this as good? -
How to filter Multiselect Field in django (Separate comma)
my Model class Dictionary(): ALLERGIES = ( (0, 'none'), (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'i'), (10, 'x'), (11, 'y'), (12, 'z'), ) ... allergies = MultiSelectField(default=0, null=True, blank=True, choices=ALLERGIES, max_choices=12) My first tried. dictionaries.filter( Q(allergies__isnull=False) & Q(allergies__icontains=pet_allergy)) example dictionaries data id allergies 1 "1,2,3,4" 2 "1,2,10" 3 "4,5,6,7,10" 4 "6,8,12 5 null pet_allergy = 1 I expected id 1 and 2 to be returned. However, id 1, 2, 3, and 4 returned contrary to my expectation. Because sql was called like %1%. My second tried class Dictionary(): ... def get_allergies(self): if self.allergies: return str(self.allergies).split(',') else: return None dictionaries.filter( Q(allergies__isnull=False) & Q(get_allergies__in=pet_allergy_id) ) >> Cannot resolve keyword 'get_allergies' into field. Is there any good way to solve this problem? P.S. My DB is mariadb. / django = v3.1 -
Which one is better structure for FK relation deletion in django?
class Address(models.Model): old_address = models.CharField(max_length=250) new_address = models.CharField(max_length=250) bjdongName = models.CharField(max_length=20) ... 1. class Listing(models.Model): title = models.CharField(max_length=25) address = models.OneToOneField(Address, on_delete=models.SET_NULL, related_name="listing") def delete(self, *args, **kwargs): address = self.address super().delete(*args, **kwargs) address.delete() 2. class Listing(models.Model): title = models.CharField(max_length=25) class ListingAddress(Address): listing = models.OneToOneField(Listing, on_delete=models.CASCADE) Q1. Which structure is better ? Q2. If I want to delete OneToOneField parent, override delete method or using signal post_delete. But are those performances same? Only when I need to delete_bulk, I need to use signal? Is there another reason using signal delete? -
how exclude an annotation from groups by (values) calculation - django
i'm try to show profit and loss, in a query which is group by date(TruncDay) , here is what im trying to implement class CustomerInvoice(models.Model): seller = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items_model = models.ManyToManyField(Item,through='InvoiceItem') created_at = models.DateTimeField(auto_now_add=True) class InvoiceItem(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') quantity = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=2) class Item(models.Model): item = models.CharField(max_length=40) quantity = models.IntegerField() buying_price = models.DecimalField(max_digits=30,decimal_places=2) i want to get the daily income, which is subtraction between price from InvoiceItemand buying price from Item if greater than 0 it will be income, but if buying price greater than price it should be loss, but for the entire day, sometimes happens in 10 invoice, we have only one item sold the buying price greater than the price, i want to count it, show that amount of money, but in the group by, in the 10 invoices for example income in 9 invoices are : 100, but in the other invoices which is sold which is buying price : 10, price:9 , it will show the income to 99, it shows nothing in the loss return InvoiceItem.objects.annotate(day=TruncDay('invoice__created_at')).values('day').annotate( paid_price=Sum( (F('price') * F('quantity')),output_field=DecimalField(max_digits=20,decimal_places=3)), storage_price=Sum( F('item__buying_price') * F('quantity'),output_field=DecimalField(max_digits=20,decimal_places=3)), income=Case( When(paid_price__gte=F('storage_price'),then=F('paid_price')-F('storage_price')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), ).annotate( loss=Case( When( storage_price__gt=F('paid_price'),then=F('storage_price') - F('paid_price')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), ).order_by('-day') but i …