Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm having trouble implementing configuration for a MySQL connection pool in Django
Before I had a simple connection, but this was closed due to the high volume of traffic that exists in the application, I am trying to configure it like this: from django.conf import settings from mysql.connector import Error from mysql.connector import pooling poolname="mysqlpool" poolsize=3 varHost='localhost', varUser=settings.DATABASES['default']['USER'], varPasswd=settings.DATABASES['default']['PASSWORD'], varDB=settings.DATABASES['default']['NAME'], try: connection_pool = pooling.MySQLConnectionPool( pool_name="pynative_pool", pool_size=5, pool_reset_session=True, host=varHost, database=varDB, user=varUser, password=varPasswd) print("Printing connection pool properties ") print("Connection Pool Name - ", connection_pool.pool_name) print("Connection Pool Size - ", connection_pool.pool_size) connection_object = connection_pool.get_connection() if connection_object.is_connected(): db_Info = connection_object.get_server_info() print("Connected to MySQL database using connection pool ... MySQL Server version on ", db_Info) cursor = connection_object.cursor() cursor.execute("select database();") record = cursor.fetchone() print("Your connected to - ", record) except Error as e: print("Error while connecting to MySQL using Connection pool ", e) finally: if connection_object.is_connected(): db_Info = connection_object.get_server_info() print("Connected to MySQL database using connection pool ... MySQL Server version on ", db_Info) cursor = connection_object.cursor() cursor.execute("select database();") record = cursor.fetchone() print("Your connected to - ", record) and it throws me the following error: connection_pool = pooling.MySQLConnectionPool( File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\pooling.py", line 156, in __init__ self.set_config(**kwargs) File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\pooling.py", line 196, in set_config raise errors.PoolError( mysql.connector.errors.PoolError: Connection configuration not valid: 'tuple' object has no attribute 'strip' Does anyone know how … -
Python, Django: Trying to understand async_views (Django > 3.0)
right now I'm trying to understand how to call two models with python/django async. Therefor I found a explanation online that seems to work but stills throws an error in command. models.py class Movies(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) class Series(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) functions.py from .models import Movies, Series import asyncio from asgiref.sync import sync_to_async @sync_to_async def get_movies_async(): asyncio.sleep(2) qs = Movies.objects.all() print(qs) @sync_to_async def get_series_async(): asyncio.sleep(5) qs = Series.objects.all() print(qs) views.py from django.http import HttpResponse import asyncio, time from .functions import get_movies_async, get_series_async async def index(request): start_time = time.perf_counter() await asyncio.gather(get_movies_async(), get_series_async()) print(f"Estimated time: {time.perf_counter() - start_time}") return HttpResponse("Index view") According to the explanation I should receive the data in about 5 seconds, but instead the data loads in way under a second (0.009...something) and I'm getting two RuntimeWarnings: RuntimeWarning: coroutine 'sleep' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback According to the explanation this shouldn't happen and unfortunately I couldn't find a proper solution online. Can someone tell me what I am missing here? -
IntegrityError when trying to create a one to many relationship in Python Django
I am a beginner developer, working on an app that displays some walks, and each walk should have an option for users to post reviews. I am trying to create a relationship between Walk and Review models. Each Walk should have multiple Reviews, but each Review should only belong to one Walk. I'm trying to create a one-to-many relationship, but keep getting IntegrityError like so: django.db.utils.IntegrityError: The row in table 'walks_walk' with primary key '1' has an invalid foreign key: walks_walk.reviews_id contains a value '2' that does not have a corresponding value in reviews_review.id. Here are my models: Walk from django.db import models from reviews.models import Review class Walk(models.Model): # walk ID automatically generated walk_name = models.CharField(max_length=100) walk_reviews = models.ForeignKey(Review, on_delete=models.CASCADE, default="No reviews yet") Review from datetime import date from operator import mod from statistics import mode from tkinter import CASCADE from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.contrib.auth.models import User # change to updated bespoke User model vs built-in class Review(models.Model): # Review ID auto-created author = models.ForeignKey(User, on_delete=models.CASCADE, default="") title = models.CharField(max_length=100) body = models.TextField(max_length=3000) I have tried several variations and cleared out my test database data, but the issue persists. What can be the … -
How to use queryset with distinct to avoid duplication value in label_from_instance?
I want to use queryset with distinct() to avoid duplication value in label_from_instance. But then I have an error like below. 'str' object has no attribute 'name' How could I use queryset with distinct() in label_from_instance? Here are the code in forms.py: from django.forms import ModelChoiceField class NameChoiceField(ModelChoiceField): def label_from_instance(self, obj): return f'{obj.name}' class MS_KansokujoForm(forms.ModelForm): code = NameChoiceField(queryset=MyModel.objects.all().values_list('name',flat=True).order_by('name').distinct()) python 3.8 Django 3.2 Mysql 5.7 -
CloudCube and Boto3 - list content of the Objects
I am encountering you with the request for help with listing the objects in my CloudCube bucket. I am developing Django application hosted on Heroku. I am using the CloudCube add-on for persistent storage. CloudCube is running on AWS S3 Bucket and CloudCube provides private Key/Namespace in order to access my files. I use the boto3 library to access the bucket and everything works fine when I want to upload/download the file; however, I am struggling with the attempts to list objects in that particular bucket with the CloudCube prefix key. On any request I receive AccessDennied Exception. To access the bucket I use the following implementation: s3_client = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, endpoint_url=settings.AWS_S3_ENDPOINT_URL, region_name='eu-west-1') s3_result = s3_client.list_objects(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Prefix=settings.CLOUD_CUBE_KEY) if 'Contents' not in s3_result: return [] file_list = [] for key in s3_result['Contents']: if f"{username}/{mode.value}" in key['Key']: file_list.append(key['Key']) Does anyone have clue what do I miss? Thank you in advance! -
Messed up trying to install backports, ending killing dnf and yum
so everything is in the title, im working on fedora30 os, on a django project, and for no reason i couldnt start another one with django-admin startproject. 1 - i got a message telling me backports need to be installed, 2- i did the command to instal it, got a error telling me its not possible for whatever reason. 3 (where the fun begins) - got tired of it, proceded to do a rm-rf on python2.7 and 3.4 folder in order to keep only python 3.9 4 - reinstalling python 5 - dnf and yum missing, and now im starting to think i really messed up all of this i dont mind if someone can help me fixing this problem what i got in the command prompt right after using any dnf or yum command : Traceback (most recent call last): File "/usr/bin/yum-config-manager", line 75, in <module> from dnf.cli import main ModuleNotFoundError: No module named 'dnf' -
how to use a models and create a form to save in the data_base
so, i created this models, like person and the text, i want to create a form in html and call these models and save then in the data base. Note: every text must have the person ID, the person ID is like the author, you know? from django.db import models from django.utils import timezone #onde é trabalhado a parte de dados # Create your models here. from django.utils import timezone # class Text(models.Model): title = models.CharField(max_length=255) description = models.TextField() datesss = models.DateTimeField(default=timezone.now) Person = models.ForeignKey(Person, on_delete=models.DO_NOTHING) def __str__(self): return self.description class Person(models.Model): name = models.CharField(max_length=255)# charfiel é STR surname = models.CharField(max_lenght=255) user = models.CharField(max_lenght=255) #telefone = models.CharField(max_length=255, blank=True)#blank se torna opcional email = models.CharField(max_length=255) password = models.CharField(max_length=255) #description = models.TextField(blank=True) photo = models.ImageField(blank=True, upload_to='pictures/%Y/%m/%d') #criar pasta pelo dia mês ano def __str__(self): return self.name -
how to find a way for a continuous cycle? using django?
new price is the price taken from the marketcapapi. I would like that every time the user buys coins, the coins are transferred to the ALGO_wallet leaving n_ALGO_coin at zero (= 0). The first time the user buys, everything is ok, the transfer is done, while the second time the data remains both in n_ALGO_coin and also in ALGO_wallet. I tried with a for loop but it tells me that the object is no interable def buyalgomkt(request): new_price = algoValue() if request.method == "POST": form = PurchaseForm(request.POST) if form.is_valid(): form.save(commit=False) profile = Profile.objects.get(user=request.user) if profile.USD_wallet > 0 and form.instance.max_spend_usd < profile.USD_wallet: form.instance.purchased_coin = form.instance.max_spend_usd / form.instance.price_mkt profile.n_ALGO_coin += form.instance.purchased_coin profile.USD_wallet -= form.instance.max_spend_usd profile.ALGO_Wallet += profile.n_ALGO_coin profile.n_ALGO_coin = profile.ALGO_Wallet - profile.n_ALGO_coin form.save() profile.save() name = request.user name.save() messages.success(request, 'Your order has been placed and processed') else: messages.warning(request, 'You do not have enough money') return redirect('purchase') else: return HttpResponseBadRequest() else: form = PurchaseForm() return render(request, 'coinmarketalgo/purchase.html', {'form': form, 'new_price': new_price}) .. how can I do? class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) ips = models.Field(default=[]) subprofiles = models.Field(default={}) n = random.randint(1, 10) n_ALGO_coin = models.FloatField(default=algoValue() * n) ALGO_Wallet = models.FloatField(default=0) purchased_coin = models.FloatField(default=0) USD_wallet = models.FloatField(default=10000) profit = models.FloatField(default=0) class … -
Attribute Error 'list' object has no attribute 'get' in Django
I'm facing a issue while getting the data from the 'POST' method I'm getting an error as Attribute Error at api/Data/SaveUserResponse/ 'list' object has no attribute 'get' Django . The response which I get in the payload [{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":150,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"},{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":151,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"}] Views.py: @api_view(['POST',]) def SaveUserResponse(request): if request.method == 'POST': auditorid = request.data.get('AuditorId') print('auditorid---', auditorid) ticketid = request.data.get('TicketId') qid = request.data.get('QId') answer = request.data.get('Answer') sid = '0' TicketType = request.data.get('TicketType') TypeSelected = request.data.get('TypeSelected') agents = request.data.get('Agents') supervisor = request.data.get('Supervisor') Comments = request.data.get('Comments') action = request.data.get('Action') subfunction = request.data.get('AuditSubFunction') region = request.data.get('AuditRegion') print('Region---', region) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s,@TicketType=%s,@TypeSelected=%s,@agents=%s, @supervisor =%s, @Comments=%s, @action=%s, @subfunction=%s, @region=%s', (auditorid,ticketid,qid,answer, sid,TicketType, TypeSelected, agents, supervisor, Comments, action, subfunction,region)) return Response(True) urls.py: path('Data/SaveUserResponse/', SaveUserResponse, name='SaveUserResponse'), -
Apply django migration if constraint doesn't exist yet
I want to add a constraint to my django model. I want this migration to do nothing if the constraint has already been added (manually in sql, not by django). I know how to check if constraint is already applied thanks to this question. However, how could I skip the "add constraint" operation in my migration file based on this condition? Do I need to create a RunPython operation or can I rely on django migration objects? I am using postgres. -
how to apply constraints on Django field within the instances associated with the user
I am a django beginner and making a todo app for practice, the functionality I want to achieve is that, when a user create a task,Only the time field should be unique about all of his tasks, I have done (unique=True) In the time field in model but that make it unique all over the database, but I want it to be unique only with the tasks associated with the user. the view is below: @login_required(login_url='login') def home(request): tasks = Task.objects.filter(name__username=request.user.username) form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.name = request.user obj.save() return redirect('home') else: print(request.POST) print(request.user.username) messages.warning(request, 'Invalid Data!') return redirect('home') context = {'tasks' : tasks} return render(request, 'task/home.html', context) task model: class Task(models.Model): choices = ( ('Completed', 'Completed'), ('In Complete', 'In Complete'), ) name = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) task = models.CharField(max_length=200, null=False, blank=False) time = models.TimeField(auto_now_add=False, blank=True) status = models.CharField(max_length=200, choices=choices, null=True, blank=False) def __str__(self): return self.task def get_task_author_profile(self): return reverse('profile') as you can see, I want to show the task that the logged in user has added. the form is: class TaskForm(ModelForm): class Meta: model = Task fields = '__all__' exclude = ['name'] the functionality I talked about … -
Bootstrap CDN overrides custom CSS in Django
I have tried everything mentioned on the internet but yet bootstrap CDN overrides the custom CSS file. The HTML file: {%extends 'movies/base.html'%} {%block content%} {% load static %} <!DOCTYPE HTML> <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <div class="section"> <h1>Recommend Me:</h1> <form action="recommendation" method="post"> {% csrf_token %} <input type="text" name="emotion" /> <button type="submit" name="button">Find</button> </form> <div class="video-container"> <div class="color-overlay"></div> <video autoplay loop muted > <source src="{% static 'movies/intro.mp4' %}" type="video/mp4"> </video> </div> </div> <div class="shows"> <h2 class="mt-5">Shows you might like:</h2> <br> <div class="row"> {%for tvshow in tvshows%} <div class="col-lg-5 col-md-6"> <a href="{{ tvshow.url }}"> <img src="{{ tvshow.image.url }}" class="img-fluid mb-2"> </a> <h3>{{ tvshow.title }}</h3> </div> {% endfor %} </div> </div> </body> </html> {%endblock%} I tried adding the attribute !important in CSS but yet it didn't work. CSS file: *{ box-sizing: border-box; margin: 0; padding: 0; font-family: 'Poppins'; } .video-container video{ position: absolute; top: 0; left: 0; width: 100%; height: 570px; object-fit: cover; z-index: 1; opacity: 0.8; } .section h1{ position: relative; text-align: center; font-size: 4rem; padding: 20px; margin: 15px; top: 100px; z-index: 2; opacity: 0.6; } .section form{ position: relative; … -
Django admin count numbers of rows before adding a new data in StackedInline mode
In my django project i have a model related to a main model like this one: class Device_Docs(models.Model): id = models.AutoField(primary_key=True) master_id = models.ForeignKey(Device, on_delete=models.CASCADE) device_file = models.FileField(upload_to='uploads/', validators=[FileExtensionValidator(['pdf', 'jpg', 'txt', 'png', 'jpeg']), validate_fsize], verbose_name="Select File", help_text='Allowed formats are PDF, JPG, JPEG, TXT, PNG, max size 3Mb') title = models.CharField(max_length=250, help_text='Document title') description = models.TextField(default='', verbose_name="Descrizione", null=True, blank=True) load_data = models.DateField(default=datetime.now(roma).strftime("%Y-%m-%d %H:%M:%S.%f"), verbose_name="Load data") owner = models.ForeignKey('accounts.CustomUser', related_name='odevdocs', on_delete=models.CASCADE) ... Now i would to show in my admin, for the Device model (main model) using StackedInline option both models data: class DocsInline(admin.StackedInline): model = Device_Docs extra = 1 @admin.register(Device) class DeviceModelAdmin(admin.ModelAdmin): list_display = ('mac_id', 'short_name', 'proj_type', 'polling_interval', 'active', 'autoupdate', 'save_date') list_filter = ('polling_interval','proj_type', 'active', 'autoupdate') search_fields = ('short_name', 'save_date' ) ordering = ('-save_date', 'mac_id') readonly_fields = ('mac_id', ) inlines = [PortinInline, DocsInline] def has_delete_permission(self, request, obj=None): return False def get_form(self, request, obj=None, **kwargs): self.exclude = ("owner", "save_date") form = super(DeviceModelAdmin, self).get_form(request, obj, **kwargs) return form Ok all works good, now my question is, how can i control the numbers ofrows already entered about Device_Docs data before save? For exmple i would block the possibility about insert data if in model there are more then 5 records with the same master_id … -
Django run a command once the server starts [duplicate]
I have a setup function which can only be run once the app has started and is answering requests, but which I would like to run only once when the server starts. Is there a hook or other way to run a setup function after Django has completed the "peforming system checks..." and gotten to the point where it has emitted "Quit the server with CONTROL-C."? -
Django model tab-complete in ipython
I wish to use ipython to create a custom command-line interface to query Django model objects. So for example I'd like to type: my_models.MyModelClass.h <TAB> And have all of the elements of the MyModelClass table that start with "h" be used as the tab complete. I could achieve this by creating a startup script and creating an object heirachy which matches the table structure, however that will be slow, and I'd prefer to only create the request on demand. Is there a more direct way to use ipython's tab complete, for example a function which is called to get the tab complete list when tab is invoked? -
docker-compose can't find django-admin in $PATH, but I can run django-admin commands separately
I'm trying to test a django app in a docker image. I have followed the tutorial until the it starts the django project. When I run, docker-compose run web django-admin startproject composeexample . I get Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "django-admin": executable file not found in $PATH: unknown ERROR: 1 It's weird because I can run django-admin createproject ... seperately. Any thoughts? I have added the ..\python39\scripts in the path. Also I have python 3.9.10 from the windows store. -
Django-CMS slug in if statement in HTML
I am trying to write an if statement to change what the link links to, based on the slug URL. I get an error in the if_statement. Shouldn't this work? <div> {% if page_attribute "slug" == 'hjem' or page_attribute "slug" == 'home' %} <a href="/no/">NO</a> / <a href="/en/">EN</a> {% else %} <a href="/no/{% page_attribute 'slug' %}">NO</a> / <a href="/en/{% page_attribute 'slug' %}">EN</a> {% endif %} </div> -
Django admin login wont respect custom next param
I want to redirect to a custom page (next='reports/fooreport') after Django admin login. I have a page in Django to be accessed by authenticated users. If I hit the URL let's say /reports/fooreport and I am redirecting the user to admin login with next='/reports/fooreport' using HttpResponseRedirect('%s?next=%s' % (reverse('admin:index'), '/reports/fooreport')) After successful login, Django is not redirecting to the next URL. However, it works pretty well for its internal apps like if I hit any admin page without login it appends in URL with next param and post login it redirects to this URL. Is there anything we can do to make it work? -
How do I filter wagtail images by a queryset?
I have following page structure: blog_ |_contributor 1 |_Post 1 |_Post 2 |_contributor 2 |_Post 3 |_Post 4 |_Post 5 Editors take the content provided by contributors and upload that content on their behalf. Editors can therefore create posts as children of each contributor. To avoid accidental copyright infringements in the use of image materials, I would like the ImageChooserPanel to only display images uploaded to the pages of a given contributor, i.e. when a post is created as a child of a given contributor, the ImageChooserPanel should only display images uploaded to the pages of that contributor (or allow additional image upload). A manual solution would be to manually create a collection for each contributor and upload and select from that section. However, that would create too much overhead, given a high number of contributors. I've tried to figure out a solution with the use of a custom image model that contains a foreignkey to the contributor in combination with a construct_image_chooser_queryset hook, but have so far fallen short. -
Summation of fields in SQL Query or getting results and then looping in code?
I have more than 100K rows in my table. I want to get the sum of data with id='x' (Filtered data would be 50-100 rows). What should I prefer? SQL Sum or get the filtered data and sum the data using loop. Option 1 query = 'SELECT SUM('field_1) as qunatity_1, SUM(field_2) as quantity_2....SUM(field_15) as quantity_3 from BOOKS where id=10' Should I just hit this query and get the required data Option 2 query = 'SELECT field_1, field_2...field_15 from BOOKS where id=10' loop on the received rows and sum the fields to get required data -
How to perform left join in django?
i like to join two tables using left join operation. this is what i like to do: SELECT * FROM orders LEFT JOIN products ON (orders.product_id = products.id); my model classes: class Orders(models.Model): name = models.CharField(max_length=100, null=False, blank=False) qty = models.IntegerField(null=False, blank=False) product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customers, on_delete=models.CASCADE) class Meta: db_table = 'orders' class Products(models.Model): name = models.CharField(max_length=100, null=False) qty = models.IntegerField(default=0, null=True) price = models.FloatField(null=True, default=0) description = models.CharField(max_length=500, null=True, default=None) class Meta: db_table = "products" -
How can increment a variable value in jinja
How can increment a variable value in jinja (django template language).. {% with a=0 %} {% with b=4 %} {% endwith %} {% endwith %} i used above code to assign value to a variable. i want to increment it with 4. -
how to pass SQL output parameter in rest framework
I'm trying to pass the Output parameter @response in Django views but I couldn't able to achieve it. I have tried two approaches here, what I have tried views.py: approach1: @api_view(['POST']) def FetchSuggestionAuditAgent(request): if request.method == 'POST': agents = request.data.get('Agents') Output = request.data.get('Answer') AuditorId = request.data.get('AuditorId') TicketId = request.data.get('TicketId') QId = request.data.get('QId') Answer = request.data.get('Answer') print('Agents--', agents) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_FetchSuggestionAuditAgent] @agents=%s, @response=%s', (agents, '')) return Response({ 'Agents':agents }) approach2: @api_view(['POST']) def FetchSuggestionAuditAgent(request): if request.method == 'POST': agents = request.data.get('Agents') sql = """\ DECLARE @response nvarchar(max), @agents nvarchar(max); EXEC [dbo].[sp_FetchSuggestionAuditAgent] @agents = ?, @response = @out OUTPUT; SELECT @response AS the_output; """ params = (agents, ) cursor = connection.cursor() cursor.execute(sql, params) rows = cursor.fetchall() while rows: print(rows) if cursor.nextset(): rows = cursor.fetchall() else: rows = None return Response(True) SQL: CREATE [dbo].[sp_FetchSuggestionAuditAgent] @agents nvarchar(max),@response nvarchar(1000) OUTPUT AS BEGIN set @agents = replace(@agents,' ', '%') select @response = FullName from ( select FullName from tblusers where IsActive=1 union all select FullName from tblusers where IsActive=0 and UserRole='Snowuser' )as a where FullName like @agents--('%'+@agents+'%') order by FullName desc END -
use of mixins class defined in Django rest framework
What is the actual use of Mixins class? I don't really get it. All the mixins classes like CreateModelmixin, Listmixin, etc features are already available in class-based view like ListCreateApiView. For eg: class ExampleView(ListCreateAPIView DestroyAPIView, RetrieveUpdateAPIView): queryset = Example.objects.all() serializer_class = ExampleSerializer pagination_class = CustomPageNumberPagination Using mixins we can do it by following: class ExampleView(ListAPIView, mixins.CreateModelMixin): queryset = Example.objects.all() serializer_class = ExampleSerializer pagination_class = CustomPageNumberPagination When I check https://www.cdrf.co/ I see the methods that are available in CreateModelMixing are the following: def create(self, request, *args, **kwargs): def get_success_headers(self, data): def perform_create(self, serializer): These methods are already available in ListCreateApiView, then why Django went to create this useless class?? -
Downloaded file is stored in 2 directories
problem occurs with the code below def creation_download(request, campaign_id, downloaded_file): bucket_file = downloaded_file gcs = GCPStorage() gcs.download_file(GCP_STORAGE_BUCKET_NAME, bucket_file) response = HttpResponse(bucket_file, content_type='application') response['Content-Disposition'] = 'attachment' return response I just want my file to be downloaded only to user/download directory, but it also being downloaded to my repository directory (where manage.py is stored and where is base_dir pointed). How do i manage only to store it in download directory?