Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How can I make a custom admin view that edits a JSON file, rather than a model?
My goal is to add an extra view to my admin page that edits a json file, rather than my database. The documentation says that custom views can be added by overriding the get_urls() method in my custom AdminSite class. It goes on to say: Any view you render that uses the admin templates, or extends the base admin template, should set request.current_app before rendering the template. It should be set to either self.name if your view is on an AdminSite or self.admin_site.name if your view is on a ModelAdmin. As you can see here, I tried doing just that (see the first line of the json_admin_view() method): import json from django.contrib.admin import AdminSite from django.urls import path from django.shortcuts import render from .forms import JsonForm JSON_FILE = 'json_app/data.json' class MyAdminSite(AdminSite): site_header = "JSON App Administration" def get_urls(self): urls = super().get_urls() my_urls = [ path('json_admin/', self.admin_view(self.json_admin_view), name='json_admin') ] return my_urls + urls def json_admin_view(self, request): request.current_app = self.name # This doesn't seem to do anything context = {} with open(JSON_FILE, 'r') as read_data: json_data = json.load(read_data) if request.method == 'POST': form = JsonForm(request.POST) if form.is_valid(): with open(JSON_FILE, 'w') as write_data: json.dump(form.cleaned_data, write_data) context.update({'form_saved': True}) else: form = JsonForm({ 'fname': json_data['fname'], … -
How to avoid problem during deployment for changing environment in django?
currently I am working with a Django project in pychram. everything was fine. then I installed pandas through settings. after that when I tried to import pandas it caused an error. that's why I have changed the environment to my existing conda environment. now I have to run the server from Anaconda terminal and now everything is going fine. my question is will I face any problem during deployment for changing the environment? -
django ajax keep appending the same result
Hello guys i sucessfully create the ajax that update the table without refreshing, but my problem is that the ajax keep appending the same result everytime it run. my question is that how can i fix this so that the ajax only appending the new result to the table instead appending the same result over and over again? people tell me to use the .html method but i dont think that what i want because if i use this it will change the whole display to the get_more_table.html destination.html {% load staticfiles %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <table id="_appendHere" class="table table-striped table-condensed"> <tr> <th>name</th> <th>desc</th> <th>status</th> <th>price</th> </tr> {% for i in dest %} <td>{{ i.name|upper }}</td> <td>{{ i.desc|capfirst }}</td> <td>{{ i.status|capfirst }}</td> <td>{{ i.price | capfirst}}</td> </tr> {% endfor %} </table> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script> <script> function updateTable(){ console.log("hello") $.ajax({ method: "GET", url: "get_more_table", success: function(data) { console.log(data) $("#_appendHere").append(data); } }) } var interval = setInterval(function () { updateTable(); }, 10000); </script> </body> </html> view def record_table(request): dest = Destination.objects.all() return render(request,"destination.html",{'dest':dest}) def get_more_table(request): … -
Assertion error django-rest-framework nested serialzer create method
I'm getting issue on creating an object through nested serializer. Assertion error: .create() method does not support writable nested fields by default. class OrderProductSerializer(serializers.ModelSerializer): class Meta: model = OrderProducts fields = '__all__' class OrderSerializer(serializers.ModelSerializer): order_products = OrderProductSerializer(many=True) class Meta: model = Order fields = (...fields of order model, 'order_products') def create(self, validate_data): products = validated_data.pop(order_products) instance = Order.objects.create(**validate_data) for product_data in products: instance = OrderProducts.objects.create(order=order, **product_data) return order I'm unable to find the error up here -
Django and Chart.js: Line-Chart with multiple Datasets
I'm trying to create a Line-Chart with chart.js and multiple datasets (the amount of datasets can change during it's lifetime): ...from my "views.py": label = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] coworker = ['John Doe', 'Jane Doe', 'Michael Smith'] data = [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [3, 4, 2, 1, 5]] If this would be a line chart with only one list of data and just one coworker, my chart usually looks like this: <script> $(document).ready(function(){ var ctx = document.getElementById('myChart1').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: {{ label|safe }}, datasets: [{ label: 'Some text...', data: {{ data|safe }}, backgroundColor: ..., borderColor: ..., borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true, } }], } } }); }); I already tried to loop through my datas like this... <script> $(document).ready(function(){ var ctx = document.getElementById('myChart1').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: {{ label|safe }}, datasets: [{ label: [{% for i in label%}"{{ i }}",{% endfor %}], data: [{% for j in data %}{{ j }}, {% endfor %}],, backgroundColor: ..., borderColor: ..., borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: … -
Skipping Django test database creation for read-only, externally managed, high-security, big databases
We need to use real data for one of our many external data sources during Django tests: data is externally managed and read-only data is accessed through manage.py inspectdb generated ORM classes data is highly sensitive and we are not allowed to store fixtures of the actual data tables are legacy design and will be phased out, hundreds of tables with complex relations, even getting a single record is complex there is too much to do and I am unwilling to spend the time it would take to generate the fixtures, guarantee they're obfuscated, get approval of the obfuscation and justify keeping it around just to bridge us for a few months We understand the downsides: This violates test purity and introduces a potential safety risk. We are willing to compromise on both to get us past the next few months when we will phase out this problem data source. In this case, I need Django to understand that I don't want it to stand up a test database for this source, and just use the actual source so we can run some quick checks and walk away. What is the simplest way to achieve this, with full understanding and … -
Price range for hosting Django with Google Kubernetes engine
Good morning, I'm new to App development (I got only a bit of experience with really simple Flask / Django apps for some internal networks) and I'm currently developing a Django application that I host on Google Cloud using Google Kubernetes Engine. I mostly followed this tutorial and adapted it to my case: https://cloud.google.com/python/django/kubernetes-engine This application is simple, relies on django.auth for authentication and has only a few forms (around 20) operated via HTML POST requests and a few static files to serve (overall is less than 100 Mb). I'd like the app to be able to deal with 100 000 GET / POST requests per day (pages access / forms / connect and disconnect) made by 1000 users. I'm aware those requests won't be done uniformly during the day and that I have to think about the scalability of the application and the used database (right now it uses Google SQL Engine but it may evolve into a postgres/mariadb image hosted within Kubernetes with persistent storage). I hope that an horizontal scale will work, I choose Kubernetes in the hope it will make things easier in order not to have to focus on pod management (I still haven't dealt … -
Multiple form fields input django
I have the following problem which I don't know how to solve and I would be interested to know how you would tackle and solve it. I'm new to Python and Django but here it is the context: For a restaurant app I have to add menu items to the menu (ie. Menu -> Menu item1, Menu item2, etc) Each menu item can have some fix input (name, short_description) and 2 categories that could have n items (options and ingredients) but both have two values (price and description). Menu - Menu item 1 -- Name -- Short description -- Options ---1: Price -> Description ---2: Price -> Description -- Ingredients ---1: Price -> Description ---2: Price -> Description I would like to know: 1) how can I render the input fields from view.py? currently I render manually from the html the first 6 input fiels for options and ingredients, then I add js to increment the number of fields upon need. But I believe that there should be a better way to do it (at least for the first 6 items) 2) how to collect the input and store in the database? I was thinking to add 2 fields in … -
When I am trying to add an item to my to do list, I m getting an IntegrityError
I am building an todo app with Register, Login, Logout functionalities, I created a TaskForm to let user create their tasks, but when is click add it gives an IntegrityError at / NOT NULL constraint failed: tasks_task.user_id I tried many different approaches but it gives the same error it works when i add user in fields in TaskForm but it creates a Dropdown list of All users tasks/models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): name = models.CharField(max_length=200) completed = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tasks") def __str__(self): return f"{self.name}:{self.user}" tasks/forms.py from django import forms from .models import Task class TaskForm(forms.ModelForm): class Meta: model = Task fields = [ 'name', ] tasks/views.py from django.shortcuts import render, redirect from .forms import TaskForm from .models import Task from django.contrib.auth.decorators import login_required # Create your views here. @login_required def home(request): tasks = Task.objects.all() if request.method == "POST": form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('home') form = TaskForm() context = { 'tasks': tasks, 'form': form, } return render(request, "tasks/home.html", context ) tasks/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name= 'home' ) ] home.html {% extends … -
Django prefetch related objects from same model
How can I annotate each object in a queryset with related objects from the same model where one or more fields have the same value? Basically I have an Order model and ideally I'd like to prefetch related orders where the customer_email field is matching. I couldn't figure out how to do this so I tried to do annotate with a subquery and ArrayAgg to get the related order ids but I feel like it can be done with a prefetch? My attempt doesn't work because it returns more than one row. class Order(models.Model): customer_email = models.EmailField() from django.db.models import OuterRef, Subquery from django.contrib.postgres.aggregates import ArrayAgg Order.objects.annotate(rel=Subquery(Order.objects.filter(customer_phone_number=OuterRef('customer_phone_number')).order_by().annotate(ids=ArrayAgg('id')).values('ids'))) -
How to remove Moviestars2019 matching query does not exist error for value that are not in DB table
I have 3 models in Django : class Background(models.Model): name=models.CharField(max_length=200) animal=models.CharField(max_length=200) classes=models.CharField(max_length=200) types=models.CharField(max_length=200) activity=models.CharField(max_length=200) food_exp=models.DecimalField(max_digits=10000) food_donation=models.DecimalField(max_digits=10000) example in DB name animal types family Alex bear Mammals Ursidae Aquella wolf Mammals Canidae Alice fox Mammals Canidae Chip Iguana Reptiles Lizard Below is the class where only certain animals in this list ( so they act in movies the rest no) class Moviestars2019(models.Model): name=models.CharField(max_length=200) movie=models.CharField(max_length=200) rehearsal=models.CharField(max_length=200) food_kg=models.DecimalField(max_digits=10000) food_expenditure=models.DecimalField(max_digits=10000) example in DB for 2019 name movie rehearsal Alex Documentary Mon, Th Aquella Fantastic Mon, Wed in 2018 it is the same as Moviestars2019 with name teh same but movie and rehersal differ from 2018 : class Moviestars2018(models.Model): name=models.CharField(max_length=200) movie=models.CharField(max_length=200) rehearsal=models.CharField(max_length=200) food_kg=models.DecimalField(max_digits=10000) food_expenditure=models.DecimalField(max_digits=10000) but the same animals who star in movies. I want to get only get animals that are in table Moviestars2019 and Moviestars2018 to calculate monthly expendirure. What i did: initially i did by types of animals "Mammals" who star in movies like: def movie_exp2019(): if background.types=="Mammals": movie2019=Moviestars2019.objects.get(name=name) return: movie2019 movie_food_2019=movie_exp2019() and then i pass to context and further use in function to make calculation of per kg epxenditure and etc. The limitation of this method is that not all "Mammals" star in movies so the rest give me error if i … -
CSS file not found. Django project
my django project wont find my css file. Spelling is correct, path is correct, lower and upper cases are correct, its linked in the head part. ive been searching for 2 hours now. <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="../src/Templates/style.css"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous"> --> <title>Document</title> <style> .form-control{ width: 50%; } </style> </head> <body> <div class="container" id="thisone"> <h3 class="">BlaBlaBla!</h3> <h5>{{ message }}</h5> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </body> is this a stupid fail of mine? Greetings -
How to add customizable Bootstrap 4 to Django app
I want to add Bootstrap 4 to my Django app and customize it. I tried django-libsass and django_compressor and imported Bootstrap with @import "./bootstrap/scss/bootstrap"; in my main .scss file. But some components such as $enable-shadows, stretched links are not working. I'm guessing it's because scss files are not compiled. How can I add customizable Bootstrap to Django? Thanks! -
Fill input field of foreignkeyfield from database in Django
I am using a foreignkey field of a model as an input field in the html form because I want a user input if the value is not present in the database. So I just gave an input tag and in views I take the value and assign it to the form field. Now if the userprofile is already created then the pincode value will be there. How can I prepopulate the input field in the html with the value from the database? profile.html <form method="POST" id="userProfileForm" enctype="multipart/form-data"> {% csrf_token %} . . . <div> <label for="input_pincode">Pincode</label> <input id="input_pincode" type="text" name="input_pincode"> </div><br> . . . </form> models.py class UserProfile(models.Model): . . . pincode = models.ForeignKey(Pincode, models.SET_NULL, blank=True, null=True) forms.py class UserProfileUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserProfileUpdateForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta: model = UserProfile fields = ['pincode', other_fields] views.py def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) up_form = UserProfileUpdateForm(request.POST, request.FILES, instance=request.user.userprofile) if u_form.is_valid() and up_form.is_valid(): u_form.save() uncommitted_up_form = up_form.save(commit=False) if request.POST['city']: pin = Pincode.objects.get_or_create(city_id=request.POST['city'], pincode=request.POST['input_pincode'])[0] uncommitted_up_form.pincode = pin #other logic uncommitted_up_form.save() messages.success(request, f'Your profile has been updated!') return redirect('profile') Here in the html file I want to show the value of … -
djago template varables for gtag
I'm using gtag(for google analytics) and I've used django template to insert some variables in the gtags. I've seen lots of inconsistency in real purchase value and google analytics value in previous days(I don't check it real-time for the possible lag of panel update in google analytics pannel) models.py @property def gtag_price(self): retrun some_int html file //at the end of file gtag('event', 'purchase', { 'value': {{ order.gtag_price }}, 'currency': 'USD', 'transaction_id': '{{ order.code }}', 'shipping': {{ order.gtag_delivery_cost }}, }); how should I use "value" parameter in this tag? with quote mark '{{ order.gtag_price }}' or without {{order.gtag_price }}? -
how to image upload via drag and drop in django
i could not find anythink about django image DRAG and DROP not that for select every image seperatelli and upload it. Do you have any idea or links. Thanks -
TypeError: '>=' not supported between instances of 'QuerySet' and 'int'
I just want that if the escs is greater than or equal to id(5) it will go to my if , if not it will go to my else studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=args) escs = esc.objects.filter(Education_Levels__in=studentenroll.values_list('ESC')) if escs >= 5: .... else: .... this is the error i get What i tried so far is in my if condition if escs >= 5: ive tried this if escs.id >= 5: this is the error did i miss something? -
How do I put line break in Django template tag?
So I'm making an app that basically gets three keywords from the user. The user has to input three keywords in three separate fields, named 'kw1', 'kw2', 'kw3'. Then I've tried to render the data with template tag, like below. *I have the template tags in script tag, because I had to put them in for loop for some reason. ... {% for form in myKeywords %} { contents : "{{form.kw1}}<br>{{form.kw2}}<br>{{form.kw3}}", } {% endfor %} ... I wanted to have line breaks between keywords, but in my page it shows the raw(?) text itself with the br tag in between. What have I done wrong? -
What does it mean: UnreadablePostError: [Errno 104] Connection reset by peer?
I wrote api in django. So when i run and test it in posman to change some pics I am getting randomly this kind of errors . What does it means? Traceback (most recent call last): Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/mebel_dunyasi/myenv/project/products/views.py", line 160, in edit_image user_id = request.POST.get('id', 0) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/wsgi.py", line 102, in _get_post self._load_post_and_files() File "/usr/local/lib/python3.7/dist-packages/django/http/request.py", line 326, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "/usr/local/lib/python3.7/dist-packages/django/http/request.py", line 286, in parse_file_upload return parser.parse() File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 154, in parse for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 640, in __iter__ for sub_stream in boundarystream: File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 464, in __next__ return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 491, in __init__ unused_char = self._stream.read(1) File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 363, in read return b''.join(parts()) File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 354, in parts chunk = next(self) File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 376, in __next__ output = next(self._producer) File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 439, in __next__ data = self.flo.read(self.chunk_size) File "/usr/local/lib/python3.7/dist-packages/django/http/request.py", line 357, in read raise UnreadablePostError(*e.args) … -
Django model class method for todays average and latest record
I have a class in my django models as below: class Meter(models.Model): rec_time = models.DateTimeField(primary_key=True) energy = models.DecimalField(max_digits=12, decimal_places=3) power = models.DecimalField(max_digits=5, decimal_places=3) @classmethod def daily_summary(date_rec=date.today()): res = Meter.objects.filter(rec_time__date=date_rec) res = res.values('rec_time__date') res = res.annotate(energy=Max('total_energy'), avg_pow=Avg('power')) return res I want to obtain a daily summary with class method daily_summary as above. but when I try it on manage.py shell, it give me error as below: ......meter/models.py in daily_average(date_rec) 11 @classmethod 12 def daily_average(date_rec=date.today()): ---> 13 res = EVC.objects.filter(rec_time__date=date_rec) 14 res = res.values('rec_time__date') 15 res = res.annotate(energy=Max('total_energy'), ....../django/db/models/manager.py in manager_method(self, *args, **kwargs) 80 def create_method(name, method): 81 def manager_method(self, *args, **kwargs): ---> 82 return getattr(self.get_queryset(), name)(*args, **kwargs) 83 manager_method.__name__ = method.__name__ 84 manager_method.__doc__ = method.__doc__ ....../django/db/models/query.py in filter(self, *args, **kwargs) ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ....../django/utils/dateparse.py in parse_date(value) ---> 75 match = date_re.match(value) 76 if match: 77 kw = {k: int(v) for k, v in match.groupdict().items()} TypeError: expected string or bytes-like object How can I fix it? -
Prevent Duplicate Allauth Error Messages Being Displayed
Im using a lot of flash massages and the issue is if a user presses the button which generates the message multiple times beofre visiting a page which displays the messages, the same message is displayed multiple times. Importantly, a lot of these messages are generated with allauth so im also wondering in which file i should put the code. Thank you. -
Create PDF/CSV based on filter results and create a download link for user to download in Django
Below is my view function. I want to make a table of filtered data_new and create a respective PDF/CSV and make a download link of the file available for user in the template def baywise_filtered_stats(request): bay = request.POST['bay'] data_new = CameraData.objects.filter(bay_name=bay) in template, <a href="link_to_download" download>PDF</a> -
Docker ERROR: Couldn't find env file: /home/sam/code/docker/.env.dev
I'm learning how to use docker with Django. So first step is you setup the Dockerfile and here's the content of the file. FROM python:3.8.0-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app/requirements.txt RUN pip install -r requirements.txt # copy project COPY . /usr/src/app/ another file the docker-compose.yml file content below version: '3.7' services: web: build: ./project command: python manage.py runserver 0.0.0.0:8000 volumes: - ./project/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev now these two files are in the folder docker which also has my django project folder called project keeping it simple :) When I run docker-compose build I get back the error ERROR: Couldn't find env file: /home/sam/code/docker/.env.dev -
django, how to deal with modelForm with foreignkey?
i want to deal with foreignKey with a modelForm and it raise this error: ValueError at /3/ The view main.views.ProductDetailView didn't return an HttpResponse object. It returned None instead. the problem is on the Wilaya and commune fields, because when i remove them all works fine. in views.py class ProductDetailView(ModelFormMixin, DetailView): model = Produit context_object_name = 'produit' form_class = CheckoutCreateForm def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["form"] = self.get_form() context["wilayas"]= Wilaya.objects.all() context["communes"]= Commune.objects.all() return context def post(self, request, *args, **kwargs): # self.object = self.get_object() # form = self.get_form() form = CheckoutCreateForm(request.POST) if form.is_valid(): checkout = form.save(commit=False) checkout.produit = self.get_object() checkout.prix = self.get_object().price checkout.save() wilaya = form.cleaned_data['wilaya'] commune = form.cleaned_data['commune'] quantity = form.cleaned_data['quantity'] nom_du_client = form.cleaned_data['nom_du_client'] prenom_du_client = form.cleaned_data['prenom_du_client'] adresse_du_client = form.cleaned_data['adresse_du_client'] print('jusque la cv') try: form = CheckoutCreateForm() return redirect(f'/{self.get_object().pk}') except: return redirect('/') in models.py class Wilaya(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Commune(models.Model): Wilaya = models.ForeignKey(Wilaya, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Checkout(models.Model): produit = models.ForeignKey('Produit', on_delete=models.CASCADE) prix = models.IntegerField(default=0) nom_du_client = models.CharField(max_length=40) prenom_du_client = models.CharField(max_length=40) adresse_du_client = models.CharField(max_length=40) date_added = models.DateTimeField(auto_now_add=True) wilaya = models.ForeignKey(Wilaya, on_delete=models.SET_NULL, null=True, blank=True) commune = models.ForeignKey(Commune, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.PositiveIntegerField(default=1) confirmer = models.BooleanField(default=False) def __str__(self): … -
Python - Django Filewrapper TypeError on HttpResponse when trying to download the file
I have code like this: from wsgiref.util import FileWrapper from django.http import Http404, HttpResponse def get(self, request, *arg, **kwargs): obj = self.get_object() filepath = os.path.join(settings.PROTECTED_ROOT, obj.media.path) wrapper = FileWrapper(open(filepath), 'rb') response = HttpResponse(wrapper, content_type='application/force-download') response["Content-Disposition"] ="attachment; filename=%s" %(obj.media.name) response["X-SendFile"] = str(obj.media.name) return response When I try to download the file getting and error: File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/wsgiref/util.py", line 30, in next data = self.filelike.read(self.blksize) Exception Type: TypeError at /products/titles-40/download/ Exception Value: argument should be integer or None, not 'str' I tried with importing FileResponse and changing HttpRpesonse in response with that, error in terminal remained the same, but browser message change to A server error occurred. Please contact the administrator. What I am doing wrong?