Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple of the same dependent dropdownboxs in one form
I have a problem with the following; I have a dependent dropdown menu in a Django model form. Now I want to use it several times in the same form but I can't get it to work if I load more than one then I can only enter/use one. And I have a 2nd problem if this works how do I get the different values in a list/array so that I can store them in the db? The ultimate goal is to select how many beams are desired and on that basis to be able to enter the desired hours, ion species, energy and flux per beam. My code is as follows: models.py from django.db import models from smart_selects.db_fields import ChainedForeignKey class IonSpecies(models.Model): # ionspecie = models.CharField(max_length=10) Name = models.CharField(max_length=10) def __str__(self): # return self.ionspecie return self.Name class Energys(models.Model): Ion_Species = models.ForeignKey(IonSpecies, on_delete=models.CASCADE) Name = models.CharField(max_length=50) def __str__(self): # return self.energy return self.Name # Create your models here. class CreateBeamRequestModel(models.Model): #status choices SELECT = 'Select' REQUEST = 'Request' TENTATIVE = 'Tentavive' ACCEPTED = 'Accepted' CONFIRMED = 'Confirmed' CANCELLED = 'Cancelled' COMPLETED = 'Completed' QUEUED = 'Queued' STATUS_CHOICES = [ (SELECT, ('Select an option')), (REQUEST, ('Request')), (TENTATIVE, ('Tentative')), (ACCEPTED, ('Accepted')), (CONFIRMED, … -
In Django admin, how can I hide another related model field when adding it to the "Tədris" model?
I tried to do it with signals but I couldn't. Models and their images on the admin panel. Please help me https://i.stack.imgur.com/A3zS0.png https://i.stack.imgur.com/edtrK.png https://i.stack.imgur.com/yNio1.png https://i.stack.imgur.com/plhUW.png -
Django error : struct.error: unpack requires a buffer of 4 bytes
I hope you are fine . I will thank if anyone help me to solve error below that is for django while activating a language for making a multi language website . Thanks . Best wishes . struct.error: unpack requires a buffer of 4 bytes -
How to add unique_together for id and key inside Jsonfied in Django?
This how my model looks like. class TestModel(models.Model): data = models.JSONField( verbose_name=_("user data"), validators=[user_data_validator], ) class Meta: unique_together = ["id", "data__userId"] This is the schema for data field class DataSchema(BaseModel): userId = UUID How to make unique_together for id and userId from the JsonField? -
Django and Javascript: Take Info From API And Save To Database
I'm very new to Javascript with Django and I'm looking for some basic info on how to take info from an API that has already been returned, and post it to the database. I have used views.py to take information and save it to the database, but I haven't done this with info from an API that is achieved in Javascript. My project is a weather app that gets info from OpenWeather for a city that the user types into a box, and that part works - the API information is returned. I currently have a model for each Location, I just don't know how to save it in the database. Is this done through fetch, using POST? I am also slightly confused about how the urls would be setup. Any information, maybe some sample github code, could help :) For example, if I want to get the location and then add it to my 'favorites' would something like this make sense? I know I would still need to make the view, and url. const location_content = document.querySelector('#content').value; function add_to_fav() { fetch('/favorites', { method: 'POST', body: JSON.stringify({ location_content: location_content }) }) .then(response => response.json()) .then(result => { console.log(result); }); localStorage.clear(); … -
What's the difference between "id" and "pk" parameter with get_object_or_404
I am learning Django. When I was learning how to use get_object_or_404, I noticed that some codes specify id as the argument of get_object_or_404, while others specify pk. It seems that whether I specify id or pk, the result is the same. foo1 = get_object_or_404(FooModel, pk=1) foo2 = get_object_or_404(FooModel, id=1) """ FooModels table has some records that includes id is 1. When I access foo/1, foo1 and foo2 have the same values. """ How do you use these parameters differently? Or if there is something fundamentally wrong with my thinking, please let me know. Thanks. models.py from django.db import models from django.utils import timezone class FooModel(models.Model): name = models.CharField('name', max_length=20) body = models.CharField('body', max_length=100) created_at = models.DateTimeField('created_at', default=timezone.now) urls.py from . import views urlpatterns = [ path("foo/<int:id>", views.foo), ] views.py from django.shortcuts import get_object_or_404 from .models import FooModel def foo(request, id) foo1 = get_object_or_404(FooModel, pk=id) foo2 = get_object_or_404(FooModel, id=id) """ FooModels table has some records that includes id is 1. When I access foo/1, foo1 and foo2 have the same values. """ $ python -m django --version 2.2.20 $ python --version Python 3.7.9 -
Django POST request from a HTML dynamic form
I have develop a dynamic form with Bootstrap and Javascript, now I'd like to post that information in sql3 database (default django database), so I made a POST REQUEST in HTML file, views.py and the respective models.py But when I try to push the submit bottom from the form, nothings happens, I think the issue is how the form was made, but I can't figure out how to solve it. Infraestructura.html {% extends "Portafolio/layout.html" %} {% load static %} {% block scripts %} <script src = "{% static 'Portafolio/scriptinfra.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <form action= "{% url 'infraestructura' %}" method="POST" class="form mt-5" id="infra"> {% csrf_token %} <h1>Factibilidad Técnica y Operativa</h1> <h2>Análisis de Infraestructura</h2> <main class="container"> <section class="row"> <div class="col-lg-4 mb-2"> <input name='Infraestructura' class="form-control" type="text" placeholder="Infraestructura"> </div> <div class="col-lg-4 mb-2"> <input name='Tiempo' class="form-control" type="text" placeholder="Tiempo"> </div> <div class="col-lg-4 mb-2"> <input name='Costo' class="form-control" type="text" placeholder="Costo Mensual"> </div> </section> </main> <nav class="btn-group"> <button id='add' class='btn btn-success' type='button'> <i class="fa fa-plus-square"></i> Añadir </button> <button id='rem' class='btn btn-danger' type='button'> <i class="fa fa-minus-square"></i> Eliminar </button> </nav> <!-- Submit buttom--> <div class="d-grid gap-2 mt-3"> <input type="submit" class="btn btn-lg btn-primary"> </div> </form> {% endblock %} views.py def infraestructura(request): if request.method =='POST': Infraestructura = … -
Adding Background Image Using CSS
In my django project I try to add background image to html template. But it does not work my code is like this background-image: url("/img/bg.jpg"); error GET http://127.0.0.1:8000/img/bg.jpg 404 (Not Found) Please help me to fix this I try it different ways... -
django.core.exceptions.ImproperlyConfigured: Cannot import 'category'. Check that 'api.category.apps.CategoryConfig.name' is correct
I am using 3.2 django, and rest framework . main project name is ECOM and api is app .Inside api there are multiple apps like category,migrations,order,payment,product,user. Now I want to inform ecom.settings about installed api. HOW I should do it ? SETTING.PY OF ECOM : INSTALLED_APPS = [ #other basic install 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'api', 'api.category', ] but getting error. My category apps.py file looks like class CategoryConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'category' GIT hub link is https://github.com/Jhaamlal/DJANGO_REACT -
How can i bind two serializers into separate one serializer django rest framework?
info: One is User and the Second one is User Data like phone number,city etc Now i can add these two serializer into third serializer and show all data in third one Problem: now i want to create new Serializer Where i can combine both serializer attributes. but i don't understand how can i achieve to bind two serializer into different one and show all data? serializers.py class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = ['email', 'phone'] class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ['city'] Want to achieve class CombineSerializer(serializers.ModelSerializer): class Meta: fields = ['email', 'phone', 'city'] -
Django ForeignKey default value in new table
I need to set a default value to a ForeignKey after the model has been migrated. Is this possible? For instance, a "meal" Class has a ForeignKey named "drinks". Some drinks are added, Pepsi, Coke,.. to the drink table. In the meal Class is it possible to name Coke as the default? From the docs I see only that the index can be used. That implies that I would have to ensure that I added the correctly named default into the correct index. Then I would be stuck with it hard coded in. How is it done so that changes to the default can be done after the fact? An example would be great if anyone has one handy. Best regards. -
How do I create a model that stores multiple images in relation to another model
How do I create a Django model PaperImage that stores multiple images that relates to another Django model Papers? And I have to afterwards access all the images related to one Papers object. How should my views.py should be in order save both these relative to eachother? #models.py class Papers(models.Model): yearChoices = [] grades = ( #some grades ) termChoices = ( #some terms ) for r in range(1985,(datetime.datetime.now().year)): yearChoices.append((r,r)) subject_list = ( #some subjects ) province_list = ( #some provinces ) year = models.DateField(choices=yearChoices,default=datetime.datetime.now().year) term = models.CharField(choices=termChoices,default=1,max_length=15) subjects = models.CharField(max_length=1,choices=subject_list,help_text="Choose what subject the post belongs to.",default='u') grade = models.IntegerField(choices=grades,default=10) school = models.CharField(max_length=254,help_text="Which school's paper is this?") province = models.CharField(max_length=254,choices=province_list,default=1) education_zone = models.CharField(max_length=254,blank=True) class PaperImage(models.Model): paper = models.OneToOneField(Papers, related_name='paper',blank=True,null=True, on_delete=models.CASCADE) images = CloudinaryField("images") -
How to handle JS script with Django template language?
I'm trying to use django template language to manipulate JS scripts, but when I try appears the following error I checked the error in case there is a misstyped code, but I couldn't detect it. How is the best way to handle multiple JS script with multiple HTML files in Django template language? Infraestructura.html {% extends "Portafolio/layout.html" %} {% block scripts %} <script src = "{% static 'Portafolio/scriptinfra.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <form class="form mt-5" id="infra"> <h1>Factibilidad Técnica y Operativa</h1> <h2>Análisis de Infraestructura</h2> <main class="container"> <section class="row"> <div class="col-lg-4 mb-2"> <input name='infs' class="form-control" type="text" placeholder="Infraestructura"> </div> <div class="col-lg-4 mb-2"> <input name='time' class="form-control" type="text" placeholder="Tiempo"> </div> <div class="col-lg-4 mb-2"> <input name='cost' class="form-control" type="text" placeholder="Costo Mensual"> </div> </section> </main> <nav class="btn-group"> <button id='add' class='btn btn-success' type='button'> <i class="fa fa-plus-square"></i> Añadir </button> <button id='rem' class='btn btn-danger' type='button'> <i class="fa fa-minus-square"></i> Eliminar </button> </nav> </form> <form class="form mt-3"> <div class="d-grid gap-2 mt-3"> <a class="btn btn-lg btn-primary" href="tecnicoequipo.html">Siguiente</a> </div> <div class="d-grid gap-2 mt-3"> <a class="btn btn-lg btn-primary" href="financierobeneficio.html">Atrás</a> </div> </form> {% endblock %} layout.html {% load static %} <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" … -
Why django template loader is case-sensitive in production but not in development
I'm using manage.py runserver on a MacOs Catalina OS as development. I have some templates that fit my built-in class based views. For example: CuadroDeControl_detail.html LoteDeMedio_list.html TipoDeMedio_detail_tablaCuadros.html CuadroDeControl_detail_resumen.html LoteDeMedio_list_tabla.html TipoDeMedio_list.html CuadroDeControl_detail_tablaMetodos.html MetodoDeControl_detail.html TipoDeMedio_list_tabla.html LoteDeMedio_confirm_delete.html MetodoDeControl_detail_resumen.html dropdown_CuadroDeControl.html LoteDeMedio_create.html TipoDeMedio_confirm_delete.html dropwdown_CuadroDeControl.html LoteDeMedio_detail.html TipoDeMedio_detail.html LoteDeMedio_detail_resumen.html TipoDeMedio_detail_resumen.html Here is an example of a working view: 58 class TipoDeMedioDetailView(AreaCalidadMixin, DashboardMixin, DetailView): 59 model = TipoDeMedio Note that my views do not explicitly set template_name. On my production environment, all my views load just fine.Django's template loader knows that the corresponding template to the view is TipoDeMedio_detail.html However, on my production environment, which is set up with apache2 and mod_wsgi on a Ubuntu 20.04.2 LTS x86_64 Linode VM, the template loader fails to load the template of the same view, because it searches for it in all lowercase. Here is an example: Request Method: GET Request URL: http://45.79.4.38/calidad/TipoDeMedio/lista Django Version: 3.1.6 Exception Type: TemplateDoesNotExist Exception Value: calidad/tipodemedio_list.html Exception Location: /home/jonatan/django-rodam/venv/lib/python3.8/site-packages/django/template/loader.py, line 47, in select_template Python Executable: /home/jonatan/django-rodam/venv/bin/python Python Version: 3.8.5 Python Path: ['/home/jonatan/django-rodam/mysite', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/jonatan/django-rodam/venv/lib/python3.8/site-packages'] Server time: Mon, 21 Jun 2021 18:24:19 -0500 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/jonatan/django-rodam/mysite/templates/calidad/tipodemedio_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/jonatan/django-rodam/mysite/login/templates/calidad/tipodemedio_list.html … -
How to get a variable in another js file in django?
I am trying to use moovit embebed services. I want to put an origin and destination address automatically. So, I have this function in a js file that receives the origin address and open a new window. I don't know how to get this data from js in html. function print_moovitmap(origin) { origin_ad = origin; //Origin_ad is global window.open('/new', '_blank'); } I am working with django. I have also origin_ad in a form field with an id but I couldn't access to this form field in html. It gives me null. origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'origin_address'})) In html (null): console.log(document.getElementById('origin_address')); And in new.html: <div class="mv-wtp" id="mapa_moovit" data-to='' data-lang="es"> <script> var m = document.getElementById('mapa_moovit'); m.setAttribute("data-to", "Central Park"); m.setAttribute("data-from", "Times Sq"); </script> {% load static %} <script src="{% static 'moovit_script.js'%}"></script> </div> I need to set atribute data-from to origin_ad but I don't know how. Thank you -
How to do aritmethic operations with django queries and .count?
I want to get a value by using the amount of objects I have in my database and making operations over that and then displaying the result in the template (So I'm passing this value in the context). The answers I found was about making operations with model fields, and that doesn't help me. This is what I tried to do in the view. (status is a charfield with options, but it could be anything) def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) amount_one = mymodel.objects.filter(status='status1').count amount_two = mymodel.objects.filter(status='status2').count total_amount = amount_one + amount_two result_amount = (amount_one * 100) // total_amount context['result'] = result_amount return context This doesn't work, but you could get the idea of what I'm trying to do. -
Geo redirect same domain after slash with AWS
Lets say i have a website called abc.com, I'm planning on scale the website based on geo location, I have two ways in mind. The first way: paris.abc.com, london.abc.com The second way: abc.com/paris, abc.com/london The first way seems simpler with AWS, The idea being hosting different subdomains to different instances with different databases, Each subdomain is basically a completely different website. But I prefer the second way, What i have in mind is, Setting up geo redirect to different instances but to the same domain, "abc.com", Then have instance A redirect abc.com to abc.com/paris inside my django project, Have instance B do the same thing to abc.com/london. Now if i do it this way, What would happen if someone from london, Instead of typing the url abc.com, They typed abc.com/paris? Would they be able to access the paris page via instance A? (This is what i want, I want them to have acess) Or the page will be empty since the django project inside instances B(london) have no page called paris. Assuming both ways are achievable, If someone logged in paris.abc.com or abc.com/paris, How do u keep them logged in If they go to page london.abc.com or abc.com/london, A shared … -
Nothing renders on Django Template
building a news aggregator. I am collecting reddit and twitter posts using their APIs, and then I create a model object for each post, which is stored in my database. I'm then passing in these post objects as context into my template, looping through the context in the template with the hope to display the posts 'html' attribute (A model field I created) onto the page, which in turn embeds the post onto the screen. However, I can't figure out why my template page is still blank. No errors are thrown, and the model objects are being created because I can see them in the admin panel. I'll provide my models.py, views.py, and template to be taken a glance at. I appreciate and am grateful for any help/advice. models.py class Post(models.Model): post_type = models.CharField( max_length=20, null=True, blank=True) root_url = models.CharField(max_length=200, default="") html = models.TextField(default="") created_at = models.DateTimeField(auto_now_add=True) views.py def main(request): all_posts = Post.objects.all context = {'posts': all_posts} return render(request, "test.html", context) template {% block content %} {% autoescape off %} <div class="container"> <div class="row"> <div class="col-6"> <h3 class='text-center'>Twitter News</h3> {% for post in posts %} {% if post.post_type == 'twitter' %} <div class="mdl-card__media" id="timeline"></div> {{ post.html }} {% endif %} … -
DoesNotExist at /accounts/login/ (delate example.com from admin page)
I'm trying to configure Django App. I logged in to Django admin page and delated "example.com" from "Site". After that, I can not access the admin page or login page. Error message is here Exception Value: Site matching query does not exist. Exception Location: /home/app_admin/venv_ruling/lib64/python3.7/site-packages/django/db/models/query.py, line 437, in get Since I can not access admin page, I can not recover "example.com" as site. How can I recover it?? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Add label or modifying widget on django-filter form
I'm looking for a way of specifying what the select fields in the filter form are for, this is how it looks like right now: And is hard to understand what the select inputs are for, the ideal would be to change the default option ("Unkown" and "--------") but it should be custom for each one. Already tried that but couldn't find a way to do it, it is possible? If someone knows a way of doing this it would be great. Adding a label should be the easier way, but don't know how to do it. filters.py class PatientFilter(django_filters.FilterSet): class Meta: model = Patient fields = { 'dni': ['exact'], 'first_name': ['icontains'], 'last_name': ['icontains'], 'risk': ['exact'], 'status': ['exact'], 'ubication': ['exact'], 'supervisor': ['exact'], } HTML {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' field_class="mr-3 mt-3" %} <div class="mt-3"> {% bootstrap_button 'Filter' button_class="btn-secondary" %} <a href="{% url 'patients' %}" class="ml-3 btn btn-secondary">Clear</a> </div> </form> {% endif %} The select inputs are foreign keys, here is its definition in models.py status = models.CharField(max_length=15, choices=STATUS_CHOICES) ubication = models.ForeignKey(Ubication, on_delete=models.CASCADE) supervisor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) I'm using tables2 with django-filters. -
How to display content assigned to foreignkey DJango
I want to display content assigned to foreignkey. After clicking on user name display in new page all of his content. Something like in "/users/" display every users but after clicking on name go to "/users/1". class Users(models.Model): def __str__(self): return self.name image = models.CharField(blank=True, max_length=600) name = models.CharField(blank=True, max_length=80) description = models.TextField(blank=True) class Meta: verbose_name = "User" verbose_name_plural = "Users" class Content(models.Model): def __str__(self): return self.name name = models.CharField(blank=True, max_length=80) image = models.CharField(blank=True, max_length=600) description = models.TextField(blank=True) User = models.ForeignKey(Ekipa, on_delete=models.CASCADE, null=True, related_name='User') class Meta: verbose_name = "Content" verbose_name_plural = "Content" -
Dynamic Fields On A Serializer For A ForeignKey
I set up a serializer that is able to dynamically serialize the desired fields as specified in the Django Rest Framework docs. class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) >>> class UserSerializer(DynamicFieldsModelSerializer): >>> class Meta: >>> model = User >>> fields = ['id', 'username', 'email'] >>> >>> print(UserSerializer(user)) {'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'} >>> >>> print(UserSerializer(user, fields=('id', 'email'))) {'id': 2, 'email': 'jon@example.com'} How would I then add in a model that is related by ForeignKey to this and dynamically serialize the desired fields from that model? We could make the models class User(models.Model): id = IntegerField() username = CharField() email = EmailField() class Vehicle(models.Model): color = CharField() type = CharField year = DateField() driver = ForeignKey(User) and then based on the view either include color, type, year, or any combination of … -
Django admin model query url string on NOT EQUALS
I have a simple Django ForeignKey relationship between two models in postgreSQL. The logic here is the Sample object can optionally have a foreign key into a type of sample control. from django.contrib.postgres.fields import CICharField from django.db import models class Sample(models.Model): controls_applied = models.ForeignKey(SampleControl, null=True, blank=True, on_delete=models.SET_NULL) class SampleControl(models.Model): id = CICharField(max_length=200, primary_key=True) On the admin changelist for Sample, I am trying to create filter that queries all or none of Samples that have a specific control (in this case, we'll use a SampleControl with id='runcontrol'). I'm trying to craft the specific URI string to append to my changelist url as I have other filters I'm trying to run in conjunction. To get all samples with controls_applied= 'runcontrol', I can simply append the following string to my URL (notice the reference to the id of the foreign key): ?controls_applied__id=runcontrol But if I want to get all samples that are not run control, it's more complicated. Wasn't sure what to do, so I decided to use 'startswith', which has a convenient 'notstartswith' companion that will do the inverse. When I use this, I see that the following works: ?controls_applied__id__startswith=runcontrol However, the inverse ?controls_applied__id__notstartswith=runcontrol gives me an error: Unsupported lookup 'notstartswith' for … -
Financiamiento() got an unexpected keyword argument 'MontoProyecto'
I'm trying to make a post request, I have created the models as well, but for some reason, it is giving me the following error I understand that this mean there is some mistyped, but when I check the html and views.py, I don't see any mistake, everything should be in order financiamiento.html {% extends "Portafolio/layout.html" %} {%block content %} <br> <div class="text-center"> <form action="{% url 'financiamiento'%}" method="POST" style="max-width:800px;margin:auto;"> {% csrf_token %} <h1 class="mt-5">Perspectiva Financiera</h1> <h1 class="h3 mb-10 mt-2">Financiamiento</h1> <label class="sr-only"></label> <input name= "MontoProyecto" type="text" id="MontoProyecto" placeholder="Monto Aporte Proyecto"class="form-control"> <label class="sr-only"></label> <input name= "MontoPropio" type="text" id="MontoPropio" placeholder="Monto Aporte Propio"class="form-control"> <label class="sr-only"></label> <input name="MontoBanca" type="text" id="MontoBanca" placeholder="Monto Aporte Banca"class="form-control"> <label class="sr-only"></label> <input name="MontoPublico" type="text" id="MontoPublico" placeholder="Monto Aporte Publico"class="form-control"> <div class="d-grid gap-2 mt-3"> <input type="submit" class="btn btn-lg btn-primary"> </div> </form> </div> {% endblock %} views.py from django.http.response import HttpResponse from django.shortcuts import redirect, render from django.http import HttpResponse from .models import Proyecto, Financiamiento # Create your views here. def index(request): return render (request, "Portafolio/index.html",{ "financiamiento":Financiamiento.objects.all() }) def registroproyecto(request): if request.method == 'POST': NombreProyecto = request.POST.get('NombreProyecto') ResponsableProyecto = request.POST.get('ResponsableProyecto') EvaluadorProyecto = request.POST.get('EvaluadorProyecto') DescripcionProyecto = request.POST.get('DescripcionProyecto') Proyecto.objects.create(NombreProyecto=NombreProyecto, ResponsableProyecto=ResponsableProyecto, EvaluadorProyecto=EvaluadorProyecto, DescripcionProyecto=DescripcionProyecto) return redirect("/Portafolio") return render (request, "Portafolio/RegistroProyecto.html") def financiamiento(request): if request.method == 'POST': MontoProyecto = … -
django nginx upstream prematurely closed connection while uploading large data
I am getting this error: upstream prematurely closed connection while reading response header from upstream when I try to upload large data from an excel file to the server. I tried with only 10000 inputs with 4 rows each. It doesn't do this when I try it on my localhost, so this might be the remote server's config. This is what I currently have in my nginx.conf file: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; client_max_body_size 20M; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } I added the client_max_body_size 20M; line and restarted nginx but it was the same.