Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save the data of a html form in django
I have two html modals in a single page one for sign up and another for sign in. But i can't figure out a way to save that data in django database. I am new to django so i don't know how to relate a html file to django. I have linked it as a front page but as far as back end, i am totally lost. i need help from scratch. here is my html file. thanks in advance. <body> <ul> <li><a class="active" href="#home">Home</a></li> <li><a href="#about">About Us</a></li> <li><a href="#contact">Contact</a></li> </ul> <h1 style="color: white; text-align: center; padding: 260px 0px 0px 30px;">getTogether</h1> <h3 style="color: white; text-align: center;">A place to socialize and make friends</h3> <button onclick="document.getElementById('id01').style.display='block'" class="button button1">Sign Up</button> <div id="id01" class="w3-modal w3-animate-opacity"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span> <form class="modal-content animate" action="/home/user_profile" method="post"> {% csrf_token %} <div class="container"> <label><b>Name</b></label> <input type="text" placeholder="Enter Your Name" name="email" required> <label><b>Email</b></label> <input type="email" placeholder="Enter Email" name="email" required> <label><b>Contact Number</b></label> <input type="text" name="Phone Number" pattern="[7-9]{1}[0-9]{9}" placeholder="Enter Your Contact Number" name="email" required> <label><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" required> <label><b>Repeat Password</b></label> <input type="password" placeholder="Repeat Password" name="psw-repeat" required> <input type="checkbox" checked="checked"> Remember me <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p> <div class="clearfix"> <button type="button" … -
Python/django logging permissions error
When running a command using the manage.py script, django gives me a permission denied error: vagrant@vagrant:/opt/proj$ python3 manage.py migrate Traceback (most recent call last): File "/usr/lib/python3.5/logging/config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib/python3.5/logging/config.py", line 731, in configure_handler result = factory(**kwargs) File "/usr/lib/python3.5/logging/__init__.py", line 1008, in __init__ StreamHandler.__init__(self, self._open()) File "/usr/lib/python3.5/logging/__init__.py", line 1037, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) PermissionError: [Errno 13] Permission denied: '/var/log/django/debug.log' But I am in the correct group (as far as I can see), and I can touch the logfile using the shell: vagrant@vagrant:/var/log/django$ ls -la total 20 drwxrwxr-x 2 nobody www-data 4096 Jul 20 13:06 . drwxrwxr-x 12 root syslog 4096 Jul 20 12:37 .. -rwxrwxr-x 1 nobody www-data 11283 Jul 20 13:07 debug.log vagrant@vagrant:/var/log/django$ groups vagrant adm cdrom sudo dip www-data plugdev lxd lpadmin sambashare vagrant@vagrant:/var/log/django$ touch debug.log vagrant@vagrant:/var/log/django$ Can anyone help me understand what the issue is here ? -
Django & javascript: hidden div dynamically updated
I'm currently struggling with Django and javascript. I have a HTML table. Each row corresponds to a Django element I load from a SQL database. Something like this : <table> {% for item in list %} <tr tabindex="0" data-toggle="popover" data-trigger="focus" data-popover-content=".hidden" data-placement="right" onclick="snpTable()" > <td>{{ item.elem1 }}</td> <td>{{ item.elem2 }}</td> <td>{% for t in item.elem3_list %} {{t}}<br/> {% endfor %} </td> Now, when I click on a row, I want to have a new table that displays all the remaining information about this item. The platform I'm working on uses bootstrap, and thanks to other SO questions I've been able to display a table when a row is clicked. Basically, the last case on each row contains a div, hidden by default, that contains the table. I use bootstrap's popover method to display it when the is clicked. <div class="hidden"> <div class="popover-heading"> <!-- Just a heading with an element from the list --> </div> <div class="popover-body"> <table style="width:100%"> <tr><td>{{ item.elem4 }}</td></tr> <tr><td>{{ item.elem5 }}</td></tr> <tr><td>{{ item.elem6 }}</td></tr> <tr><td>{{ item.elem7 }}</td></tr> <tr><td>{{ item.elem8 }}</td></tr> <tr><td>{{ item.elem9 }}</td></tr> <tr><td>{{ item.elem10 }}</td></tr> </table> </div> </div> </td> </tr> <script>$("[data-toggle='popover']").popover('destroy'); </script> {% endfor %} </table> Nothing fancy, right? The elements 4, 5, and so on … -
Why Django show me the path to the template but do not load the template himselfe into the page?
In the static folder of my DjangoServer is located a template of the default webpage. It's decorated with some template blocks. If I load this template file, the path to the template is shown in the browser, it looks like, that the code is not loaded. If I store the template in an app/template folder and I extend this file. It works very well. I use the tutorial of Django but it still not working. Settings.py django.contrib.staticfiles is added to INSTALLED_APPS STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') static/html/basePage.html {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> {% block head %} <title>{% block title %}My amazing site{% endblock %}</title> {% endblock %} </head> <body> {% block body %} <header> {% block header %} <header> -- HEADER BANNER --</header> {% block menu %}<nav></nav>{% endblock %} {% endblock %} </header> <section> {% block section %} SECTION {% endblock %} </section> {% block footer %} <footer> -- FOOTER --</footer> {% endblock %} {% endblock %} </body> <script type="text/javascript" src="{% static 'angularjs/SOME_ANGULAR_FILES_LOADED.js' %}"></script> </html> index.html from an app {% load staticfiles %} {% extends "html/basePage.html" %} {% block menu %}<nav><a href="/appA">App A</a></nav>{% endblock %} {% … -
Set text in bold and vertical space with Django EmailMessage
In my script, User fills a Django form then two things : data are saved in my database and an email is sent to a support account. I'm looking for improve this little part from my Django web application. All this process works fine, but I would like to improve this part in my view : subject = "Ticket n° " + str(post.id) + " : " + str(post.Objet.encode('utf-8')) message = "Bonjour Datasystems, \n \n Vous avez un nouveau ticket en attente comportant les informations suivantes : \n " + "Nom : " + str(post.Nom.encode('utf-8')) + " \n Prénom : " + str(post.Prenom.encode('utf-8')) + " \n Société/Association client : " + str(request.user.last_name.encode("utf-8")) + " \n N° Téléphone : " + str(post.Telephone.encode("utf-8")) + " \n Adresse Email : " + str(post.Mail.encode("utf-8")) + " \n Description du problème : " + str(post.Description.encode("utf-8")) image = post.Image mail = EmailMessage(subject, message, 'support@datasystems.fr', ['support@datasystems.fr'], html_message='This is <b>HTML</b> Content') mail.attach_file(image.path) mail.send() I would like to write this part with bold character before each variable. For example in my email : Nom : test (currently) Nom : test (What I would like to get) And make vertical space where I put both \n : For example : … -
How to draw a matplot lib (python) polar scatter chart in django?
I am writing a web application where I have to draw a polar scatter chart(https://matplotlib.org/examples/pie_and_polar_charts/polar_scatter_demo.html) in the webpage. The polar scatter chart is generated using python matplotlib and then is converted into JSON format and displayed on the webpage using mpld3 library(https://mpld3.github.io/install.html). Here is my code to show an empty polar scatter chart: <script src=".../mpld3/d3.v3.min.js"></script> <script src=".../mpld3/mpld3.v0.3.1.dev1.min.js"></script> <div class="col-sm-7"> <div id="fig01"></div> <script> mpld3.draw_figure("fig01",{"id": "el44281963893827960", "plugins": [{"type": "reset"}, {"type": "zoom", "button": true, "enabled": false}, {"type": "boxzoom", "button": true, "enabled": false}], "height": 480.0, "data": {}, "width": 640.0, "axes": [{"yscale": "linear", "id": "el44281963940408456", "axesbg": "#FFFFFF", "xdomain": [0.0, 6.283185307179586], "images": [], "xlim": [0.0, 6.283185307179586], "axesbgalpha": null, "collections": [], "ydomain": [0.0, 4.0], "markers": [], "texts": [], "xscale": "linear", "lines": [], "sharey": [], "paths": [], "axes": [{"grid": {"color": "#B0B0B0", "alpha": 1.0, "dasharray": "none", "gridOn": true}, "fontsize": 10.0, "scale": "linear", "visible": true, "nticks": 8, "position": "bottom", "tickformat": ["3", "2", "1", "8", "7", "6", "5", "4"], "tickvalues": [0.0, 0.7853981633974483, 1.5707963267948966, 2.356194490192345, 3.141592653589793, 3.9269908169872414, 4.71238898038469, 5.497787143782138]}, {"grid": {"color": "#B0B0B0", "alpha": 1.0, "dasharray": "none", "gridOn": true}, "fontsize": 10.0, "scale": "linear", "visible": true, "nticks": 4, "position": "left", "tickformat": ["Gen 1", "Gen 2", "Gen 3", ""], "tickvalues": [1.0, 2.0, 3.0, 4.0]}], "zoomable": true, "bbox": [0.22375000000000006, 0.10999999999999999, 0.5774999999999999, 0.77], "sharex": [], "ylim": [0.0, … -
Hyperlinking the Query Parameters with Django Rest Framework
I was just wondering if there is a way to include the extra query parameters within HyperlinkIdentityField using the Django REST framework? i.e. /api/groups/?level=specificlvl as an automatically generated url pointing to a specific level Many thanks! -
Django ModelForm inheritance, subclassing and passing in an instance
I have an address model: class Address(models.Model): line1 = models.CharField(max_length=100) .... and an AddressForm: class AddressForm(forms.ModelForm): class Meta: model = Address Several models will have an address field, so instead of copy+pasting all of the fields from the AddressForm, I wanted to extend the AddressForm so I can reuse it. Specifically, I want to avoid copying+pasting all of the form fields into other app's forms and have only one AddressForm.is_valid() function. For example, an Order will have an Address, so my plan was to do something like this: class Order: address = models.ForeignKey(Address, on_delete=models.CASCADE) class OrderForm(AddressForm): class Meta: model = Order However, when I pass an instance to the OrderForm from the order/views.py, I'm passing instance of an Order and all of the AddressForm fields show up as blank: form = OrderForm(instance=order) How do I initialize the AddressForm fields from the order.address field? I had tried this: class OrderForm(AddressForm): def __init__(self, *args, **kwargs): kwargs['instance'] = kwargs['instance'].address super(OrderForm, self).__init__(*args, **kwargs) But it doesn't work. Is there a way to do this? Or a better way of reusing the AddressForm? Or would this only work if Order was a subclass of Address? Cheers, -
How to create multi tenant schemas and users in django?
I am still learning all these things. i have referred https://django-tenant-schemas.readthedocs.io/en/latest/ ,this link but i was not able to understand. please help me if know anyone knows. thank you -
Is there an example of Django based web app using Token Authentication
I am looking for a simple example of Django web app (purely Django) using Token Authentication Where a user logins gets some view do something and logout I am basically looking for use of Token Authentication in web apps....I want to know how will I get to know which user has requested which view and how to pass token to views and urls log in log out means creating token and deleting them and between that performing some actions. -
Wagtail not pulling through custom field panels
I'm overriding the wagtail AbstractFormField panel attribute in the following way: ... before_input = RichTextField(verbose_name=_('before input'), blank=True) after_input = RichTextField(verbose_name=_('after input'), blank=True) panels = [ FieldPanel('label'), FieldPanel('before_input'), FieldPanel('after_input'), FieldPanel('required'), FieldPanel('field_type', classname="formbuilder-type"), FieldPanel('choices', classname="formbuilder-choices"), FieldPanel('default_value', classname="formbuilder-default"), ] where the other panels are what comes out of the box. This is working perfectly on the admin side and also saving as rich text into my database I am pulling this through to my form in my template in the following way: <form action="{% pageurl page %}" method="POST" class="lm-ls1" id="feedback-form"> {% csrf_token %} {{ form.question1.help_text }} <!-- Simpler non interable way --> {{ form.question1.before_input }} <p>---------------</p> {% for row in form.fields.values %} {{row.choices}} <p>---------------</p> {{row.help_text}} <p>---------------</p> {{row.before_input}} {% endfor %} </form> But I am only getting html output for the form panels excluding the before_input and after_input ones I am getting through roughly the following: Overall, how did you feel about the service you received today? --------------- [('Very satisfied', 'Very satisfied'), ('Satisfied', 'Satisfied'), ('Neither satisfied nor dissatisfied', 'Neither satisfied nor dissatisfied'), ('Dissatisfied', 'Dissatisfied'), ('Very dissatisfied', 'Very dissatisfied')] --------------- Overall, how did you feel about the service you received today? --------------- --------------- How can I access the before_input field panel data stored in the … -
Wagtail - How to add a disabled choice to drop down form field?
I'm fairly new to Wagtail and just building my first form. I would like to add a disabled choice to a drop down field to act as a placeholder/field title. Any advice is appreciated. Thanks -
Getting TypeError while fetching value from table using Python and Django
I am getting error while fetching value from table using Python and Django. I am explaining the error below. Error: Exception Type: TypeError Exception Value: not all arguments converted during string formatting I am explaining my code below. rname = request.POST.get('rname') keyword = '%' + rname + '%' all_value = Meeting.objects.raw("SELECT * FROM booking_meeting WHERE room_name LIKE ? ", (keyword,)) Here I am getting the error. Please help me to resolve this error. -
Stopping multiple view calls generated via frenzied button clicks (Django app)
I'm uploading an image file in a basic Django web app. There's an upload button in the html template wrapped around by a form tag. Once the upload button is pressed, the underlying view takes over and processes image upload. In the Chrome browser of my colleague's Macbook, pressing upload multiple times really quickly manages to call the underlying function multiples times too. I end up getting a plethora of copies of the image being uploaded. However, this isn't replicatable in my own environment's Firefox (Ubuntu OS). Seems this issue is browser sensitive? In any case, how do I cut off this code behavior? If the user goes into a click frenzy, I don't want multiple images to go up. Can someone guide me how to handle this in Django? I would prefer a non-JS, server solution too. Note: Let me know if you need to see my related code. -
How site administration is managed in Django-Angular2 project
I have to use Angular 2+ for front-end and Django as back-end, in my project. Usually Django provides the '/admin' URL through which we can access the admin portal to do all the site-administration stuffs. But to use Angular 2+ as front-end we need to convert the whole back-end (Django) into REST API, which is actually recommended. In this case how can we use the Django Admin URL or its utilities from Angular URLs? Or else whether I have to replicate Django Admin in Angular 2. It will be a great help if someone can give me some ideas on this. -
Set some text to a text area on selecting a value using django
I have a form, with a text area and two drop downs. One drop down is for category and another one is for product. One selecting a category, I can get it's products well in the second drop down. Code for that is give n below. category = forms.ModelChoiceField( queryset=Cat.objects.all(), required=False, label='Category', widget=forms.Select( attrs={'filter-for': 'product'} ) ) product = ChainedModelChoiceField( queryset=Product.objects.none(), chains=( ( 'category'), ), required=False, label='Product', widget=APISelect( api_url='/api/app_name/product/?category={{category}}', ) ) When i select a product from the product drop down, i would like to display the selected product name in the text area. If change product selected, new product name should appear in the text area. How can we do it? Is there any nice way to do it without writing some jQuery code? Something like the above drop down code done without any jQuery code. -
Failing to install a fixture after adding one more TestCase
I'm almost starting to wonder if there is some limit on how many TestCases a Django app can have, so I need your help to figure out how to avoid this problem and have functional tests in my app with all of the TestCases. My Django (v1.10.7) app has 4 TestCases, which run fine. As soon as I add a 5th TestCase, running the tests all together with python3 ./manage.py test myapp starts resulting in a random one of the old TestCases failing with: ERROR: setUpClass (myapp.tests.RandomOldTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/db/backends/base/base.py", line 206, in _cursor return self.create_cursor() File "/usr/lib/python3/dist-packages/django/db/backends/postgresql/base.py", line 211, in create_cursor cursor = self.connection.cursor() psycopg2.InterfaceError: connection already closed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/test/testcases.py", line 1019, in setUpClass 'database': db_name, File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 130, in call_command return command.execute(*args, **defaults) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/lib/python3/dist-packages/django/core/management/commands/loaddata.py", line 64, in handle self.loaddata(fixture_labels) File "/usr/lib/python3/dist-packages/django/core/management/commands/loaddata.py", line 104, in loaddata self.load_label(fixture_label) File "/usr/lib/python3/dist-packages/django/core/management/commands/loaddata.py", line 167, in load_label obj.save(using=self.using) File "/usr/lib/python3/dist-packages/django/core/serializers/base.py", line 201, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/usr/lib/python3/dist-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, … -
Django: Add related objects that are part of a set
Apologies for the terrible title, I'm not sure how best to phrase this. I am using django cartridge as a base model for my products. https://github.com/stephenmcd/cartridge/blob/master/cartridge/shop/models.py#L105 I have more complex products that can have multiple options stored with in option sets, for example: Shirts: Sizes: Small Medium Large Obviously the same shirt can be had in a Small, Medium or Large size but I want our admins to be able to add extra sizes (or other options) at a later date. To express these I am using the following models: # A container that can hold multiple ProductOptions class ProductOptionSet(models.Model): title = models.CharField(max_length=100) class ProductOption(models.Model): option_set = models.ForeignKey(ProductOptionSet, related_name="test") option_title = models.CharField(max_length=100) option_slug = models.CharField(max_length=100, help_text='A system friendly version of the value') # Inherited from my CMS system. class ShirtProduct(Product): sizes = models.ManyToManyField(ProductOption, related_name="shirt_size") I am looking to save these options based on a simple string of information e.g size = 'medium' in the ShirtProduct save() method. Currently I have the following: def save(self, *args, **kwargs): [...] if key is "size": option = ProductOption.objects.get(option_slug=value) self.sizes.add(option) super(ShirtProduct, self).save(*args, **kwargs) However this appears to do nothing. What am I missing? -
Eager Dumping for Nested Schemes - Marshmallow SQLAlchemy
i am working on a django rest api project, i have the following codes: show_repository.py: @staticmethod def create_show(time, price, hall_id, movie_id): show = Show( time=time, price=price, hall_id=hall_id, movie_id=movie_id ) session.add(show) session.commit() return show show_controller.py: created_show = self.show_repo.create_show( movie_id=movie_id, hall_id=hall_id, time=request.data['time'], price=request.data['price'], ) data_type = 'show' serialized_created_show = serializer.dump(created_show) return Response({data_type:serialized_created_show}) show_serializer.py: class MovieSchema(ModelSchema): class Meta: model = Movie class HallSchema(ModelSchema): class Meta: model = Hall class ShowSchema(ModelSchema): movie = fields.Nested('MovieSchema', exclude=('shows',)) hall = fields.Nested('HallSchema', exclude=('shows', 'seats',)) class Meta: model = Show exclude = ('reservations',) i already have a records in my DB for halls and movies, i want to create a show as implemented in the show_repository.py/ create_show, so my created object will be returned with all information about the show i have been created, then the object deserialized with marshmallow's serializer as i implemented in show_serializer.py; but, the sql queries applied when deserialization was as following: 2017-07-20 12:58:20,835 INFO sqlalchemy.engine.base.Engine SELECT `show`.id AS show_id, `show`.movie_id AS show_movie_id, `show`.hall_id AS show_hall_id, `show`.time AS show_time, `show`.price AS show_price FROM `show` WHERE `show`.id = %s 2017-07-20 12:58:20,835 INFO sqlalchemy.engine.base.Engine (61L,) 2017-07-20 12:58:20,838 INFO sqlalchemy.engine.base.Engine SELECT movie.id AS movie_id, movie.name AS movie_name, movie.description AS movie_description, movie.duration AS movie_duration FROM movie WHERE movie.id = … -
Make an union of prefetch_related from different foreign keys
I have three models, let's take an imaginary example: class Entity(models.Model): name = models.CharField() class EntityAssociation(models.Model): buddy1 = models.ForeignKey(Entity, related_name='+') buddy2 = models.ForeignKey(Entity, related_name='+') class EntityPhoto(models.Model): entity = models.ForeignKey(Entity, null=True) association = models.ForeignKey(EntityAssociation, null=True) title = ... We have some people (Entity), that can share personal photos of themselves. We also have some relations between entities (represented by EntityAssociation) that can also share photos of them together. For a single entity, I can retrieve all the photo associated to an entity, either directly or through an association, doing so: obj = Entity.objects.last() EntityPhoto.objects.filter( Q(entity=obj) | Q(association__buddy1=obj) | Q(association__buddy2=obj) ) What I want is being able to prefetch all the photos of a set of entities selected. A typical use-case would be: for entity in Entity.objects.all().prefetch(???): print(entity.name, 'has', len(entity.photos_prefetched), 'photos') print([x.title for x in entity.photos_prefetched]) And this should be returning all the photos. A solution with three queries (Entity listing, prefetch through entity, prefetch through association attr ; two would be perfect) would satisfy me but the more important is to be able to iterate through a single list, on each entity I tried to look the internal code of Prefetch but it looks like a prefetch is tied to a … -
Combined forms in Django for attributes of parent model
Having a lot of models, I have started to factor out common blocks with the aim of my database reaching second normal form. As the application should be used by a sales team, most entries are some kind of orders. An excerpt from my models file looks like this: class Order(models.Model): dl = models.CharField(max_length=100) cl = models.CharField(max_length=100) (...) class Setup(models.Model): order = models.ForeignKey(Order) # could be OneToOneField() name = models.CharField(max_length=200) package = models.CharField(choices=( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ('XL', 'Extra large'), ('C', 'Custom') ), max_length=2) server = models.ForeignKey(Webserver) (...) While it does not make any logical sense to keep the order details out of the model for a setup order, it helps to keep the project maintainable, since setup orders are not the only things coming in and this way you can change the order model and all other models/orders are updated too. Here comes the problem. For attributes like Setup.server Django's default behaviour of creating a dropdown with all web servers the company can offer is totally fine. If the team decides to add another one, it can simply create another server option on another page. But for order, I would like that the OrderForm is included on … -
Get Email or not of facebook by using django social auth
In django social auth, How to check facebook is providing email or not. Beacause in facebook email is optional and according to our requiremnt email is compulsory? -
Django decimal rounding
I have this function and I want to allow only 2 decimal places for the value. This is not a model field but it's being calculated from them. What is the right way to do it? Thanks in advance! @property def value(self): value = self.average_flow_rate * (self.d_n / 1000) / self.nu if 2320 < value < 4000: return 4000 else: return value -
Django Nested Serializer does not find attribute
This are my models class OWNER_STORE(models.Model): _id = models.CharField(max_length=120, unique=True, default=uuid.uuid4) MSE_STORE_TYPE = models.ForeignKey(STORE_TYPE) MSE_OWNER_INFO = models.ForeignKey(OWNER_INFO, related_name='STORES') STORE_NAME = models.CharField("STORE_NAME", max_length=250, null=True, blank=True) STORE_ID = models.IntegerField("STORE_ID", null=True, blank=True) STORE_ADDRESS_HOUSE = models.CharField("STORE_ADDRESS_HOUSE", max_length=250, null=True, blank=True) STORE_ADDRESS_ROAD = models.CharField("STORE_ADDRESS_ROAD", max_length=250, null=True, blank=True) STORE_ADDRESS_VILLAGE = models.CharField("STORE_ADDRESS_VILLAGE", max_length=250, null=True, blank=True) STORE_ADDRESS_UNION = models.CharField("STORE_ADDRESS_UNION", max_length=250, null=True, blank=True) STORE_ADDRESS_THANA = models.CharField("STORE_ADDRESS_THANA", max_length=250, null=True, blank=True) STORE_ADDRESS_DISTRICT = models.CharField("STORE_ADDRESS_DISTRICT", max_length=250, null=True, blank=True) STORE_ADDRESS_DIVISION = models.CharField("STORE_ADDRESS_DIVISION", max_length=250, null=True, blank=True) STORE_EMPLOYEE_STATUS = models.BooleanField("EMPLOYEE_STATUS") STORE_NUMBER_OF_EMPLOYEE = models.IntegerField("NUMBER_OF_EMPLOYEE", null=True, blank=True) STORE_AVG_REVENUE = models.IntegerField("STORE_AVG_REVENUE", null=True, blank=True) STORE_AVG_COGS = models.IntegerField("STORE_AVG_COGS", null=True, blank=True) STORE_AVG_PROFIT = models.IntegerField("STORE_AVG_PROFIT", null=True, blank=True) STORE_CUSTOMER_CREDIT_LIMIT = models.IntegerField("CUSTOMER_CREDIT_LIMIT", null=True, blank=True) STORE_BUSINESS_TARGET = models.IntegerField("BUSINESS_TARGET", null=True, blank=True) STORE_REORDER_THRESHOLD = models.IntegerField("REORDER_THRESHOLD", null=True, blank=True) STORE_PASSWORD = models.TextField("STORE_PASSWORD", max_length=50, default=None, null=True, blank=True) def __str__(self): return str(self.id) class MSE_EMPLOYEE(models.Model): emp_id = models.IntegerField(null=True, blank=True) store = models.ForeignKey(OWNER_STORE) MSE_EMPLOYEE_ID = models.IntegerField(null=True, blank=True) MSE_EMPLOYEE_NAME=models.CharField(max_length=250, null=True, blank=True) MSE_EMPLOYEE_MOBILE_NUMBER = models.CharField(max_length=250, null=True, blank=True) MSE_EMPLOYEE_JOINING_DATE = models.DateField(null=True, blank=True) MSE_EMPLOYEE_SALARY = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.MSE_EMPLOYEE_NAME) For my serializers.py, I did this class STORE_EMPLOYEE_SERIALIZER(serializers.ModelSerializer): employees = EMPLOYEE_SERIALIZER(many=True) class Meta: model = OWNER_STORE fields=("MSE_STORE_TYPE", "MSE_OWNER_INFO", "STORE_NAME", "STORE_ID", "STORE_ADDRESS_HOUSE", "STORE_ADDRESS_ROAD", "STORE_ADDRESS_VILLAGE", "STORE_ADDRESS_UNION", "STORE_ADDRESS_THANA", "STORE_ADDRESS_DISTRICT", "STORE_ADDRESS_DIVISION", "STORE_EMPLOYEE_STATUS", "STORE_NUMBER_OF_EMPLOYEE", "STORE_AVG_REVENUE", "STORE_AVG_COGS", "STORE_AVG_PROFIT", "STORE_CUSTOMER_CREDIT_LIMIT", "STORE_BUSINESS_TARGET", "STORE_REORDER_THRESHOLD", "STORE_PASSWORD", "employees") I was hoping that with a get request, I would … -
400 Bad Request Request Header Or Cookie Too Large -- Making django application in production iusing Nginx Ubuntu on AWS
i'm trying to make my django application in production on an ubuntu AWS instance using nginx as a web server, i followed this tutoriel which worked for many persons : "https://jee-appy.blogspot.fr/2017/01/deply-django-with-nginx.html?showComment=1500480504935". The problem is that i'm having a "400 Bad Request Request Header Or Cookie Too Large" while trying to access my website". I have delete my cash and cookie and also increased the large_client_header_buffers but didn't resolve the problem. This is my file /etc/nginx/nginx.conf: user www-data; worker_processes 4; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 20000; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; gzip on; gzip_http_version 1.0; gzip_comp_level 2; gzip_proxied any; gzip_vary off; gzip_types text/plain text/css application/x-javascript text/xml application/xml application/rss+xml appl$ gzip_min_length 1000; gzip_disable "MSIE [1-6]\."; server_names_hash_bucket_size 64; types_hash_max_size 2048; types_hash_bucket_size 64; large_client_header_buffers 4 16k; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } And my file /etc/nginx/sites-available/mywebsite.conf : upstream sample_project_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/ubuntu/venv_mywebsite/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name mywebsite.com; client_max_body_size 4G; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log; location /static/ { …