Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django returned response not updating in html
I send some of the dropdown values from my ajax to Django views, the Django views returning a response in JSON format. The value is a list of the list according to python so in javascript it's an array of arrays. What I want to do is to parse the data coming from the Django views and update a div content in the front end. This is what I tried so far: filter.html <form id="form1" method="POST"> {% csrf_token %} <div classs="container"> <div class="row"> <div class="col-lg-5"> <label for="intent">Intent</label> <div class="styled-select blue semi-square"> <select name="intent" id="intent-sel"> <option value="all">All</option> <option value="opinion">Opinion</option> <option value="complaint">Complaint</option> <option value="suggestion">Suggestion</option> <option value="satisfied">Satisfied</option> <option value="delivery">Delivery</option> <option value="customer_sensitivity_for_pricing">SensitivityForPricing</option> </select> </div> </div> <div class="col-lg-5"> <label for="product-type">Product Type</label> <div class="styled-select blue semi-square"> <select name="product_type" id="product-sel"> <option value="all">All</option> <option value="condom">Condom</option> <option value="lube">Lubricant</option> </select> </div> </div> <div class="col-lg-5"> <label for="rating">Rating</label> <div class="styled-select blue semi-square"> <select name="rating" id="rating-sel"> <option value="all">All</option> <option value="1">1 Star</option> <option value="2">2 Star</option> <option value="3">3 Star</option> <option value="4">4 Star</option> <option value="5">5 Star</option> </select> </div> </div> <div class="col-lg-5"> <label for="brand">brand</label> <div class="styled-select blue semi-square"> <select name="brand" id="brand-sel"> <option value="all">All</option> <option value="durex">Durex</option> <option value="skore">Skore</option> <option value="kamasutra">KamaSutra</option> </select> </div> </div> </div> </div> <div class="buttonHolder"> <button type="submit" id='upload-button' class="btn btn btn-outline-dark">Filter</button> </div> </form> <div id="content_data"> </div> … -
How to implement django webapp for travelling saleman problem
I have a semester project to implement travelling salesman problem using django framework and google maps api. This webapp is supposed to take some locations as input and output the route with minimal distance on the map shown on the website. I am already familiar with html, css and javascript. I have also learnt django for this project. But as this is my first development project, I don't know how to start making this project and what should be the structure of this project. Can anyone guide me for the basic steps to develop this project? -
Want to get the owner of the post but only i get 3 fields from 13 (Django)
User model Post model Post serializer Post view Using get method with POSTMAN Testing and i get only id , username and image -
Is there a way to create a Django app in memory just for testing?
I'm creating a Django project that behaves like a "framework". There is a custom management command to create apps with an given boilerplate (startapp overridden). Is there a way to create this app only in memory during the testing phase? -
I'm trying to add new product on my new project. But why it's show (no such table: main.auth_user__old)
I'm trying to add new product details on product table. But whenever I try to save this it's show me OperationalError at /admin/products/product/add/ *Here are errors detail: * Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Exception Type: OperationalError at /admin/products/product/add/ Exception Value: no such table: main.auth_user__old -
How to make one app to another app notifications message in Django?
I am trying to make one notifications message from one app to another app like One app is (app name)final(it python files like url,setting etc..)and other is (app name)user(it’s particularly app so its python files like model ,url,views,apps,admin etc...) So how to make?? So can u help me to solving my problems? -
Register Django custom path converter once for multiple urls files
I have converters.py file with defined MyCustomConverter. It is imported to multiple urls.py files (the same code for different django app urls): from django.urls import register_converter from converters import MyCustomConverter register_converter(MyCustomConverter, "my_custom_converter") Is it possible to avoid duplication and register the path converter once somewhere outside urls and use it everywhere? -
Django flatpages catch all
I am using the catch all pattern for flatpages in Django, like this:- urlpatterns = [ path('somepath/', include('project.somepathapp.urls')), path('anotherpath/', include('project.anotherpathapp.urls')), etc. ] urlpatterns += [ path('<path:url>/', views.flatpage), ] In my template, I use:- <a href="/about-us/">About Us</a> to get to the About flatpage. But the URL pattern strips off the final slash and passes the flatpage view the URL /about-us (as opposed to /about-us/). The flatpage view then spots that the URL doesn't end in a slash, adds it back in, finds the page and redirects to that URL but adds an extra slash so that the URL is now /about-us// If I remove the final slash from the catch all pattern, any URL from the main paths (somepath/ and anotherpath/) without the final slash is matched by the catch all pattern before the APPEND_SLASH is used and, since there is no page with that URL, the user gets a 404. So a URL like /somepath/ will work but /somepath won't. What have I done wrong? It seems like a catch-22 to me. I can't use the middleware option because that doesn't always get passed through other middleware views so I'm stuck. Any ideas? -
how to access phone number from django phonenumber_field.modelfields.PhoneNumberField?
I have PhoneNumberField in my django model. How to retrieve the actual phone number from the field object. class MyUser(models.Model): mobile = PhoneNumberField( verbose_name="Phone Number", blank=True, null=True, unique=True ) ... -
Persmissions of INSTALLED_APP not present, still 403 Forbidden error
I added a clearing cache app https://github.com/timonweb/django-clearcache to my django project. I don't see any new permissions from this app which I can assign to users. Still when other user than superadmin tries to access the clearing cache view, he gets "403 Forbidden" error. Which permission and how I should add for django-clearcache app to my project? Thank you. -
Celery No such table when using postgresql
Im currently putting my django project in production with docker and celery. for this i followed a blog post online. now i stumbled over an error which i can't seem to fix. when running the container with sqlite everything works just fine, but with postgresql i get this error: celery-beat_1 | [2020-03-20 14:32:00,052: INFO/MainProcess] Scheduler: Sending due task check_routers_online (Router.tasks.check_routers_online) celery_1 | [2020-03-20 14:32:00,066: INFO/MainProcess] Received task: Router.tasks.check_routers_online[d4cece14-1d20-43ae-8712-1ad48ce79208] celery_1 | [2020-03-20 14:32:00,085: ERROR/ForkPoolWorker-1] Task Router.tasks.check_routers_online[d4cece14-1d20-43ae-8712-1ad48ce79208] raised unexpected: OperationalError('no such table: Router_router') celery_1 | Traceback (most recent call last): celery_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute celery_1 | return self.cursor.execute(sql, params) celery_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute celery_1 | return Database.Cursor.execute(self, query, params) celery_1 | sqlite3.OperationalError: no such table: Router_router celery_1 | celery_1 | The above exception was the direct cause of the following exception: celery_1 | celery_1 | Traceback (most recent call last): celery_1 | File "/usr/local/lib/python3.7/site-packages/celery/app/trace.py", line 385, in trace_task celery_1 | R = retval = fun(*args, **kwargs) celery_1 | File "/usr/local/lib/python3.7/site-packages/celery/app/trace.py", line 650, in __protected_call__ celery_1 | return self.run(*args, **kwargs) celery_1 | File "/home/app/web/Router/tasks.py", line 14, in check_routers_online celery_1 | for router in routers: celery_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 276, in __iter__ celery_1 | self._fetch_all() … -
error when do database migration when building Django website
I use python3.7 to build website using Django Framework. I could start the web server well But when I tried to do database migration(when I run this command: python3 manage.py makemigrations, error occurs: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) ..... delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute 'is_relation' manage.py: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "locallibrary.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) -
One more "django.db.utils.ProgrammingError: relation "device_gclouddevice" does not exist"
I know there is a lot of post with this problem but somehow I can't find a solution for my problem. Configuration Django 3.0.0 Python 3.6.9 Docker 19.03.5 Issue I have a class starting like below, nothing fancy. class PubSub: test = GcloudDevice.objects.count() I use this class via command line and it works perfectly if I comment the test variable. BUT if I run the command line with this line I get: django.db.utils.ProgrammingError: relation "device_gclouddevice" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "device_gclouddevice". The thing is I am able to create GcloudDevice and I can see it and managed it from the admin zone. Things I already tried I deleted all my migrations, remove my db and its volume. Recreated all again, still the same issue. I tried after this to delete again the migration from my device app and migrate them on their own, still the same If anyone can help me and also explain to me how is it possible that everything works on the admin ( I can see on the django-debug-toolbar that this request is passing : SELECT COUNT(*) AS "__count" FROM "device_gclouddevice , HOW FRUSTRATING) but not from the command line I … -
How to implement browser side caching in django for dynamic files (eg If image is served from RAM )
I am using django and nginx for serving images. I use redis to store frequently accessed images. Since they're not static and not served by nginx directly,I don't know how to implement browser side caching. Image url looks like: site.com/image/image_name.jpg How should I go about generating hash,setting expire time,etc? Also how should I receive cached image's hash from browser and send 304 or invalidate the cached image? -
How do i filter many to many relationship in Django
My aim is to be able to filter by using the fields from the participants' table which I'm able to do. However, the participant table has a many to many relationship with sessions which is called in the sessions table. I'm not able to filter the participant data by filtering sessions I tried by using the related name but the filtering was unsuccessful. Can anyone help me with this as I'm still learning Django and this is my first project. participant_list.html {% load widget_tweaks%} {% block content %} <body class="sb-nav-fixed"> <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.first_name.label_tag }} {% render_field filter.form.first_name class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.last_Name.label_tag }} {% render_field filter.form.last_Name class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.country.label_tag }} {% render_field filter.form.country class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.gender.label_tag }} {% render_field filter.form.gender class="form-control" %} </div> <div> {% for choice in filter.form.organization %} <label class= "checkbox-inline"> {{ choice.tag}} {{ choice.choice_label }} </label> {% endfor %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.trainer.label_tag }} {% render_field filter.form.trainer class="form-control" %} </div> <div> {% for choice in filter.form.session %} <label class= "checkbox-inline"> {{ choice.tag}} {{ choice.choice_label }} </label> … -
Django: Join two Querysets to touple
Given two Querysets from different models, q1 = Queryset[a, b, c, d], q2 = Queryset[e, f, g, h]. How do i join them to a tuple, so the output is: Queryset[(a, e), (b, f)...]. I guess this isn't quite possible, since the Querysets are from different models. The output doesn't have to be a Queryset though, it can be a List aswell. I just want to be able to iterate over it. Thanks for your Help! -
Django computation in using aggregate method
I have this computation in my views that using filter and aggregate method first is i distinct the select the StudentSubjectGrade models and in the overall i filter the average and i use aggregate to compute the average and for every grading categories i have to multiply it by its PercentageWeight. this is the computation average = average * Grading_Categories__PercentageWeight / 100 students = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).order_by( 'Students_Enrollment_Records', 'Grading_Categories','id' ).values('id','Grading_Categories','Average', 'Grading_Categories__PercentageWeight') overall = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).aggregate(average_grade=Avg('Average') * students[ 'Grading_Categories__PercentageWeight'] / 100) this is their models class StudentSubjectGrade(models.Model): GradeLevel = models.ForeignKey(EducationLevel, on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, on_delete=models.CASCADE,null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject,on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories,on_delete=models.CASCADE,null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod,on_delete=models.CASCADE,null=True, blank=True) Gradedates = models.DateField(auto_now_add=True) Average = models.FloatField(null=True, blank=True) class gradingCategories(models.Model): CategoryName = models.CharField(max_length=500, null=True) PercentageWeight = models.FloatField() this is the error i get UPDATE when i tried this overall = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).aggregate(average_grade=Avg('Average') * F( 'Grading_Categories__PercentageWeight') / 100 ) I received this error -
How to debug nginx with django on docker
I have django and ngix on docker. My project returns Internal server Error. that's ok I should debug. I use docker-compose logs -f nginx but there is only this log. nginx | 172.18.0.1 - - [20/Mar/2020:13:26:15 +0000] "GET / HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" "-" And my django is works on python mangge.py runserver localserver. I guess it might be uwsgi related error. However I have no idea how to debug this. Where can i check log?? these are my docker-compose file version: '3' services: python: container_name: python build: ./python command: uwsgi --socket :8001 --module app.wsgi --py-autoreload 1 --logto /tmp/mylog.log volumes: - ./src:/code - ./static:/static ports: - "8082:8082" expose: - "8001" depends_on: - db db: image: mysql:5.7 container_name: db command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: todoList MYSQL_USER: docker MYSQL_PASSWORD: docker TZ: 'Asia/Tokyo' volumes: - ./mysql:/var/lib/mysql - ./sql:/docker-entrypoint-initdb.d nginx: image: nginx:1.13 container_name: nginx ports: - "8000:8000" volumes: - ./nginx/conf:/etc/nginx/conf.d - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./static:/static depends_on: - python phpmyadmin: container_name: phpmyadmin image: phpmyadmin/phpmyadmin environment: - PMA_ARBITRARY=1 - PMA_HOST=db - PMA_USER=root - PMA_PASSWORD=root links: - db ports: - 8081:80 volumes: - /sessions -
is django more secure than flask?
Django have got inbuilt security like XSS protection , CSRF protection , SQL injection protection and Clickjacking protection ,etc but flask doesnot have got inbuilt security . So it worth to tell that Django is more secure than Flask ? and for massive web application , developer should use Django instead of Flask ? -
Is there a Django built in signup view?
I know django has default account related views. the urls for them can be found in django.contrib.auth.urls. Is there a built in register view similar to those views? or do I have to implement one myself? -
how to customize the 403 error page in django?
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView,ListView from .models import Article from django.urls import reverse_lazy class ArticleListView(LoginRequiredMixin,ListView): model = Article template_name = 'article_list.html' login_url = 'login' How can i customize the 404 error page? -
django-guardian get_objects_for_user by checking permission via ForeignKey
I have two Django Models of the form: from django.db import models class Car(models.Model): pass class Wheel(models.Model): car = models.ForeignKey(Car, related_name='wheels', on_delete=models.CASCADE) I am using django-guardian to enforce object level permissions. The real application has a very large number of nested objects, and it was found that the write performance for creating all of the permission objects for every nested object was prohibitively slow. So instead, Users are granted permissions to the top level object (Car in this toy example). On REST endpoints that access Wheel, the Django REST Framework permissions are checked by walking the foreign key upwards (in this case Wheel.car) to verify if a User should have access to a particular Wheel. How could get_objects_for_user be used to get all of the Wheels for which a User has the appropriate permission for its parent Car? Specifically trying to override django-rest-framework-guardian's ObjectPermissionsFilter.filter_queryset to support filtering objects based on the permissions of one of their ForeignKeys. -
ReadOnly views checks wrong access token in Django Rest Framework
I have a view with the following permission permission_classes = [IsOwnerOrReadOnly] the permission definition is class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True # the object has a owner attribute return obj.owner == request.user It listing of the objects works as expected if the user authenticated and pass correct access token. it also works if I do not add Authorization in header. The only problem happens when the authorization token is expired or wrong. It sends 401 response. Invalid token header. No credentials provided. How can I ignore authorization token in django code for right or wrong authorization header. -
In python what is F() mean and how to use it in django?
I search over the Internet about F() mean in python and how to use it in Django filter. its not very clear to me, on how to use it in Django. -
Annotate function with input param field value
I have a model class Audiopart(models.Model): book_id = models.ForeignKey(Audiobook, on_delete=models.CASCADE) part_title = models.CharField(max_length = 255) part_text = models.TextField(blank = True, null=True) part_reader = models.CharField(max_length = 255) filename = models.FileField(upload_to=get_upload_path, blank=True) with function def get_upload_path(instance, filename): return os.path.join( 'audio', instance.book_id.folder, filename ) I want to upload file in directory and save in database just filename (without path). But not found any way to do it. So, I make function for cleaning filename def clear_filename(_filename): if '/' in _filename: _filename = _filename.split('/')[2] return _filename How can I print my objects in view with cleaned filename? def audioparts(request, _book_id): all_audioparts = list(Audiopart.objects.filter(book_id=_book_id, published=True).values()) return JsonResponse(all_audioparts, safe=False)