Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin import-export csv with FK issues
I am bit new to Django admin. I have done "import" with django-import-export. And my models contains ForeignKey references. And I am getting error invalid literal for int() with base 10: ' Homewares & Giftware'. I can show the code, pasting error + relevant information that I think is needed. If something more required, I can provide. Kindly help !!! This is import_csv () #Importing csv file in djnago admin side def import_csv(self, request): context = dict( self.admin_site.each_context(request), form=self.import_form ) if request.method=='POST': csv_file=request.FILES['csv_file'] if not csv_file.name.endswith('.csv'): messages.error(request,'File is not CSV type') return HttpResponseRedirect("import") # if csv_file.multiple_chunks(): # messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),)) # return HttpResponseRedirect("import") data_set = csv_file.read().decode('UTF-8') io_string=io.StringIO(data_set) next(io_string) for column in csv.reader(io_string,delimiter=',',quotechar='"'): if column: print("handle",column[1]) created=VendProduct.objects.get_or_create( handle=column[1], sku=column[2], composite_handle=column[3], composite_sku=column[4], composite_quantity=column[5], vend_product_name=column[6], description=column[7], variant_option_one_name=column[8], variant_option_one_value=column[9], variant_option_two_name=column[10], variant_option_two_value=column[11], variant_option_three_name=column[12], variant_option_three_value=column[13], tags=column[15], supply_price=column[16], retail_price=column[17], account_code=column[18], account_code_purchase=column[19], #brand=column[20], ### HERE IS THE ISSUE ) This is the error that I am getting: Request Method: POST Request URL: http://127.0.0.1:8000/admin/accounting/vendproduct/import/ Django Version: 2.2.6 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'Homewares & Giftware' Exception Location: /home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python3.7/site-packages/django/db/models/fields/init.py in get_prep_value, line 968 Python Executable: /home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/bin/python Python Version: 3.7.5 Python Path: ['/home/roohi/work/24campus/campus_co_backend', '/home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python37.zip', '/home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python3.7', '/home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python3.7/site-packages', … -
Django + Nginx Unable to serve media files
I have two servers: the first for Nginx and the second for Django + media files. Nginx server IP: xxx.xx.xx.1 Django + media files server IP: xxx.xx.xx.2 In Django's settings.py file, my media path configurations: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" In the first server, my Nginx configurations: server { listen 80; server_name example.com; location /media/ { proxy_pass http://xxx.xx.xx.2/; } location / { include proxy_params; proxy_pass http://xxx.xx.xx.2:8000/; } } In the second server, where the media files are placed, my Nginx configurations: server { listen 80; server_name xxx.xx.xx.2; location /media/ { alias /home/sadm/Desktop/{project_name}/media; } However, when trying to access example.com/media/images/my_image.jpg, I get a 404 error. Any help is greatly appreciated! Thanks in advance! -
Django and JQuery - Iterate through object list
I have a table that looks like this: <table> {% for object in object_list %} <tr> <th id="hiddenth">{{ object.user }}</th> <th><button onclick="showTh()">Show Users</button></th> </tr> {% endfor %} </table> This returns a column with usernames and a column with buttons as expected. But, all buttons are mapped to the first row of the table and the other rows are not affected. How can I fix this? Thank you for any help -
How to use cycle in django with two columns?
I created one section divided into two columns. Each of the columns is to represent one blog entry. Unfortunately, two columns are currently assigned one and the same entry, and they will be two separate. I don't quite understand how to use the cycle tag correctly in this case. example http://imgbox.com/NWO7qA7S I use the bootstrap 4 and django 2.2 frameworks to create the page. I tried various combinations, but understanding the operation of the cycle tag is unclear to me. {% for post in posts %} <section class="bg-light py-5" id="aktualnosci"> <div class="container"> <h1>Informacje o zmianach w prawie podatkowym</h1> <div class="divider"></div> <p class="text-paragraph pt-3">Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam iure consectetur accusantium delectus, iusto culpa mollitia eum molestiae at? Ab!</p> <div class="row py-3"> <!-- FIRST POST --> <div class="col-lg-6"> <div class="news-card"> <div class="text-center text-white bg-blue d-flex align-items-center news-card-date"> <div class="mx-auto news-card-date-body w-75"> <i class="far fa-calendar-alt d-none d-block mx-auto"></i> <span class="d-block news-card-date-value mt-1">{{ post.published }}</span> </div> </div> <div class="news-card-body"> <div class="news-card-img"> <img class="img-fluid" src="{% static 'main/images/126.jpg' %}" alt=""> </div> <div class="news-card-content"> <div class="news-card-content-inner"> <h2>{{ post.title }}</h2> <p class="text-paragraph">{{ post.lead }}</p> <a class="pb-2" href="#">Czytaj więcej</a> </div> </div> </div> </div> </div> <!-- SECOND POST --> <div class="col-lg-6"> <div class="news-card"> <div class="text-center … -
How to generate dynamically image URL in Django?
I'm new in Django, and I don't use mainly Python for websites. But now one project require that. I want to create API, where you POST static image URL, and and script would generate with Django something like this: https://example.com/img?image=xXgGDd5GSjfsdaskDAdsKdkSD76454dfGdDfFs.png. This would be exactly same like gived static URL. I have no problem to create API, due about this is much guides when I google it, but this generating... This is my problem. -
How to display a page and start the file download from it in django?
I have a method in my views.py that I've constructed with a http response # # content-type of response response = HttpResponse(content_type='application/ms-excel') # #decide file name response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.xls"' #adding new sheets and data new_wb = xlwt.Workbook(encoding='utf-8') new_wb.save(response) This works fine if I only have response in my return But I also want to return a render return render(request, 'uploadpage/upload.html', {"excel_data": seller_info, "message":message, "errormessage":errormessage}) I was wondering if there's a way to do that -
Uploading Image from django template occurs "MultiValueDictKeyError(repr(key))"
I have tried some of the solutions from previous posts, but nothing works. Everything works fine if I remove the image-upload input from the template. My Template: <form id="contact" action="#" method="post" enctype="multipart/form-data"> <input type="hidden" name="customer_id" value="{{ customer_id }}"> <fieldset> <input type="text" name="name" {% if name %} value="{{ name }}" {% else %} placeholder="Your Name" {% endif %} tabindex="1" required> </fieldset> <fieldset> <input type="text" name="phone" {% if phone %} value="{{ phone }}" {% else %} placeholder="Your Phone Number" {% endif %} minlength="11" maxlength="14" tabindex="3" required> </fieldset> <fieldset> <label>Complaint Image</label> <input type="file" name="complaint_image" accept="image/*" required> </fieldset> <fieldset> <button name="submit" type="submit" id="contact-submit">Submit Feedback</button> </fieldset> </form> views.py: if request.method == "POST": customer_id = request.POST.get("customer_id", None) name = request.POST.get("name", None) phone = request.POST.get("phone", None) image = request.FILES["complaint_image"] return redirect('/custom/success/') Error Message File "/home/raphael/alice_v2/custom/views.py", line 1926, in pureit_feedback image = request.FILES["complaint_image"] File "/home/raphael/alice_v2/venv/lib/python3.6/site-packages/django/utils/datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'complaint_image' -
istalled gunicorn but it is not in venv/bin folder
I'm new to gunicorn and trying to deploy a django website on an ubuntu. I have used: pip3 install gunicorn sudo apt-get install gunicorn but when I want to fill this file: sudo nano /etc/systemd/system/gunicorn.service and I fill it with: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target but there is no gunicorn file in /bin what is the missing part? -
AttributeError 'Client' object has no attribute 'get'
Bonjour, j'ai un problème très probablement idiot mais que je n'arrive pas à résoudre, un Attribute error après l'exécution d'une fonction de views En mode degug de mon application Django j'obtiens: AttributeError Exception Value: 'Client' object has no attribute 'get' (...) Error during template rendering In template (...)Comptabo/templates/base.html, error at line 0 Lorsque que je clique sur le nom d'un client dans ma page index. J'ai déjà essayé beaucoup de chose et regardé les topics correspondant ainsi que la doc, je ne comprends pas d'où vient l'erreur. Ce n'est pas un problème liée au template, ni au fichier urls.. Si quelqu'un a une idée Ma fonction client dans views.py : def client(request, id = 0): if id: client = Client.objects.get(id = id) form = ClientForm(client) factures = Facture.objects.filter(client = client) devis = Devis.objects.filter(client = client) form_fact = FactureForm() form_dev = DevisForm() return render(request,'client.html',{'client' : client, 'form' : form, 'factures': factures, 'devis': devis, 'formf': form_fact,'formd': form_dev}) else: return redirect('/index') Ma class Client dans models.py : class Client(models.Model): nom = models.CharField(max_length = 30) adresse_voie = models.CharField(max_length = 30) adresse_code = models.IntegerField() adresse_ville = models.CharField(max_length = 30) adresse_pays = models.CharField(max_length = 30, default = "France") tel = models.CharField(max_length = 12) fax = models.CharField(max_length … -
Access Foreign key items for SQLAlchemy
I would need your support/advice again, as I am just a hobby programmer. I am storing data for a data analysis in mysql and access through django/phpmyadmin. I think it is better than just storing in a text file. For the real analysis I download the latest data then using SQLAlchemy to pandas. Here is the issue: To have the data structured, I use in django/mysql foreign keys, e.g. class Analyse(models.Model): company = models.ForeignKey('analysen.Company', on_delete=models.CASCADE, related_name='analyse') ... other fields class Company(models.Model): identification = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=80) The table for the analysis is "Analyse", however, in my pandas aggregation I would like to use after "downloading" with SQLAlchemy also the company name, so a different field of class Company than the primary key. Which is the easiest solution without changing too much? I believe this is not too complicated, I just do not find the solution right now. Thanks in advance for your help! Kind regards! -
Django Postgres ArrayField: Overlap Length
Let say I have a model: class Post(models.Model): nlp_data = ArrayField(models.CharField(100)) As any awesome blog, I'd like to fetch some recomendations, to keep my users reading. The rule I want to implement: Get any posts, where nlp_data has at least two common "words" with a set of given "words". My guess is I could use some Func inheritance, using some CARDINALITY and && operator, but I'm struggling assembling those together. nlp_data is really coming from NLP Algorithms, any M2M tag system is excluded. -
How can I make citext extension work on Django tests?
I'm running tests against a model having a ArrayField(CICharField()) field and they return a string instead of a list. I use pytest-django to run the tests. I know that returning a string instead of a list was a known problem in the past, but it's fixed in my current Django version (2.1.13). When I reproduce the test from the shell, everything works ok. Things seems to be related to the tests environment, specially how test suite creates the database. As far as I understand, citext extension is not installed properly during the tests. If I run the test battery twice, keeping the database (using --reuse-db), the second (and next other) run work perfectly well. That makes me think that the extension is installed "too late". Probably not very useful, but this is the result I'm getting: self = <tests.test_ciarrayfield.CIArrayFieldTestCase testMethod=test_save_load> def test_save_load(self): print(settings.INSTALLED_APPS) instance = ProductFactory(sku="SKU1", product_types=[]) loaded = Product.objects.get() > self.assertEqual(instance.product_types, loaded.product_types) E AssertionError: [] != '{}' src/tests/test_ciarrayfield.py:14: AssertionError And part of my model: class Product(models.Model): product_types = ArrayField( CICharField(max_length=750), default=list, blank=True) The obvious expected result is to get a list on that field after getting the instance from the database, and not a string. As I said, this … -
Django: Intercepting & Accepting/Rejecting Login Attempts
Is there a way to intercept login attempts with Django, perhaps a signal or hook, whereby if a certain User attribute is True or False, would either allow the login attempt to continue, or reject it... I would rather not have to rebuild from scratch, just use the existing Django infrastructure... -
Jinja: find all the variables used in a template [duplicate]
This question already has an answer here: How to get list of all variables in jinja 2 templates 4 answers I'm working with Django and Jinja and I want to obtain a list of all the variables used in a given template. For the moment, I've managed to retrieve all the undeclared variables, ie. those who are used like this {{ username }},j by using jinja2.meta.find_undeclared_variables. But, I also need to obtain the declared variables, ie. those who are used like this {% set age = 32 %}. Unfortunately, I haven't found a way of doing this. How can I obtain the second type of variables from within a Jinja template? -
Building a secure file-manager app with Django
I'm developing a project which is going to be a public website and it needs to get media files (digital images, audios and videos) from users and save them and I don't want users to upload malicious files into my server (I'm currently using an SFTP server for storage). So I'm looking for a solution to check file formats and allow "safe and intact" media files to be uploaded. Is there any python package to check some bytes of the file and say "this is a valid jpg" or "mp3" etc? Can you recommend any other solution for my problem (securing my file-manager app)? -
How to support optional or empty FileField with Django Rest Framework?
I added a new FileField 'photo' to my existing model and migrated the database. When I try to return data using DRF, I get the error message "ValueError: The 'photo' attribute has no file associated with it." Photo column contains empty values. The field should be optional. models.py: def photo_directory_path(instance, filename): return 'photos/{0}/{1}'.format(instance.id, filename) class MyModel(models.Model): ... photo = models.FileField(blank = True, editable = True, upload_to=photo_directory_path) ... class MyModel_l10n(models.Model): ... mymodel = models.ForeignKey(MyModel, on_delete=models.CASCADE, related_name='%(class)s_mymodel') ... serializers.py: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['photo'] class MyModel_l10nSerializer(serializers.ModelSerializer): photo = serializers.ReadOnlyField(source='mymodel.photo') class Meta: model = MyModel_l10n fields = ['photo', ...] views.py: res = MyModel_l10n.objects.filter(...) serializer = MyModel_l10nSerializer(res, many=True) return Response (serializer.data) error message: ValueError: The 'photo' attribute has no file associated with it. -
How to handle read/write operations on FileObject in Test environment (using Pytest)
I am testing a FileField in django with pytest. What I want to do is to check if the returned content within the file is the same as the file that was uploaded. I know that I can just call read() normally on a FieldFile but somehow in my test env it doesn't work like expected. The pytest docs also don't answer my prayers. I do it like this: def test_content_of_returned_file(self, client, user): response = make_auth_request(user, client) #makes authenticated call first_obj = FileCollection.objects.first() #gets the first object in the db print(first_obj.store_file) # for debugging first_obj_file = first_obj.store_file.read() #read content of first object assert response.content == first_obj_file #check if the content of db object and called object is the same Unfortunately this gives me a ValueError: I/O operation on closed file. When I try to open it like this: first_obj_file = open(first_obj.store_file, "r") I get the same error. Maybe the error is also the response.content. I am not sure. When I print it out it give my a test_file_download.TestDownload object. So maybe the read and write operations differ? Any help is very much appreciated! Thanks in advance! -
Django raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am trying to use pyspark to preprocess data for the prediction model. I get an error when I try spark.createDataFrame out of my preprocessing.Is there a way to check how processedRDD look like before making it to dataframe? import findspark findspark.init('/usr/local/spark') import pyspark from pyspark.sql import SQLContext import os import pandas as pd import geohash2 sc = pyspark.SparkContext('local', 'sentinel') spark = pyspark.SQLContext(sc) sql = SQLContext(sc) working_dir = os.getcwd() df = sql.createDataFrame(data) df = df.select(['starttime', 'latstart','lonstart', 'latfinish', 'lonfinish', 'trip_type']) df.show(10, False) processedRDD = df.rdd processedRDD = processedRDD \ .map(lambda row: (row, g, b, minutes_per_bin)) \ .map(data_cleaner) \ .filter(lambda row: row != None) print(processedRDD) featuredDf = spark.createDataFrame(processedRDD, ['year', 'month', 'day', 'time_cat', 'time_num', 'time_cos', \ 'time_sin', 'day_cat', 'day_num', 'day_cos', 'day_sin', 'weekend', \ 'x_start', 'y_start', 'z_start','location_start', 'location_end', 'trip_type']) I am getting this error: [Stage 1:> (0 + 1) / 1]2019-10-24 15:37:56 ERROR Executor:91 - Exception in task 0.0 in stage 1.0 (TID 1) raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:452) at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRunner.scala:588) at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRunner.scala:571) at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:406) at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37) at scala.collection.Iterator$class.foreach(Iterator.scala:891) at org.apache.spark.InterruptibleIterator.foreach(InterruptibleIterator.scala:28) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at org.apache.spark.InterruptibleIterator.to(InterruptibleIterator.scala:28) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at org.apache.spark.InterruptibleIterator.toBuffer(InterruptibleIterator.scala:28) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at org.apache.spark.InterruptibleIterator.toArray(InterruptibleIterator.scala:28) at org.apache.spark.api.python.PythonRDD$$anonfun$3.apply(PythonRDD.scala:153) at org.apache.spark.api.python.PythonRDD$$anonfun$3.apply(PythonRDD.scala:153) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2101) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2101) … -
Django Docker app container don't open on browser after run
I dockerize my django app, this is my Dockerfile: FROM python:3.6-alpine EXPOSE 8000 RUN apk add --no-cache make linux-headers libffi-dev jpeg-dev zlib-dev RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN mkdir /Code WORKDIR /Code COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt ENV PYTHONUNBUFFERED 1 COPY . /Code/ ENTRYPOINT python /Code/core/manage.py runserver 0.0.0.0:8000 well, i build my image and i run it: docker run -p 8000:8000 --link postgres:postgres cath11/test_app all sems to be done: but when i open my browser on http://0.0.0.0:8000/ or http://127.0.0.1:8000/ my app won't open Why my django app seems running on my container, i expose port bat i cannot see it in my hosted browser? So many thanks in advance -
Many-to-Many with additional properties
I've built a small ERP system with some products( model: Product) and 1 stock location. The quantity in stock is simply 1 property of the object. I'd like to extend the application to more stock-locations but don't find the right way to do this. For 2 or 3 locations I can add of course simply additional properties to my model but in the case of many locations(let's say i.e. 250) this becomes not clear anymore. I already tried a many-to-many relationship between a model of stocklocations and products. The problem here, however, is that I can add products to stocklocations but cannot retrieve the amount of product in each stocklocation. I hope somebody can help me on the right track to tackle this self-created problem. -
Django for loop is not showing my items on webpage
I have a table on my webpage that I want to iterate product information into and it worked up until I tried adding a paginator. The server runs fine and the rest of the website is functional. Here are my files: shop/products.html {% extends 'base.html' %} {% block content %} <h1>On sale here</h1> <div class="col-sm-3"> <h4>Categories</h4> <ul class="list-group"> <a href="{% url 'products' %}" class="list-group-item"> All Categories </a> {% for c in countcat %} <a href="{{ c.get_absolute_url }}" class="list-group-item catheight">{{c.name}} <span class="badge">{{c.num_products}}</span> </a> {% endfor %} </ul> </div> <div class="col-sm-9"> <h4>Note that all products are second hand, unless otherwise stated.</h4> <form class="form-inline my-2 my-lg-0" action="{% url 'search_result' %}" method="get"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="q"> <button class="glyphicon glyphicon-search h-100" type="submit"></button> </form> <table class="table table-bordered table-hover table-condensed"> <thead> <!-- The header row--> <tr> <th>ID</th> <th>Name</th> <th>Image</th> <th>Category</th> <th>Description</th> <th>Stock</th> <th>Price</th> <th>Buy</th> </tr> </thead> <tbody> <!-- Product row(s) --> {% for product in products %} <tr> <td>{{product.id}}</td> <td>{{product.name}}</td> {% if product.image %} <td><img src="{{product.image.url}}"></td> {% endif %} <td>{{product.category}}</td> <td>{{product.description}}</td> <td>{{product.stock}}</td> <td>&euro;{{product.price}}</td> {% if product.stock > 0 %} <td><a href="{% url 'add_cart' product.id %}" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-shopping-cart"></span></a></td> {% else %} <td><a href="" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-warning-sign red"></span></a></td> … -
I want to insert google ads sense ads into my django app but i don't know how? can you please help me with this?
Actually, I m developed a simple blog app and i want it to have some ads so that i can earn some income, if someone visits my site. But i dont know how to insert those ads in django. Please help me ! -
Dockerfile error during creating a Django project with Docker
I try to start a django/postgresql project with Docker. I have 3 files in the project folder (Dockerfile, docker-compose.yml, requirements.txt) When I run: sudo docker-compose run web django-admin startproject composeexample . I get the following error: Starting backend_db_1 ... done Building web ERROR: Cannot locate specified Dockerfile: Dockerfile Here's my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: '3' services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db requirements.txt Django>=2.0,<3.0 psycopg2>=2.7,<3.0 -
How to change the initial value of a nested field to zero instead of null value.?
How to change the initial value of a nested field to zero instead of null value.? In my case Prize model is a OneToOneField to model Album Serializer class PrizeSerializer(serializers.ModelSerializer): class Meta: model = Prize fields = ['title', 'amount'] class AlbumSerializer(serializers.ModelSerializer): prize = PrizeSerializer(read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'prize'] Some items have prize data but some do not have prize data. If there is no prize data it will be shown as null, >>> serializer.data { "album_name": "The Grey Album", "artist": "Danger Mouse", "prize": null } how to change this null value to zero.? Expected output >>> serializer.data { "album_name": "The Grey Album", "artist": "Danger Mouse", "prize": "0.0" } -
django server (hosted on ec2 ubuntu) failing for multiple users
I am trying to run django server on aws ec2 instance (ubuntu) using screen command. screen -L python3 manage.py runserver 0.0.0.0:8000 My script works in simple common way that it detects a POST request, processes and responds via HttpResponse. When one user is interacting, and suddenly new user iteracts and new post request is detected, older flow get cut off. How do I handle multiple users ?