Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
query URL (query string) problem about "paginator" and "filter" in Django
my views.py: def subcategory(request, category_url): category = get_object_or_404(Category, category_url=category_url) subcategories = Subcategory.objects.filter(category=category) products_list = Product.objects.filter(product_category=category) subcatid = request.GET.getlist('subcategory') print(subcatid) if subcatid: ids = [int(id) for id in subcatid] subcategories1 = Subcategory.objects.filter(category=category, id__in=ids) products_list = Product.objects.filter(product_category=category, product_subcategory__in=subcategories1) else: subcategories1 = None products_list = Product.objects.filter(product_category=category) page = request.GET.get('page', 1) paginator = Paginator(products_list, 2) try: pass products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if request.user.is_authenticated: wishlist = get_object_or_404(Wishlist, user=request.user.profile) else: wishlist = None ctx = {'products':products, 'products_list':products_list, 'wishlist':wishlist, 'subcategories':subcategories, 'category':category, 'subcategories1':subcategories1} return render(request, 'products/subcategory.html', ctx) my paginator html : <nav aria-label="Page navigation"> <ul class="pagination justify-content-center"> {% if products.number|add:'-4' > 1 %} <li class="page-item"> <a class="page-link" href="?page={{ products.number|add:'-5' }}" aria-label="Previous" tabindex="-1" aria-disabled="true"> <span aria-hidden="true"></span><< </a> </li> {% endif %} {% if products.has_previous %} <li class="page-item "> <a class="page-link page-link-prev" href="?page={{ products.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="Previous" tabindex="-1" aria-disabled="true"> <span aria-hidden="true"><i class="icon-long-arrow-right"></i></span>قبلی </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link page-link-prev" href="" aria-label="Previous" tabindex="-1" aria-disabled="true"> <span aria-hidden="true"><i class="icon-long-arrow-right"></i></span>قبلی </a> </li> {% endif %} {% for i in products.paginator.page_range %} {% if products.number == i %} <li class="page-item active" aria-current="page"><a class="page-link" href="">{{ … -
how to effectively use UUID model field with django
If someone had to build a similar web application like Instagram using Django and expect a large user base as the start up grow, i am wondering if indexing the UUID model field while using postgres as a database would be a good idea after having modified the initial User model provided by django. class User(AbstractUser): id = models.UUIDField(primary_key=True, index=True, default=uuid.uuid4, editable=False) settings.py AUTH_USER_MODEL = "users.User" I have mentioned Instagram as an example to consider Read and Write of the database field in the application. I look forward to hear from anyone familiar with database and django good practices. Thank you -
Load a Django Form into Template using jQuery and stay on same page after submitting?
I am using Django function based views with a single template which contains multiple tabs. Depending on which tab is selected I hide/show certain elements on the page by catching .click() event using jQuery. I populate the visible elements using Ajax requests to certain view functions. I added a new tab to submit data via a form. Currently I have an additional template containing the form. When the tab is clicked, I load the template into an element using jQuery.load(upload.html). The form populates and posts to a Django view through a modelForm. It works alright however I can't seem to figure out how to stay on the same form tab after posting. Any redirect from Django causes the main template to reload to the default starting tab. Also, if the user navigates to main_template/upload.html the form is loaded outside of the main template page. I would like to avoid this. Am I going about this wrong ? main_template.html <div id="myForm"></div> $("#tabButton").click(function(){ $("#myForm").load("upload.html"); }); upload.html <form method="post" enctype="multipart/form-data" action="{% url 'core:upload' %}"> {% csrf_token %} {% bootstrap_form form layout='horizontal' %} {% bootstrap_button "Upload" button_type="submit" %} </form> urls.py urlpatterns = [ url('upload', views.upload, name='upload'), ] views.py def upload(request): if request.method == 'POST': … -
How can I avoid duplicate SQL queries with Django model forms?
I have the following models: from django.db import models class Author(models.Model): name = models.CharField(max_length=30) class Article(models.Models): author = models.ForeignKey(Author, on_delete=models.CASCADE) text = models.TextField() and a generic CreateView from django.views.generic.edit import CreateView urlpatterns += [ path("", CreateView.as_view(model=models.Article, fields="__all__")) ] with the following template (article_form.html) <form action="post"> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Submit"> </form> I am using Django Debug Toolbar to list the performed SQL queries for each web request. My question is: Why is the following SQL query for the author list performed twice for each request? And how can I avoid the duplicate query? SELECT "myapp_author"."id", "myapp_author"."name" FROM "myapp_author" Moreover, the debug toolbar says that the first query took only 0.5 ms, whereas the second took 42 ms! Almost 100x longer. How can this be? I am using Django 3.2 with an SQLite database. Thank you! -
How to display N number of Movies the staffs has and the N number of Staffs the Movies has in Django Rest-framework api
I'm Creating a site where I Have models.py like below class Staff(models.Model): staff_name = models.CharField("Staff Name", max_length=25) staff_dob = models.DateField("Staff Date of Birth", help_text="Staff Born Date") staff_gender = models.IntegerField(choices=GENDER, help_text="Staff's Gender") staff_about = models.TextField("About the Staff") staff_pic = models.ImageField(upload_to="Anime/Staff/images/") class Movies(models.Model): author = models.CharField(help_text="Author name of the movie", max_length=50) country_of_origin = models.CharField("Country Of Origin", max_length=20) start_date = models.DateField("Start Date") end_date = models.DateField("End date") status = models.IntegerField(choices=RELEASE_STATUS, help_text="Current status of the movie") staffs = models.ForeignKey(Staff, on_delete=CASCADE) I want to display N number of Movies the Staffs have and N number of Staffs the Movie have. I'm new to Django and rest_framework. Thanks in advance. -
django RelatedObjectDoesNotExist error while creating
models: class FullNameMixin(models.Model): name_id = models.BigAutoField(primary_key = True, unique=False, default=None, blank=True) first_name = models.CharField(max_length=255, default=None, null=True) last_name = models.CharField(max_length=255, default=None, null=True) class Meta: abstract = True class Meta: db_table = 'fullname' class User(FullNameMixin): id = models.BigAutoField(primary_key = True) username = models.CharField(max_length=255, unique=True) email = models.CharField(max_length=255, unique=True) token = models.CharField(max_length=255, unique=True, null=True, blank=True) password = models.CharField(max_length=255) role = models.IntegerField(default=1) verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.username class Meta: db_table = 'cga_user' class Profile(FullNameMixin): id = models.BigAutoField(primary_key = True) birthday = models.DateTimeField(null=True, blank=True) country = models.CharField(max_length=255, null=True, blank=True) state = models.CharField(max_length=255, null=True, blank=True) postcode = models.CharField(max_length=255, null=True, blank=True) phone = models.CharField(max_length=255, null=True, blank=True) profession_headline = models.CharField(max_length=255, null=True, blank=True) image = models.ImageField(upload_to=get_upload_path, null=True, blank=True) profile_banner = models.ImageField(upload_to=get_upload_path_banner, null=True, blank=True) cga_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, related_name="profile") gender = models.CharField( max_length=255, blank=True, default="", choices=USER_GENDER_CHOICES ) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) class Meta: db_table = 'profile' When i am creating Profile from django admin panel getting below error. e filename = self.upload_to(instance, filename) File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/api/model_utils/utils.py", line 7, in get_upload_path instance.user, File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__ raise self.RelatedObjectDoesNotExist( api.models.FullNameMixin.user.RelatedObjectDoesNotExist: Profile has no user. [24/Jul/2021 13:49:51] "POST /admin/api/profile/add/ HTTP/1.1" 500 199997 … -
therw is an error of circular import how to resolve the error?
Django.core.exceptions.ImproperlyConfigured: The included URLconf 'travelproject1.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
How to display questions based on subcategory using Django Rest Framework?
I want to display all questions based on subcategory. This is my code : models.py class Subcategory(models.Model): subcategory_id = models.BigAutoField(primary_key=True) subcategory = models.CharField(max_length=40) class Meta: managed = True db_table = 'subcategory' def __str__(self): return self.subcategory class Question(models.Model): question_id = models.BigAutoField(primary_key=True) subcategory = models.ForeignKey('Subcategory', models.DO_NOTHING, default=None) question = models.TextField() answer = models.CharField(max_length=255) class Meta: managed = True db_table = 'question' def __str__(self): return self.question serializers.py class SubcategorySerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('subcategory_id', 'subcategory') class QuestionSerializer(serializers.ModelSerializer): subcategory = serializers.StringRelatedField() class Meta: model = Question fields = ('question_id', 'subcategory', 'question', 'answer') view.py @api_view(['GET', 'POST', 'DELETE']) def question_list(request): # GET list of question, POST a new question, DELETE all question if request.method == 'GET': questions = Question.objects.all() question = request.GET.get('question', None) if question is not None: questions = questions.filter(question__icontains=question) questions_serializer = QuestionSerializer(questions, many=True) return JsonResponse(questions_serializer.data, safe=False) # 'safe=False' for objects serialization elif request.method == 'POST': question_data = JSONParser().parse(request) questions_serializer = QuestionSerializer(data=question_data) if questions_serializer.is_valid(): questions_serializer.save() return JsonResponse(questions_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(questions_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': count = Question.objects.all().delete() return JsonResponse({'message': '{} Questions were deleted successfully!'.format(count[0])}, status=status.HTTP_204_NO_CONTENT) /api/subcategory : [ { subcategory_id: 1, subcategory: "Mathematics" }, { subcategory_id: 2, subcategory: "History" } ] /api/questions : [ { question_id: 1, subcategory: 1, question: "10 … -
Django data in tables not showing up
My tables in my django don't show up , the titles for the table do but the data itself does not. can someone tell me what is wrong with my code dashboard.html {% extends 'accounts/main.html' %} {% block content %} {% include 'accounts/status.html' %} <div class="col-md-16"> <h5>LAST 5 ORDERS</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="">Create Order</a> <table class="table table-sm"> <tr> <th>Title</th> <th>Language</th> <th>Rating</th> <th>Type of Media</th> <th>Genre</th> <th>Review</th> <th>Notes</th> <th>Date</th> <th>Update</th> <th>Remove</th> </tr> {% for media in mediass %} <tr> <td>{{media.title}}</td> <td>{{media.language}}</td> <td>{{media.rating}}</td> <td>{{media.type_of_media}}</td> <td>{{media.genre}}</td> <td>{{media.review}}</td> <td>{{media.notes}}</td> <td>{{media.date}}</td> <td><a href="">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} </table> </div> </div> {% endblock %} models.py from django.db import models class Media(models.Model): CATEGORY = ( ('Movie', 'Movie'), ('Tv Show', 'Tv Show'), ('Drama', 'Drama'), ('Other', 'Other'), ) NUMBER = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) GROUP = ( ('Action', 'Action'), ('Anime', 'Anime'), ('Comedy', 'Comedy'), ('Crime', 'Crime'), ('Fantasy', 'Fantasy'), ('Horror', 'Horror'), ('Romance', 'Romance'), ('Other', 'Other'), ) title = models.CharField(max_length=200, null=True) language = models.CharField(max_length=200, null=True) rating = models.CharField(max_length=200, null=True, choices=NUMBER) type_of_media = models.CharField(max_length=200, null=True, choices=CATEGORY) genre = models.CharField(max_length=200, null=True, choices=GROUP) review = models.CharField(max_length=1000, null=True) notes = models.CharField(max_length=1000, null=True, blank=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return … -
Django not finding The Project module:
Everyone This is my first Django project for university, our project name is Hotel and every time I run: python manage.py runserver I get : ModuleNotFoundError: No module named 'Hotel' The traceback is: Traceback (most recent call last): File "C:\python3\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\python3\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\python3\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\python3\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\python3\lib\site-packages\django\conf\__init__.py", line 82, in getattr self._setup(name) File "C:\python3\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\python3\lib\site-packages\django\conf\__init__.py", line 170, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\python3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'Hotel' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\LENOVO\Desktop\Hotel\manage.py", line 22, in <module> main() File "C:\Users\LENOVO\Desktop\Hotel\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\python3\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() … -
How can I get a username from django User Model
I have the following where a comment is posted via a POST request urlpatterns = [ path("recipes/comments/", RecipeCommentView.as_view(), name="post_comment"), # POST ] Views.py @permission_classes([AllowAny]) class RecipeCommentView(generics.CreateAPIView): queryset = models.RecipeComment.objects.all() serializer_class = RecipeCommentSerializer Serializers.py class UserSerialiser(serializers.ModelSerializer): class Meta: model = models.User fields = ["username"] class RecipeCommentSerializer(serializers.ModelSerializer): published_by = UserSerialiser(read_only=True) class Meta: model = models.PublishedRecipeComment fields = ["recipe", "published_by", "content", "created_at"] ordering = ["position"] Models.py class RecipeComment(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.PROTECT, related_name="comments") published_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True) content = models.CharField(max_length=2500) created_at = models.DateTimeField(auto_now_add=True) I am using the User model from django.contrib.auth.models, how can I have the username of the currently logged in user attached to the published_by field? -
django uploading audio file returns null
models.py from django.db import models from datetime import datetime class Song(models.Model): title = models.CharField(max_length=64) audio_file = models.FileField() genre = models.CharField(max_length=64) created_at = models.DateTimeField(default=datetime.utcnow) serializers.py from rest_framework import serializers from . import models class SongSerializer(serializers.ModelSerializer): class Meta: model = models.Song fields = '__all__' class CreateSongSerializer(serializers.ModelSerializer): class Meta: model = models.Song fields = ['title', 'audio_file', 'genre'] views.py from . import models, serializers from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.decorators import parser_classes from rest_framework.parsers import FileUploadParser class SongView(APIView): def get(self, request, format=None): serializer = serializers.SongSerializer(models.Song.objects.all(), many=True) return Response(serializer.data) class PostSong(APIView): # here is the class <------------ serializer_class = serializers.CreateSongSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): title = serializer.data.get('title') genre = serializer.data.get('genre') filename = serializer.data.get('audio_file') song = models.Song(title=title, audio_file=filename, genre=genre) return Response(serializers.CreateSongSerializer(song).data, status=status.HTTP_200_OK) return Response({'Bad Request': 'Invalid Data'}, status=status.HTTP_400_BAD_REQUEST) urls.py from django.urls import path from . import views urlpatterns = [ path('songs/', views.SongView.as_view(), name='songs'), path('add-song/', views.PostSong.as_view(), name='add-song') ] Response { "title": "123", "audio_file": null, "genre": "123" } Everything works fine expect for when I try to upload a file it becomes null, I tried implementing the parser_class but that was getting rid of the form so I couldnt actually post data, how can … -
fetching data from models in django
i am bulding a ecommerce site i which i created two model name categoreis and subcategories in which subcategorie is related to categories with foreign key so a category name merch can have so many sub categories like shirt, tshirt, hoddies etc so what i want to achieve a navbar which which contain all the categories and all of them are dropdown when i click to that category i can see all the subcategories of it in dropdown menu here is my models.py class Categories(models.Model): name = models.CharField(max_length=100, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Subcategories(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name here is my views.py class home(View): def get(self, request,): category_list = Categories.objects.all() return render (request, 'home.html', {'category_list': category_list }) this is what i tried i know this not gonna work but it atleast all the categories in the nav bar here is what i want to achieve i hope you understan very well with this -
how to pass object from attr of button in django template to js
I want to pass a Python object to JavaScript via the HTML attribute. I used the following codes, but I did not get an answer. html code : <button style="margin: 7px" type="button" class="btn btn-primary user-button-edit" user-arg="{{ user|safe }}" data-toggle="modal" data-target="#exampleModalCenter"> js code : $(".user-button-edit").click(function() { var user = $(this).attr("user-arg"); console.log(user); console.log(user.name); $("#Userpermissions_6").prop("checked",true); }) the user.name --> undefined Due to the presence of ' in user object, it does not convert to Jason and gives an error. Does anyone have a solution? (I do not want to create an attribute for each data.) -
Django add dynamic fields with dynamic name attributes to front end and then insert it to Model
I have a Model which consists of almost 500+ fields. I want to take data through the front-end Form. But the issue is I can’t display all the 500 fields. what I want is I will add the fields which I need. like on day-1 I will add 3 fields. food = 230 , petrol = 500, rent = 700. on the second day, fields may vary. I can add 20 fields on the second day. on the third day data may be of different fields. like petrol = 200, cement= 5000 , steel = 100 etc etc and so on! Simple Solution is: I displayed all fields in HTML and submitted it to view and received in View function through Post Request! and then save() . But i want it to be dynamic! if request.method == 'POST': print("this is post") # print() food_expense=request.POST['food'] petrol_expense=request.POST['petrol'] easyload_expense=request.POST['easyload'] labour_expense = request.POST['labour'] equipments_expense = request.POST['equipments'] rent_expense = request.POST['rent'] cement_expense = request.POST['cement'] steel_expense = request.POST['steel'] other1_expense = request.POST['other1'] other2_expense = request.POST['other2'] other3_expense = request.POST['other3'] ..... .... fields upto 500+ # expense_paidby = request.POST['paid_by'] expense_paidby_id = request.POST['paid_by'] paidby= PaidBy.objects.get(id=expense_paidby_id) # expense_paidby = PaidBy.objects.get(name__icontains = request.POST['paid_by']) projectname_id= request.POST['pname'] project_in_which_expenses_made=ProjectName.objects.get(id=projectname_id) # project_in_which_expenses_made = request.POST['project_name'] date = request.POST['date'] … -
Why my Django Ajax form submit doesn't work?
I wrote a script that works perfectly when i put it bottom of html file but when copy code and paste it in dataforms.js file and of course put correct link in my html it doesn't work. HTML: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8" /> <title>Adminto - Responsive Bootstrap 4 Landing Page Template</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta content="A fully featured admin theme which can be used to build CRM, CMS, etc." name="description" /> <meta content="Coderthemes" name="author" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- App favicon --> <link rel="shortcut icon" href="images/favicon.ico"> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!--Material Icon --> <link href="{% static 'css/materialdesignicons.min.css' %}" rel="stylesheet"> <!--pe-7 Icon --> <link href="{% static 'css/pe-icon-7-stroke.css' %}" rel="stylesheet"> <!-- Magnific-popup --> <link href="{% static 'css/magnific-popup.css' %}" rel="stylesheet"> <!-- Custom sCss --> <link href="{% static 'css/style.css' %}" rel="stylesheet"> </head> <body> <!--Navbar Start--> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-bottom sticky sticky-dark"> <div class="container-fluid"> <!-- LOGO --> <a class="logo text-uppercase" href="index.html"> <img src="images/logo-dark.png" alt="" class="logo-dark" height="18" /> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <i class="mdi mdi-menu"></i> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto navbar-center" id="mySidenav"> <li class="nav-item active"> <a href="#home" class="nav-link">Introductions</a> </li> … -
Am using Python Django and I want to validate a NVarchar variable
I want to validate the 1st letter of the NVarchar and identify if it starts with 'P' or 'I' and then respectively switch between href tags. [This is the jobseqno from DB][1] [This is the actual condition that i want to modify][2] [1]: https://i.stack.imgur.com/PqtWc.png [2]: https://i.stack.imgur.com/UgnFW.jpg Thanks in Advance!! -
@property doesn't store value in DB
My model is like this: class Cart(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(null=False,blank=False) total = models.FloatField(null=False,blank=False) @property def total(self): return self.quantity * self.product.price The total appears in my admin dashboard but when I inspect the db from the shell I don't get the total value, I get the other values: <QuerySet [{'id': 42, 'product_id': 11, 'quantity': 2}]> Expected output: <QuerySet [{'id': 42, 'product_id': 11, 'quantity': 2, 'total': 29.00}]> -
django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded:
this is the Databases code in 'settings.py': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'proj_15db', 'USER': 'root', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '3306', } } After typing "manage.py makemigrations" successfully i then type "manage.py migrate" the following error occured : all the essential code has been done successfully but when i try to migrate this following happens Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\db\backends\mysql\base.py", line 234, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\MySQLdb\connections.py", line 179, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Django_Class\proj_15\manage.py", line 22, in <module> main() File "D:\Django_Class\proj_15\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, … -
how can i contact us page to django
Save all the contact us inputs on the database, and create a view to handle all the records. Tasks include Search and sort: based on the user entries like the services, or the email, phone number, names etc. Delete: records with irrelevant information to be removed/fake/false records to be removed Insert:: new records to be inserted when a new entry is submitted how to perform these tasks -
One Django view, multiple urls and apps
I have a small newsletter signup form at the footer of every page. The footer is part of base.html. I use Ajax to submit the form. Right now Ajax code calls a view defined in app1 and the corresponding URL is defined in the urls.py of the same app. Here's the AJAX code (this code is saved in a separate js file and included in the base.html): $('#newsletterForm').submit(function(e){ e.preventDefault() $('#loader').css("display", "block") $.ajax({ type : "POST", url : "/subscribe/", data : { subscriber_email : $('#e-mail').val(), csrfmiddlewaretoken : csrftoken, datatype : "json", }, success: function(){ $('#loader').css("display", "none"), $('#subscribed').css("display", "block"), $('#subscribed').delay(3000).fadeOut("slow") }, failure: function(){ alert('An error has occurred. Please try again.') }, }); }); The view (defined in app1): def subscribe(request): if request.is_ajax(): subscriber = Subscriber(email=request.POST.get('subscriber_email')) subscriber.save() return JsonResponse({}, status=200) else: return redirect('homepage:index') The URL (defined in app1): path('subscribe/', views.subscribe, name='subscribe'), Now, the problem is when I'm in app2, Django looks for /subscribe/ in that app which doesn't exist. So is there any way to solve this issue or I have to include /subscribe/ in urls.py and views.py of every app? -
django css has an issue with -ms-filter
enter image description here hey, so I have been making this Django app and when I run this, I can see errors with the ms-filter used with the message in the pic. please help me correct it. -
FOREIGN KEY constraint failed - can't remove from admin - Django
I want to remove data from admin but I am getting error Traceback (most recent call last): File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 1735, in changelist_view response = self.response_action(request, queryset=cl.get_queryset(request)) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 1402, in response_action response = func(self, request, queryset) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\actions.py", line 39, in delete_selected modeladmin.log_deletion(request, obj, obj_display) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 843, in log_deletion return LogEntry.objects.log_action( File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\models.py", line 29, in log_action return self.model.objects.create( File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 447, in create obj.save(force_insert=True, using=self.db) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 790, in save_base updated = self._save_table( File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 933, in _do_insert return manager._insert( … -
Add Product by Category in Django
I am trying to insert my product by category in django. I have two model Product and Category. I want to add Product in Product table.when I add product category comes in select box and select category. Category id in category value. which is insert in product table. Category is ForeignKey. But show this error: Cannot assign "<QuerySet [<Category: Mixeur>, <Category: Hachoir>, <Category: Batteur>]>": "Product.category" must be a "Category" instance. model.py: from django.db import models from django.forms import ModelForm class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): label = models.CharField(max_length=50) description = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() def __str__(self): return self.label view.py : def add_product(request): print(request.POST) p_category = Category.objects.all() if request.method == 'POST': label = request.POST['label'] description = request.POST['description'] quantity = request.POST['quantity'] category = request.POST['category'] data = Product( label=label, description=description, quantity=quantity, category=p_category ) data.save() return HttpResponseRedirect('/products/') else: form = AddProduct() return render(request, 'product/add_product.html', {'form': form, 'p_category':p_category}) add_product.html <form action="/add-product/" method="post"> {% csrf_token %} <label for="label">Label: </label> <input id="label" type="text" name="label" value=""> <label for="description">Description: </label> <input id="description" type="text" name="description" value=""> <label for="quantity">Quantity: </label> <input id="quantity" type="text" name="quantity" value=""> <select class="form-control mb-4" name="category"> <option selected disabled>Select Category</option> {% for cat in p_category %} <option value="{{cat.id}}">{{cat.name}}</option> … -
Query Optimization and profiling for celery tasks
Django-debug-toolbar and Django-silk are two famous tools for profiling HTTP requests. Is it possible to analyze a celery task or any other function inside the code? for instance, I have a celery task like this: def main_task(): while _condition: logic() sleep(_t) return True I need some information like duplicate and similar queries in logic() for every loop.