Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change Products by Form in Django
I have two models about my products class Product(models.Model): product_model = models.CharField(max_length=255, default='', verbose_name="نام محصول") product_url = models.SlugField(max_length=200, default='', verbose_name="اسلاگ محصول" ) description = tinymce_models.HTMLField(verbose_name="توضیحات") size = models.ManyToManyField(Size , verbose_name="سایز", related_name="rel_size") ... class Size(models.Model): size = models.CharField(max_length=20) size_url = models.SlugField(max_length=200, default='', verbose_name="اسلاگ سایز") class Stock(models.Model): amount = models.PositiveIntegerField(verbose_name="موجودی انبار") product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="محصول") size = models.ForeignKey(Size, on_delete=models.CASCADE, verbose_name="سایز") product_price = models.FloatField(null=True, verbose_name="قیمت محصول") we have L M Xl XXL sizes and in views.py i have: def product_detail(request, product_url): if request.user.is_authenticated and request.user.is_staff or request.user.is_superuser: product = get_object_or_404(Product, product_url=product_url) stock = get_list_or_404(Stock, product=product) if request.method == "POST": amount = request.POST['amount'] price = request.POST['price'] stock.amount = amount stock.product_price = price stock.save() ctx = {'product':product, 'stock':stock} return render(request, 'staff/product_detail.html',ctx) else: return redirect('/staff') and my html : <div class="container-fluid"> {{product.product_model}} <br> <br> {% for sto in stock %} <form method="POST" class="register-form" id="register-form"> {% csrf_token %} <p>{{sto.size}}</p> <input type="text" value="{{ sto.amount | default_if_none:"" }}" name="amount" id="lo" placeholder="موجودی"/> <input type="text" value="{{ sto.product_price | default_if_none:"" }}" name="price" id="lo" placeholder="قیمت (تومان)"/> <br> <input type="submit" name="signup" id="signup" class="form-submit" value="ذخیره"/> </form> {% endfor %} <br> </div> My problem is that each size has own amount and price from a product, like each product has 1 or more size it … -
how to select manytomany objects only for the current instance
i want the manytomany select display the values related for a current instance like this: in this image he display interet sql & nage but sql not for a current instance Hanin sql interet is for person Ahmedmahmoud nage is for acurrent instance Hanin Models.py class Formation(models.Model): Nom = models.CharField(max_length=100) Niveau = models.CharField(max_length=200) institution = models.CharField(max_length=100) contexte = models.CharField(max_length=100) Description = models.TextField() DateDebut = models.DateField(null=True) DateFin = models.DateField(null=True) id_candidat = models.ForeignKey(Candidat, null= True, on_delete=models.SET_NULL,default=Candidat.id) def __str__(self): return self.Nom class CV(models.Model): interet = models.ManyToManyField(Interet) candidat = models.ManyToManyField(Candidat) Langues = models.ManyToManyField(Langue) Certifications= models.ManyToManyField(Certification) Experiences= models.ManyToManyField(Experience) Competence = models.ManyToManyField(Competence) Refferances= models.ManyToManyField(Réfférence) Declaration = models.ManyToManyField(DeclarationPerson) Formations = models.ManyToManyField(Formation) views.py def createcv(request): if request.method=='POST': cv_form=CVForm(request.POST) if cv_form.is_valid(): cv_form = cv_form.save(commit=False) cv_form.id_candidat= Candidat.objects.get(id=request.user.candidat.id) cv_form.save() return redirect('/resume') context={'cv_form':cv_form} return render('/') forms.py class CVForm(ModelForm) : class Meta: model=CV fields="__all__" exclude = ["candidat"] -
How to extract data from Django api rest framework POST method
I'm trying to build an API that execute a script with some variables, those variables are in the POST msg, like {'command': 'start', 'name': 'var'}.. The thing is that I can't find the function the extraction those exact values and not all of the data. after a few days I tried with flask but that idea is the same. from flask import Flask, request from flask_restful import Api, Resource import os script = 'python /home/USER/somepath/client.py start ' app = Flask(__name__) api = Api(app) class Netflix(Resource): def get(self): return "Success", 201 def post(self): name = request.data os.system(script+name) print(name) return "Success", 201 api.add_resource(Netflix, "/netflix") if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=8000) -
Login and Authentication in Django
I am trying to create a login function and login authentication in the views.py inside def login(request) for particular username and password from my model class "Signup" . Could someone please help me in my existing code how to do so or share any resources to perform the following operation. P.S. I am new to Django and getting overwhelmed by the information present in the internet due which couldn't get the solution to my problem. I am adding my code snippets for models.py , views.py , urls.py and login.html . "models.py" from django.db import models # Create your models here. class SignUp(models.Model): username= models.CharField(max_length=100) email=models.EmailField(max_length=254) password=models.CharField(max_length=20) address=models.CharField(max_length=250) "views.py" from django.shortcuts import render,redirect from django.http import HttpResponse from .models import SignUp from django.contrib.auth import login,authenticate,logout # Create your views here. def login(request): if request.method == 'POST': username= request.POST['username'] password= request.POST['password'] user = authenticate(username=username,password=password) html2 = "<html><body>No such user</body></html>" if user is not None: login(request,user) return redirect('') else: return HttpResponse(html2) else: return render(request,'login.html') def signup(request): if request.method == 'POST': username= request.POST['username'] email= request.POST['email'] password1= request.POST['password1'] password2= request.POST['password2'] address= request.POST['address'] html = "<html><body>Confirm Password and Password should be same </body></html>" html1= "<html><body>User Already present </body></html>" if password1 != password2: return HttpResponse(html) else: for … -
django admin filter_list by manytomany filed
models.py class Author(models.Model): nickname = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=255) authors = models.ManyToManyField(Author) admin.py @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_filter = (???,) How to filter the books of a particular author through the admin panel. -
Return redirect wont pass parameters
i cant find solution to this simple problem. urls.py path('board/<id>/', board, name="board"), views.py def index(request): if request.method == 'GET': usuario = request.user last_board = Usuario.objects.filter(user=usuario.id).values_list("last_board", flat=True) if usuario.is_authenticated: return redirect('/board/', last_board ) return render(request, "index.html") i tried with get, post, without a request.method but its just simple dont pass the arguments, i literally have the same line on another method and works perfectly. Error url returned: 127.0.0.1/8000/board/ TypeError at /board/ tablero() missing 1 required positional argument: 'id' -
ngrok: Access subdirectory URLs in Django
I am using ngrok to test my website. I am able to launch the home page, but how do I launch directories other than homepage? such as 127.0.0.1:8000\apartment_listing? I get Error 500: Internal Server Error. Any solution? -
Django admin : TypeError: __str__ returned non-string (type NoneType)
Please help noob.. Although there is no seed(any instance) in my tables or DB, the error occur when I try to ADD instance in http://localhost:8000/admin/posts/post/add/ If there are seeds, I can see on the admin page, but try to edit or add, then error occur. Can't find where is the problem. (I also tried return str(~~variable) things...) error is same as below: TypeError at /admin/posts/post/add/ str returned non-string (type NoneType) class Post(core_models.TimeStampedModel): pno = models.IntegerField(null=True) # 게시물_번호 password = models.CharField(max_length=100, null=True) # 비밀번호 union = models.ForeignKey( union_models.Union, on_delete=models.CASCADE, null=True ) # 조합 # null=True 안하면 에러남 title = models.CharField(max_length=50, null=True) # 제목 content = models.CharField(max_length=10, null=True) # 내용 writer = models.ForeignKey( user_models.User, related_name="writer", on_delete=models.PROTECT, null=True ) # 작성자 receiver = models.ForeignKey( user_models.User, related_name="receiver", on_delete=models.PROTECT, null=True ) # 받는사람 hits = models.IntegerField(null=True) # 조회수 is_notice = models.BooleanField(null=True, default=False) # 공지사항_구분 category = models.CharField(null=True, max_length=50) # 공지사항_카테고리 def __str__(self): if self.title == None: return "ERROR- IS NULL" return self.title -
Browse local csv file and upload to Django database model extended from Django default User model
I'm trying to create a Django project with a 'Browse' button on a HTML page that allows you to search your local drive for a CSV file which you can then import according to the Django model that is extended from the default Django User model. I have seen examples on how to import the CSV file directly in the code itself but can't find anything on how to allow users to visit a HTML site and have a button they can click to browse a local CSV file to import to the Django database. For example, I have a model that is extended from Django default User model like so: class extendUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) extendUserID = models.AutoField(primary_key = True) userType = models.CharField(max_length = 20, choices = userType, default = 'customer') address = models.CharField(max_length=60, null = True) dob = models.DateField() contactNum = models.CharField(max_length=15, null = True) accountDateCreated = models.DateTimeField(auto_now_add=True, null = True) def __str__(self): return self.user.first_name And I have a CSV file that contain the following in the format of: First name, last name, email, address, dob, contact number John, Doe, johnemail@email.com, 123 Earth Avenue, 01 Jan 1981, 123321 How can I allow users to browse their local … -
django-modeltranslation: how to keep the default field empty?
I've the following table: # parts - name (default) - name_en (translated) - name_es (translated) When filling name_en and name_es via the django admin panel, name is also set, even if I keep it empty. The value is taken from either name_es or name_en, depending on my current locale. As I've to support more than 2 languages and editors from several countries, the default field name would become a mess IMO. Question Is there a way to keep it empty or even avoid name_en and use name instead? Code extraction # settings.py LANGUAGES = ( ('en', gettext('English')), ('es', gettext('Spanish')), ) # app/models.py class Part(models.Model): name = models.CharField(max_length=100, blank=True, default='') # app/serializer.py class PartSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Part fields = ['name'] # app/views.py class PartViewSet(viewsets.ModelViewSet): queryset = Part.objects.all() serializer_class = PartSerializer Note: I'm using the django-restframework and the docs of django-modeltranslation mention: When creating a new viewset , make sure to override get_queryset method, using queryset as a property won’t work because it is being evaluated once, before any language was set. Thanks in advance! -
ValueError at / The 'pic' attribute has no file associated with it
I have a simple model with pic field having null and blank class PostForNewsFeed(models.Model): title = models.CharField(max_length=100, blank=True) description = models.CharField(max_length=255, blank=True) slug = models.SlugField(unique=True, max_length=100, blank=True) pic = models.ImageField(upload_to='path/to/img', null=True, blank=True, default='') {% if post.pic.url %} <a href="{% url 'post-detail' post.id %}" ><img class="card-img-top" src="{{ post.pic.url }}" alt="" /></a> {% endif %} When I submit without a pic I am getting the pic attribute not associated with a file. My code seems fine in the template. -
When I set DEBUG=False Django gives me 400 bad request am using [docker, nginx, django, gunicorn]
I am trying to define a production env for Django using docker and Nginx and Gunicorn and It works fine when debug=True If I make debug=False the Issue start here gives me Bad Request (400) my Nginx file like this: upstream API { server backend-stack:8000; } server { listen 80; server_name localhost; location / { proxy_set_header Host $host; proxy_pass http://api; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; } location /static/ { alias /backend/static/; } location /media/ { alias /backend/media/; } } my allowed_hosts In settings.py if env.get("ALLOWED_HOSTS"): ALLOWED_HOSTS = env.get("ALLOWED_HOSTS", default=['127.0.0.1']) my gunicorn execute command from entrypoint.sh file: gunicorn core.wsgi:application --bind 0.0.0.0:8000 also here Is my nginx container In docker-compose: nginx: container_name: nginx-stack build: ./nginx restart: always volumes: - ./nginx/config:/etc/nginx/conf.d - ./nginx/log:/var/log/nginx - static_volume:/app_backend/static - media_volume:/app_backend/media ports: - 80:80 - 443:443 depends_on: - backend networks: - app-network finaly access log file for nginx : 192.168.144.1 - - [12/Jun/2021:15:18:02 +0000] "GET / HTTP/1.1" 400 154 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36" "-" -
How to include a django html template in a div tag?
I would like to include a django html template in another template inside a div tag, like so: {% block content %} <div id='content'> {% include 'template_to_include.html' %} </div> {% endblock %} Without the div I got the expected result but when I put the include tag inside the div, I got a blank line. Any help is apreciated please -
Django redirecting me to the same URL in every request
Whatever I type after http://127.0.0.1:8000, django redirects me to http://127.0.0.1:8000/catalog/catalog/ Catalog is app name. Project name is mysite. I am on Windows 10, and the browser is Google Chrome. mysite/urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('catalog.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) catalog/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home), ] catalog/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse('Hey, Youre at the catalog homepage') -
Download image from django backend using Authorization Token [DJANGO , REACT-NATIVE]
I'm developing a react-native application and I want to download user's profile picuture from django-backend. Now I've tried using base64 encoding and it works, but is it possible to make a GET request using Authorization Token (from react) and retrive the corresponding image from django? I mean something like: "www.site.com/media/user1.png" but using Authorization Token to prevent everyone to access to the image. Thanks -
django-orm case-insensitive group by
I'm trying to annotate my data with their count in a case-insensitive manner. I found this similar question: django-orm case-insensitive order by and tried this: from django.db.models.functions import Lower Posts.objects.filter(published=True).values('author').annotate(Lower('author')) However it returns: AttributeError: 'Lower' object has no attribute 'split' I also tried this one: Posts.objects.filter(published=True).values('author').annotate(c=Count(Lower('author'))) It has no effect and the result is case sensitive. -
Flask - GraphQL - Windows- cannot import name 'OperationType' from 'graphql.language
Im trying to use GraphQL in my Flask app as follwos : from flask_graphql import GraphQLView from Schema.schema import schema .... def create_app(): app.add_url_rule( '/graphql', view_func=GraphQLView.as_view( 'graphql', schema=schema, graphiql=True # for having the GraphiQL interface ) ) but it gives me the follwing error : C:\Users\GodDammit\Downloads\Fake_News_Detection-master\Fake_News_Detection-master>py flaskGraphql.py Traceback (most recent call last): File "C:\Users\GodDammit\Downloads\Fake_News_Detection-master\Fake_News_Detection-master\Fake_News_Det.py", line 9, in <module> from flask_graphql import GraphQLView File "C:\Users\GodDammit\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_graphql\__init__.py", line 1, in <module> from .blueprint import GraphQL File "C:\Users\GodDammit\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_graphql\blueprint.py", line 5, in <module> from .graphqlview import GraphQLView File "C:\Users\GodDammit\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_graphql\graphqlview.py", line 7, in <module> from graphql_server import (HttpQueryError, default_format_error, File "C:\Users\GodDammit\AppData\Local\Programs\Python\Python39\lib\site-packages\graphql_server\__init__.py", line 17, in <module> from graphql.language import OperationType, parse ImportError: cannot import name 'OperationType' from 'graphql.language' (C:\Users\GodDammit\AppData\Local\Programs\Python\Python39\lib\site-packages\graphql\language\__init__.py) I v search in the web but it seems I'm first one ever encounters this problem. -
How do i get Django form fields to work in my custom html create post model form
Here is my views for create post..i would really appreciate a solution on how to fit the form field in mine Html code. def create_post(request): context = {} user = request.user if request.method == "POST": form = NewPostForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user_name = user data.save() messages.success(request, f'Posted Successfully') return redirect('feed') else: form = NewPostForm() context['NewPostForm'] = form return render(request, 'feed/feed.html', context) Here is my forms model, how do I access the form fields in my html code below without having to use the form variables like this {{form.as_p}}? class NewPostForm(forms.ModelForm): class Meta: model = Post fields = ('description', 'pic', 'tags',) class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = ('comment',) Here is my HTML code for the post. -
By using multiple checkboxes in html, how should I fetch the data and store in the database in django?
I am creating multiple checkboxes in html and now I want to fetch this data and store it in the database. I'm using MySQL as the database and I'm using the django-multiselectfield(django-multiselectfield) library in django for creating checkboxes in django. models.py file 👇 from multiselectfield import MultiSelectField from django.db import models class Teacher(models.Model): id=models.AutoField(primary_key=True) SCHOOL_BOARD_CHOICES = [ ('State', 'State'), ('CBSE', 'CBSE'), ('ICSE', 'ICSE'), ] school_board = MultiSelectField(choices=SCHOOL_BOARD_CHOICES, blank=True, null=True) This is how it is looking in django's admin dashboard html file 👇 <form role="form" action="{% url 'register_save' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" name="username" id="username" placeholder="Enter username"> </div> <div class="form-group"> <label for="fname">First Name</label> <input type="text" class="form-control" name="fname" id="fname" placeholder="Enter your first name"> </div> <div class="form-group"> <label for="lname">Last Name</label> <input type="text" class="form-control" name="lname" id="lname" placeholder="Enter your last name"> </div> <div class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" name="email" id="email" aria-describedby="emailHelp" placeholder="Enter email"> </div> <div class="form-group"> <label for="pass">Password</label> <input type="password" class="form-control" name="pass" id="pass" placeholder="Password"> </div> <div class="form-group"> <label for="cpass">Confirm Password</label> <input type="password" class="form-control" name="cpass" id="cpass" placeholder="Confirm Password"> </div> <div class="form-group"> <label for="category">Choose Category</label> <select class="form-control" id="category" name="category"> <option>School</option> <option>College</option> <option>Engineering</option> <option>Professional</option> </select> </div> <p>Class(es) you teach</p> <div style="margin-top: 0.5px;" class="form-group form-check"> <input type="checkbox" class="form-check-input" name="school_class" … -
the correct way to retrieve payload using JWT id token on cognito with Django
So I am working on integrating AWS Cognito with the backend of company's project.To my understanding, id_token has user's email with it. What is the correct way to retrieve the payload from an id_token? This is what I have right now: JWT_AUTH = { 'JWT_PAYLOAD_GET_USERNAME_HANDLER':'api.cognito.jwt.get_username_from_payload_handler', 'JWT_DECODE_HANDLER':'api.cognito.jwt.cognito_jwt_decode_handler', 'JWT_PUBLIC_KEY': rsa_keys, 'JWT_ALGORITHM': 'RS256', 'JWT_AUDIENCE': COGNITO_AUDIENCE, 'JWT_ISSUER': COGNITO_POOL_URL, 'JWT_AUTH_HEADER_PREFIX': 'Bearer', } the cognito_jwt_decode_handler function looks like this: def cognito_jwt_decode_handler(token): print('Inside cognito_jwt_decode_handler!') options = {'verify_exp': api_settings.JWT_VERIFY_EXPIRATION} unverified_header = jwt.get_unverified_header(token) if 'kid' not in unverified_header: raise DecodeError('Incorrect authentication credentials.') kid = unverified_header['kid'] try: public_key = RSAAlgorithm.from_jwk(api_settings.JWT_PUBLIC_KEY[kid]) except KeyError: raise DecodeError('Can\'t find proper public key in jwks') else: print('here!') return jwt.decode( token, public_key, api_settings.JWT_VERIFY, options=options, leeway=api_settings.JWT_LEEWAY, audience=api_settings.JWT_AUDIENCE, issuer=api_settings.JWT_ISSUER, algorithms=[api_settings.JWT_ALGORITHM] ) so this works fine with access_token in the authorization. while i changed it to id_token, that cognito_jwt_decode_handler function is even not getting invoked. What could be the issue here? -
(fields.E304) Reverse accessor for 'groups' & 'user_permissions' clashes with reverse accessor
I'm working on a django project, I have two user login systems, one is for "staff" and the other is for "clients" members/models.py: (clients) from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.db.models import CheckConstraint, Q import datetime from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import Group from phonenumber_field.modelfields import PhoneNumberField from .managers import MembersManager class members(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() contact = PhoneNumberField(default='+92') avatar = models.ImageField(upload_to='images') age = models.PositiveSmallIntegerField() gender = models.CharField(max_length=2, choices=( ('F', 'Female'), ('M', 'Male') )) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MembersManager() class Meta: verbose_name_plural = 'Members/Clients' constraints = [ CheckConstraint(check=Q(age__gte=18), name='age_gte_18'), ] def __str__(self) -> str: return super().__str__(f'CL{self.id}') class membersGroup(Group): class Meta: proxy = True app_label = 'auth' verbose_name = _('Members Group') staff/models.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import Group from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): INTERNAL_STAFF = 1 MARKETING_STAFF = 2 SUPERVISOR = 3 ROLES_CHOICES = ( (INTERNAL_STAFF, 'Internal Staff'), (MARKETING_STAFF, 'Marketing Staff'), (SUPERVISOR, 'Supervisor'), ) first_name = models.CharField(max_length=20, default='') last_name = models.CharField(max_length=20, default='') email = models.EmailField(_('email address'), unique=True) … -
How can store data of page for certain time in djnago?
Add path('/int:id/',cache_page(60)(views.add_food), name='addfood') def add_food(request, id): pi = FoodIngredient.objects.get(pk=id) context = { 'pi':pi, } return render(request, 'calorie/home.html', context) Everytime i click add button above..a item is shown based on its 'id'. If i pass another id through the add button..another item is shown..what i want is to display individaul item based on id keeping the previous one the page. is it possible with django?? like click add (id 1) display: item1 and then click add(id 2) display: item 1 item 2 -
Django Rest Framework - AttriubuteError: 'AutoSchema' object has no attribute 'get_link'
The following code is throwing me error when i run (http://127.0.0.1:8000/docs/): from django.contrib import admin from django.urls import path, include from rest_framework.schemas import get_schema_view from rest_framework.documentation import include_docs_urls schema_view = get_schema_view(title='Blog API') urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('posts.urls')), path('api-auth/', include('rest_framework.urls')), # Peculiar to rest_framework path('api/v1/rest-auth/', include('rest_auth.urls')), # Peculiar to django-rest-auth package path('api/v1/rest-auth/registration/', include('rest_auth.registration.urls')), # Peculiar to rest_auth app path('docs/', include_docs_urls(title='Blog API')), path('schema/', schema_view), ] Here is the error: AttributeError: 'AutoSchema' object has no attribute 'get_link' Please Help suggest a potential solution -
Heroku Logs: No Module Named Numpy
I'm using Django to deploy a website. There is a call to import numpy in my apps.txt file for an ML function. I have numpy==1.19.5 in my requirements.txt file and I installed numpy in the terminal using pipenv install numpy The website works when I deploy it locally, but when I deploy it to Heroku and run heroku open, I get an application error. Here are the logs: 2021-06-12T14:15:02.802169+00:00 app[web.1]: worker.init_process() 2021-06-12T14:15:02.802170+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process 2021-06-12T14:15:02.802170+00:00 app[web.1]: self.load_wsgi() 2021-06-12T14:15:02.802170+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2021-06-12T14:15:02.802171+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-06-12T14:15:02.802172+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-06-12T14:15:02.802172+00:00 app[web.1]: self.callable = self.load() 2021-06-12T14:15:02.802172+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2021-06-12T14:15:02.802173+00:00 app[web.1]: return self.load_wsgiapp() 2021-06-12T14:15:02.802173+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2021-06-12T14:15:02.802173+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-06-12T14:15:02.802174+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app 2021-06-12T14:15:02.802174+00:00 app[web.1]: __import__(module) 2021-06-12T14:15:02.802175+00:00 app[web.1]: File "/app/wandering_mind/wsgi.py", line 16, in <module> 2021-06-12T14:15:02.802175+00:00 app[web.1]: application = get_wsgi_application() 2021-06-12T14:15:02.802175+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-06-12T14:15:02.802176+00:00 app[web.1]: django.setup(set_prefix=False) 2021-06-12T14:15:02.802176+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/__init__.py", line 24, in setup 2021-06-12T14:15:02.802176+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2021-06-12T14:15:02.802176+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 89, in populate 2021-06-12T14:15:02.802177+00:00 app[web.1]: app_config = AppConfig.create(entry) 2021-06-12T14:15:02.802177+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/config.py", line 116, in create 2021-06-12T14:15:02.802177+00:00 … -
Form is not saving in ajax
I am building a BlogApp and I am trying to submit a form without refreshing the page. I am editing the gender of the user. When i click on submit button then it is keep showing me GET /edit_now?csrfmiddlewaretoken=JnegVCQ818H83U29W8zcx8D9QKIK6GxgvLWf5BE5Ab3BcCpxdeEXUXsMNCtHVrU3&gender=derfef models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') gender = models.CharField(max_length=20) views.py def edit_now(request): form = EditGender() context = {'form':form} return render(request, 'edit_gender.html',context) def postFriend(request): if request.is_ajax and request.method == "POST": form = EditGender(request.POST) if form.is_valid(): instance = form.save() instance.user = request.user.profile instance.save() ser_instance = serializers.serialize('json', [ instance, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error": ""}, status=400) edit_gender.html <form id="friend-form"> <div class="row"> {% csrf_token %} {% for field in form %} <div class="form-group col-4"> <label class="col-12">{{ field.label }}</label> {{ field }} </div> {% endfor %} <div class = "col text-center"> <input type="submit" class="btn btn-primary" value="Edit" /> </div> </div> <form> <script> $(document).ready(function () { /* On submiting the form, send the POST ajax request to server and after successfull submission display the object. */ $("#friend-form").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData = $(this).serialize(); // make POST ajax call $.ajax({ …