Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show number of objects in Many to Many Relationship? (Django)
I have a simple blog created in Django with Posts and Comments for each post. I'm trying to show the total number of comments for each post on the home page but I can't get the total to show. Here's my model: class Post(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) title = models.CharField(max_length=100, blank=False) content_text = models.TextField(blank=False, max_length=3000) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Comment(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) post = models.ForeignKey(Post, on_delete= models.CASCADE) content_text = models.TextField(max_length=500) created_date = models.DateTimeField(auto_now_add=True) My views.py: def home(request): posts = Post.objects.all() return render(request, 'post/home.html', {'posts': posts}) And lastly my html file: {{ post.comments.count }} The other information displays correctly such as {{post.title}}. Any ideas what I'm doing wrong? Thanks! -
How to remove currently image path and clear check box in django forms?
I want to remove this field from from django forms. enter image description here forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = '__all__' exclude=['user'] -
Template for Carousel not showing context variable
I have made a Slider Model which contains 3 images and Texts related to it to slide in a Carousel My problem is that I want these images to be shown from the newest to oldest. If I remove the {% if sliders %} {% for slider in sliders %} the latest image only appears because in the views it is filtered by .latest('timestamp') I have also tried to replace .latest('timestamp') in the views with .all() it still didn't work This is the model: class Slider(models.Model): title = models.CharField(max_length=60) image = models.ImageField(blank=False, upload_to='Marketing') header_text = models.CharField(max_length=120, null=True, blank=True) middle_text = models.CharField(max_length=120, null=True, blank=True) footer_text = models.CharField(max_length=120, null=True, blank=True) button_text = models.CharField(max_length=120, null=True, blank=True) active = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title def get_image_url(self): return "%s/%s" % (settings.MEDIA_URL, self.image) I've had help with the view which is as follows: class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) try: context['marketing_message'] = MarketingMessage.objects.filter( active=True).latest('timestamp') except MarketingMessage.DoesNotExist: context['marketing_message'] = None try: context['slider'] = Slider.objects.filter( active=True).latest('timestamp') except Slider.DoesNotExist: context['slider'] = None return context This is the template: {% if sliders %} {% for slider in sliders %} <div class="carousel-item {% if forloop.first … -
CSS file isn't applying to the page, not loading under sources
I was trying to link a css file to my html, and for some reason the css won't load in. Below I'll supply the html and css code. When I open the page source, the css href works fine, I can click on it and it takes me to the css file, but when I inspect I can see that the css file is not part of sources. I've tested my code on JSFiddle and it works fine there, as well as on the snippet here. I also tried pressing ctrl + f5 and shift + f5 to refresh the page without caches, but nothing changed. So I don't know what else to do to fix this. I've been doing it on Chrome so I tested it real quick on Firefox but still, no changes. Thanks in advance for any help. raw html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> <link rel="'stylesheet" type="text/css" href="{% static 'polls/styles.css' %}"> </head> <header> <div class="site-header" width="100%" height="100px"> <h3><a class="site-header-link" href="/polls">Home</a></h3> </div> </header> <body> {% block content %}{% endblock %} </body> </html> Runnable html and css. li a { color: green; } body { background: grey; } .question-display … -
Join two sets of data of the same table in django
I want to select two sets of data from the same table and them join them using a common field class modelA(models.Model): year = models.IntegerField() week = models.IntegerField() sales = models.IntegerField() pillar = models.IntegerField() I want two select data from the (for example) week 8 and 9 of the year, then join them using the corresponding pillar so i get something like this: Using sql i think it should look like this, but i don't know how to translate that to django select * from ( select * from data where year = 2020 and week = 8 ) as A join ( select * from data where year = 2020 and week = 9 ) as B on A.pillar = B.pillar -
usage of ('/') in the following django code
I started a todo app tutorial and having a problem into fully understanding code in this part of it: def index(request): tasks = Task.objects.all() form= TaskForm() if request.method == "POST": form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') ''' just the part which used redirect('/') , what is the meaning of this sign (( ('/') )) and if you could explain to me why is it important to specify for the app that if the request method is POST do the following moves? -
Save successfully validated form fields when other fields fail
I have a rather long form including validation which I would like users to fill out. If the user submits the form successfully then it is saved to the db. I am aware that some users may attempt to submit the long form, only to have it raise validation errors, then leave my site and return to complete it later. I would like the form fields which are successfully validated to be saved (or is it possible to have them save automatically without the user needing to press the submit button?) so if the user exits the site they can later return and only have the fields which failed validation blank, not the entire form. views.py def needs_analysis(request): if request.method == 'POST': form = PersonalInformationForm(request.POST, request.FILES, instance=request.user.personalinformation) if form.is_valid(): form.save() return redirect('enrolment-index') else: form = PersonalInformation(instance=request.user.personalinformation) context = { 'form' : form } return render(request, 'enrolment/personal_info.html', context) Thank you. -
"FieldList" with foreign objects
Let's say I have cars running in different races. I want an ordered list in Race with the cars that will run. The problem is I want to manually modify that list from admin interface. class Car(models.Model): id = models.CharField(max_length=16, primary_key=True) class Race(models.Model): title = models.CharField(max_length=255) start_grid = models.ForeignKey(Car,on_delete=models.CASCADE) I have read many posts about ordering on related ForeignKey based on some filters like creation date or so, but this particular case requires to define a manual order. Don't exist some kind of models.ListField so my solution is to create a list of related Car ids and store JSON string in Race. But feeling that is not a good idea How can I create a field that contains an ordered list of foreign objects/id and be compatible with modify the order from admin interface? -
DJANGO - static doesnt load when using <int:pk>
I am a newbie and I tried to solve this problem now for hours. My CSS files work normally on every other url but when I enter OrderUpdateView.as_view() it doesn't work anymore. It shows the site but there is no css styling. I can send forms.py if needed. from django.conf.urls import url from django.urls import path from .views import * urlpatterns = [ url(r'^$', index, name='index'), url(r'^profile$', profile, name='profile'), url(r'^order/', OrderListView.as_view(), name='order'), url(r'^create/', CreateOrderView.as_view(), name='add_order'), path('update/<int:pk>/', OrderUpdateView.as_view(), name='edit_order'), path('done/<int:pk>/', done_order_view, name='done_order'), path('delete/<int:pk>/', delete_order, name='delete_order'), path('action/<int:pk>/<slug:action>/', order_action_view, name='order_action'), # ajax_calls path('ajax/search-products/<int:pk>/', ajax_search_products, name='ajax-search'), path('ajax/add-product/<int:pk>/<int:dk>/', ajax_add_product, name='ajax_add'), path('ajax/modify-product/<int:pk>/<slug:action>', ajax_modify_order_item, name='ajax_modify'), ] Here are my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'bz28yb5yaw37@=!@&3e@e)1a)p1!_zt)wxs5a8*s%qhv21&sjk' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'inventory', 'django_tables2', 'import_export', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'inventory_management_system.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
Template not displaying any data in Django application (Django 3.05)
Basically, I'm building a Django application that's like a blog. So, my "social" page is supposed to display posts (that right now I'm adding through the admin page). However, when I load that page, nothing shows up. Here's my views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Posts # Create your views here. def home(request): context = { 'posts' : Posts.objects.all() } return render(request, 'social/social.html', context) Here's my models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Posts(models.Model): post_title = models.CharField(max_length = 20, help_text = 'Enter post title') post_text_content = models.TextField(max_length = 1000) post_author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) post_date = models.DateField(auto_now = True, auto_now_add = False) ### Make seperate model for image content ### class Meta: ordering = ['post_title', 'post_author', 'post_date', 'post_text_content'] def __str__(self): return self.post_title class Author(models.Model): first_name = models.CharField(max_length = 100) last_name = models.CharField(max_length = 100) date_of_birth = models.DateField(null = True, blank = True) user_name = models.CharField(max_length = 20) class Meta: ordering = ['user_name', 'first_name', 'last_name', 'date_of_birth'] def __str__(self): return str(f'{self.first_name}, {self.last_name}, {self.user_name}') Here's my social.html: {% extends "social/base.html" %} {% block content %} <h1>Your Feed</h1> <p>This is your feed. Here, you'll see posts from people you follow.</p> … -
Cannot integrate Django and Charts.js, data wont pass from views
Cannot pass data from Django Views to template in which im using charts.js garphs to display my graph. The paid and unpaid fields wont show on graph but the labels does. How do i fix that. Whats the right syntax. Here's the code: My View: def graph2(request): labels = [] data1 = [] data2=[] queryset = due.objects.order_by('-paid')[:10] for Due in queryset: labels.append(Due.months) data1.append(Due.paid) data2.append(Due.unpaid) return render(request, 'account/graph2.html', { 'labels': labels, 'data1': data1, 'data2': data2, }) Template: <script> new Chart(document.getElementById("bar-chart-grouped"), { type: 'bar', data: { labels: {{ labels|safe }}, datasets: [{ barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, data: {{ data1|safe }} }], datasets: [{ barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, data: {{ data2|safe }} }] }, options: { title: { display: true, text: 'Population growth (millions)' } } }); </script> Model: class due(models.Model): months= models.CharField(max_length=30) paid = models.PositiveIntegerField() unpaid = models.PositiveIntegerField() def __str__(self): return "{}-{}".format(self.months, self.paid,self.unpaid) -
If i have to run cron job every Friday at 10am, is this the rite setting: 0 17 5 * * *
If i have to run cron job every Friday at 10am, is this the rite setting: 0 17 5 * * * Thanks -
Django non-static content not rendering
I'm using kubernetes and containers. nginx ingress controller. Also nginx container is serving up static content. The landing page (static) works just fine (checked with incognito, no caching). Soon as I go to a page that requires rendering something from the backend, it times out. I logged into the containers and cannot see any immediate issues in the log files or elsewhere. I shut down all the containers and started them fresh. Still nothing from the Django side is responding. Here is my nginx config (in Kubernetes/yaml format): apiVersion: v1 kind: ConfigMap metadata: name: nginx-config data: nginx.conf: | events { worker_connections 1024; } http { server { access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; listen 8080; server_name localhost; location ^~ /.well-known/acme-challenge/ { default_type "text/plain"; } location /static/ { autoindex on; alias /code/core/static/; include /etc/nginx/mime.types; } location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8080/; } } } I can't tell what the issue is. Any ideas on how to troubleshoot? -
Bootstrap django - nav dropdown issue
Hi this is my first django project. I am trying to implement base templating. Using django 3 and free sb admin 2 template. I am having an issue with nav dropdown, what i am missing ? I was also having issue with sidebar but fixed that with templatetags. Please check my template attachment here. This is what it currently looks like Thanks in advance -
FileNotFoundError at /main/insert_phone/
I am building a django app which sends texts using twilio. I'm trying to have it get the body of the message from a text file which is in the same directory as my views.py file, which is where the code for sending the text is. I'm getting this error: "FileNotFoundError at /main/insert_phone/ [Errno 2] No such file or directory: 'textgenrnn_texts.txt'" and I'm not sure why because the name of the file is correct. Here is the part of the views file where the issue is: from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from django.core.exceptions import ValidationError # import pymsgbox from .models import Phone from .forms import Post import subprocess from twilio.rest import Client ... def insert_phone_item(request: HttpRequest): phone = Phone(content=request.POST['content']) try: phone.full_clean() except ValidationError: return redirect('/main/list/') phone.save() # get receiver from postgres db reciever = Phone.objects.values_list('content', flat=True).distinct() # get text body from file with open('textgenrnn_texts.txt', 'r') as myfile: text = myfile.read() client.messages.create(to=reciever, from_=sender, body=text) return redirect('/main/list/') -
Django REST User Creation/Authentication
This question is based on the one here. I am setting up a Django REST Framework for my web app and am trying to set up User accounts. Based on the REST documentation, they put all of their account code in their example in the main project directory and a separate application so did that as well. Here is what I have: urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls import url from rest_framework import routers from . import views router = routers.DefaultRouter() router.register('users', views.UserViewSet) urlpatterns = [ path('admin/', admin.site.urls), url('', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class Meta: model = User # Tuple of serialized model fields (see link [2]) fields = ( "id", "username", "password", ) views.py from rest_framework import viewsets, permissions from rest_framework.generics import CreateAPIView from django.contrib.auth.models import User from .serializers import UserSerializer # Create your views here. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class CreateUserView(CreateAPIView): model = User permission_classes = [ permissions.AllowAny ] serializer_class = UserSerializer I have tried using the Boomerang … -
Django Serializer showing "character": "Dictionary object (256)" as opposed to the actual character
I am using Django rest framework and I am trying to do a JOIN on a GET command. I have the following view: class CharacterView(APIView): permission_classes = (AllowAny,) def get(self, request, user_id): character_saves = Char.objects.select_related('character').filter( user_id=user_id) serializer = CharacterSerializer(character_saves, many=True) return Response({"characters": serializer.data}) And the following serializer: class CharacterSerializer(serializers.Serializer): character_id = serializers.IntegerField() user_id = serializers.IntegerField() active = serializers.BooleanField() character = serializers.CharField() def create(self, validated_data): return Char.objects.update_or_create( user_id=validated_data.pop('user_id'), character_id=validated_data.pop('character_id'), defaults=validated_data ) Yet, I am getting the following data: "characters": [ { "character_id": 256, "user_id": 1, "active": true, "character": "Dictionary object (256)" }, { "character_id": 260, "user_id": 1, "active": true, "character": "Dictionary object (260)" } ] Instead of giving me the actual item I want, it gives me a dictionary object. This is almost correct, however I am guessing I am configuring something wrong in my query or serializer, preventing me from getting the raw value. How do I get the actual value here, rather than "Dictionary object (260)"? -
Django: Manipulate Form Input
I want to be able to multiply the user's input by 2 (if the user inputs 4 on a form, save 8). I haven't been able to figure out how I might go about doing this. Any ideas? -
Django - updating a user's profile removes session
I'm successfully updating the user's profile, but for some reason it is removing the session somehow. I'm using the same form used during the initial user creation - just filling in the fields via initial. Is it some built-in Django magic that is messing with my session? Here is what the request looks like: [09/May/2020 22:40:38] "POST /user/settings HTTP/1.1" 200 9564 [09/May/2020 22:40:41] "GET /users/12/ HTTP/1.1" 302 0 views.py # @login_required(login_url='/login/') def settings(request): user = request.user if request.method == 'POST': POST = request.POST.copy() POST['user_type'] = user.user_type form = CreateUserForm(POST, instance=request.user) if form.is_valid(): user = form.save(commit=False) user.entity_type = request.user.entity_type print("Saving user.") user.save() user.session = request.session # return redirect('dashboard', pk=request.user.id) else: print(form.errors) else: email = user.email zipcode = user.zipcode user_type = user.user_type if user.entity_type == 'individual': first_name = user.first_name last_name = user.last_name form = CreateUserForm(instance=request.user, initial={ 'first_name': first_name, 'last_name': last_name, 'email': email, 'zipcode': zipcode, 'user_type': user_type }) elif user.entity_type == 'business': business_name = user.business_name print(user_type) form = CreateUserForm(instance=request.user, initial={ 'business_name': business_name, 'email': email, 'zipcode': zipcode, 'user_type': user_type }) context = {'form':form} return render(request, 'user/settings.html', context) forms.py class CreateUserForm(UserCreationForm): first_name = forms.CharField(max_length=100, help_text='First Name', required=False) last_name = forms.CharField(max_length=100, help_text='Last Name', required=False) business_name = forms.CharField(max_length=100, help_text='Business Name', required=False) email = forms.EmailField(max_length=150, help_text='Email') zipcode = … -
How can i add multiple models and custom fields to a json response in Django Rest Framework
i'm new into Python/Django programming and i got stuck with something in a personal project that i'm doing. My issue is that i want to return a custom response based on different models of my application, some of the values will come from custom queries and others are part of the models itself. So, i have the following models in my app(some fields were deleted to not make the post too long): class Parking(models.Model): google_id = models.CharField(max_length=100) short_name = models.CharField(max_length=100) long_name = models.CharField(max_length=300) price = models.DecimalField(max_digits=4, decimal_places=2, null=True, blank=True) class ParkingLot(models.Model): parking = models.ForeignKey(Parking, on_delete=models.CASCADE, null=False, related_name='parkinglots') size = models.ForeignKey(Size, on_delete=models.DO_NOTHING, null=False, related_name='size') width = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) height = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) class ParkingAvailability(models.Model): parkinglot = models.ForeignKey(ParkingLot, on_delete=models.CASCADE, null=False, related_name='availability') available = models.BooleanField(null=False, blank=False) from_hour = models.TimeField(auto_now=False, auto_now_add=False, default='09:00:00') to_hour = models.TimeField(auto_now=False, auto_now_add=False, default='21:00:00') These models are an exact representation of my database tables. All good. My problem is that now i want to make a custom json response, this needs to run queries over these tables but not show the entire objects and in some cases, custom fields based on filter or operations that i need to run over the tables (for example, numbers of parkinglots … -
Pass args and kwargs into reverse Django
I think this is a very easy question, so bare with me. I have a link that is set up as follows: page/<key> where key is a randomly generated key, that is setup here: reverse('page', args=(key,)) However, I want to also pass data into the page/<key> endpoint. However, if I add another variable into args here: reverse('page', args=(key, more_data)) then it gets messed up as it tries to open a url at: page/<key>/<more_data> Furthermore, django doesn't allow args and kwargs in one reverse call. How would I pass data in then? Thanks! -
Django custom URL missing 1 required positional argument
I have the following view (empty for test) : from .forms import Form_Step_1 def register(request, step): print(step) In my urls.py I have : urlpatterns = [ path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('register', register, name='register'), path('register/', register, name='register'), path('register?step=<int:step>/', register, name='register'), ] The register and register/ works well. But if I go to register?step=1 I have the following error : register() missing 1 required positional argument: 'step' Thanks for your help -
How to add an additional class to a table from context in Django
I have 2 functions one for MarketingMessage and another for Slider. I have already a function for MarketingMessage and I want to add the Slider because the below function is not working correctly I want to combine them together as they are from the same model This is the original function that I want to add to it def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) try: context['marketing_message'] = MarketingMessage.objects.filter( active=True).latest('timestamp') except MarketingMessage.DoesNotExist: context['marketing_message'] = None return context this is the function that I want to get rid of and include it to the above one def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) try: context['sliders'] = Sliders.objects.filter( active=True).latest('timestamp') except Sliders.DoesNotExist: context['sliders'] = None return context This is the model class MarketingMessage(models.Model): title = models.CharField(max_length=60) message = models.TextField( max_length=120) active = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title class Slider(models.Model): title = models.CharField(max_length=60) image = models.ImageField(blank=False, upload_to='Marketing') header_text = models.CharField(max_length=120, null=True, blank=True) middle_text = models.CharField(max_length=120, null=True, blank=True) footer_text = models.CharField(max_length=120, null=True, blank=True) button_text = models.CharField(max_length=120, null=True, blank=True) active = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title Thank you all -
502 Bad Gateway - Dockerized Django Gunicorn NGINX on AWS EBS
So I am trying to deploy over two days and I can't seem to to manage to get fix this error. I am getting a 502 bad gateway error. I am trying to deploy a two-container app to elastic beanstalk. The two containers are: Nginx reverse proxy container Django app with gunicorn I SSHed to my EC-2 instance and fetched the nginx logs 2020/05/09 21:48:25 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 84.119.15.244, server: , request: "GET / HTTP/1.1", upstream: "http://172.17.0.2:8000/", host: "http://xxx-xxx-xxx.us-east-1.elasticbeanstalk.com/" 84.119.15.244 - - [09/May/2020:21:48:25 +0000] "GET / HTTP/1.1" 502 560 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-" 2020/05/09 21:48:25 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 84.119.15.244, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://172.17.0.2:8000/favicon.ico", host: "http://xxx-xxx-xxx.us-east-1.elasticbeanstalk.com/", referrer: "http://xxx-xxx-xxx.us-east-1.elasticbeanstalk.com/" It seems like the upstream refused to connect. I also took the gunicorn logs and it looks like server started successfully [2020-05-09 21:48:07 +0000] [1] [INFO] Starting gunicorn 19.9.0 [2020-05-09 21:48:07 +0000] [1] [INFO] Listening at: http://127.0.0.1:8000 (1) [2020-05-09 21:48:07 +0000] [1] [INFO] Using worker: sync [2020-05-09 21:48:07 +0000] [9] [INFO] Booting worker with pid: 9 here is my nginx default.conf … -
jQuery: Saving a form with jQuery turns the form invalid
I'd like to save a form containing an image. Without jQuery the form saves as intended, however, adding below "js-product_image-create-form" function creates an invalid form, but, at the same time, json respond status is: <JsonResponse status_code=200, "application/json"> The form is invalid in the View (prints "invalid" below) and in "invalid" in jQuery. However, removing the class="js-product_image-create-form", visually I get json with a valid form = True as well as the function prints "valid" Why is the form valid in one case but invalid in the other case? Using Django View: def save_product_image_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True print("valid") product_image = ProductImage.objects.all() data['html_product_image_list'] = render_to_string('product_image/includes/partial_product_image_list.html', { 'product_image': product_image }) else: data['form_is_valid'] = False print("invalid") context = {'form': form} data['html_form'] = render_to_string( template_name, context, request=request) return JsonResponse(data) def product_image_create(request): if request.method == 'POST': form = ProductImageForm(request.POST, request.FILES) else: form = ProductImageForm() return save_product_image_form(request, form, 'product_image/includes/partial_product_image_create.html') $(function() { var saveForm = function() { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function(data) { if (data.form_is_valid) { alert("I am valid"); $("#product_image-table tbody").html(data.html_product_image_list); $("#modal-product_image").modal("hide"); } else { alert("I am invalid !"); $("#modal-product_image .modal-content").html(data.html_form); } } }); return false; }; …