Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django url having %20 issues
One of my urls in url.py goes like this is like this path('<str:subject>/<str:agglevel>/<str:cust_cd>/',views.Customer.as_view()) cust_cd takes value from UI. cust_cd is basically customer name which is a string value. Url works fine for single words for cust_cd. Ex:Google,Gmail etc. But when I give words with spaces like Ex:You tube I get 404 error. It says you%20tube not found. Am not able to figure out how to configure url so that it accepts space characters. -
What is the difference between reconnectingwebsocket.js and websocket bridge.js?
I am implementing websockets using channels in Django project. I read that since Channel 2, the javascript bridge was removed. I saw some examples that use websocketbridge.js and others that use reconnectingwebsocket.js. What is the difference between them? Many thanks in advance for your replies, -
UUIDField in Django (error:operator does not exist: integer = uuid)
i want to use uuid field as my id (primary key) but there is something wrong with it and i can't fix it ... this is my model class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=90) description = models.TextField() image = models.ImageField(upload_to='courses/images') intro_video = models.FileField(upload_to='courses/videos') free = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) etc when i try to add a new course it gave's me this error ProgrammingError at /admin/courses/course/add/ operator does not exist: integer = uuid LINE 1: ..., "created_at" = NULL WHERE "courses_course"."id" = 'a130811... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Exception Type: ProgrammingError Exception Value: operator does not exist: integer = uuid my database is postgresql please help me. -
How to customize extended group model from admin in django
I was trying to extend django group model to have an extra field named display_name. It's working fine but I am not able to put any constraint or string representation in admin. Here is my models.py from django.db import models from django.contrib.auth.models import Group class CustomGroup(models.Model): def __str__(self): return self.group.name + "- " + self.display_name group = models.OneToOneField('auth.Group', unique=True, on_delete=models.CASCADE) display_name = models.CharField(max_length=40, blank=False) and here is my admin.py from django.contrib import admin from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin from django.contrib.auth.models import Group from .models import CustomGroup class GroupInline(admin.StackedInline): model = CustomGroup can_delete = False verbose_name_plural = 'custom groups' class GroupAdmin(BaseGroupAdmin): inlines = (GroupInline, ) # Re-register GroupAdmin admin.site.unregister(Group) admin.site.register(Group, GroupAdmin) I am trying to make the display_field required and change the string representation on admin interface. Both the thongs aren't working! -
How to connect one page with another page in django?
I have one landing page. I want to separate them and divide them in different pages so that whenever I make changes in it, I don't have to search a long index.html page. How to do this? I made changes but it is not working because in <div> it has id which I don't know how to reach? views.py def contact(request): if request.method == 'POST': print(request) first = request.POST.get('first', '') last = request.POST.get('last', '') email = request.POST.get('email', '') textarea = request.POST.get('textarea', '') print(first, last, email, textarea) return render(request, 'home/contact.html') index.html <div class="row"> <div class="col-lg-12 mb-5"> <form action="" method="post"> {% csrf_token %} <div class="form-group row"> <div class="col-md-6"> <input type="text" class="form-control" name="last" placeholder="Full name"> </div> </div> <div class="form-group row"> <div class="col-md-12"> <input type="text" class="form-control" name="email" placeholder="Email address"> </div> </div> <div class="form-group row"> <div class="col-md-12"> <textarea name="textarea" id="" class="form-control" placeholder="Write your message." cols="30" rows="10"></textarea> </div> </div> <div class="form-group row"> <div class="col-md-6 mr-auto"> <input type="submit" class="btn btn-block btn-primary text-white py-2 px-5" value="Send Message"> </div> </div> </form> </div> </div> -
How to use staticfiles from STATIC_ROOT in django
I wanted to use CKEditor in Django, and I want to modify its styles. After running the command python manage.py collectstatic, how to set settings so that Django would use statics from STATIC_ROOT which was collected. Thanks beforehand. Any ideas or solutions are welcome. -
_frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('django.test.signals') at 1407117951849
Whenever I go for python manage.py runserver command, this error is shown maximum time - Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/contrib/admin/checks.py", line 79, in check_dependencies for engine in engines.all(): File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/template/utils.py", line 90, in all return [self[alias] for alias in self] File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/template/utils.py", line 90, in <listcomp> return [self[alias] for alias in self] File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/template/utils.py", line 81, in __getitem__ engine = engine_cls(params) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/template/backends/django.py", line 25, in __init__ options['libraries'] = self.get_templatetag_libraries(libraries) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/template/backends/django.py", line 43, in get_templatetag_libraries libraries = get_installed_libraries() File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/template/backends/django.py", line 108, in get_installed_libraries for name in get_package_libraries(pkg): File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/home/hostbooks/django1/myproject/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File … -
Django easy_pdf remove margin
To create pdf from html i use easy_pdf. Small example: in view.py from easy_pdf.rendering import render_to_pdf_response context = dict({'user_company': 'test'}) template_name = "pdf_template.html" return render_to_pdf_response(request, template_name, context) html template: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <style> * { margin: 0 !important; padding: 0 !important; } </style> </head> <body> {{user_company}} <img src="/static/some_image.png" height="1000" width="1000"> </body> </html> Image and all element are placed inside margins: I have try to change and add some margins options inside side_packages/easy_pdf/templates/easy_pdf/base.html <style type="text/css"> @page { // added margin: 0 !important; * { margin: 0 !important; padding: 0 !important; } body { margin: 0 !important; padding: 0 !important; } @frame { margin: 0 !important; } // changed size: {{ pagesize|default:"A4" }}; margin-left: 0; margin-right: 0; margin-top: 0; margin-bottom: 0; @frame header { -pdf-frame-content: page-header; margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; } @frame footer { -pdf-frame-content: page-footer; bottom: 0; margin-left: 0; margin-right: 0; height: 0; } } </style> But without effect Question Where to add or change css options to remove the margins from pdf? -
Django migrations integrity error column contains null values
django.db.utils.IntegrityError: column "required_tem_grid" contains null values So I mistakenly gave wrong type of value when Django asked me to provide default value for existing rows. Problem is now that I am stuck with this error. I have been burned by this error before too and the only way I could recover was to create another db and running migrations again. Is there any other way? I have tried to revert to previous migration (initial) but this error pops up everywhere. There is no such column in the database that I can see. Is there some place this default value gets cached? -
Moving patch decorators into a function
I'm writing tests for models that trigger various functions which go beyond the scope of the testing (some functions invoke network functionality and other undesired things, which are not part of the test, can be slow to just let run and is easier to just switch off for testing purposes). We do this by using a series of @patch decorators above every test function as required. I don't like putting the same decorators over every test function in the test class because they clutter up the code. Is it possible to move all my patches into a function and just call it from there? I tried a simple implementation like below but it didn't work for me: from unittest.mock import patch class MyTest(APITestCase): def patch_all(self): p1 = patch('mod1.func1') p2 = patch('mod1.func2') ... return (p1, p2, ...) def test_function(self): p1, p2, ... = self.patch_all() perform_actual_test() Is there a way to patch out the functions without writing decorators everywhere and just calling a function instead? -
Probleme django
Bonjour j'ai un problème sur django depuis le models.py from django.contrib import admin from django.db import models from blog.models import user @admin.register(user) class user(models.Model): Prenom = models.CharField(max_length=50) Nom = models.CharField(max_length=50) NomComplet = models.CharField(m ``` ```python makemigrations from blog.models import user ImportError: cannot import name 'user' from 'blog.models' (C:\Users\user\PycharmProjects\pythonad\blog\models.py) -
Django WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:3022]
i want to create chat app, i follow the https://channels.readthedocs.io/en/latest/tutorial/part_2.html here, chat/ __init__.py routing.py urls.py settings.py wsgi.py i added this code to my routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) in my settings.py ASGI_APPLICATION = 'Accounting.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } in my urls.py urlpatterns = [ path('chat/', include('chat.urls')), path('admin/', admin.site.urls), ] in my chat app chat/ __init__.py consumers.py routing.py templates/ chat/ index.html room.html urls.py views.py i have consumers.py from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) this is the code in my chat>routing.py … -
How to recover 403 Forbidden error in django?
I am working on contact form but whenever I click on submit button, it gives me an error CSRF verification failed. Request aborted. How to recover this issue because I checked and didn't understand why it is giving me this error? views.py def contact(request): if request.method == 'POST': print(name) return render(request, 'home/contact.html') contact.html <div class="row"> <div class="col-lg-12 mb-5"> <form action="home/contact" method="post"> {% csrf_token %} <div class="form-group row"> <div class="col-md-6 mb-3 mb-md-0"> <input type="text" class="form-control" name="first" placeholder="First name"> </div> <div class="col-md-6"> <input type="text" class="form-control" name="last" placeholder="Last name"> </div> </div> <div class="form-group row"> <div class="col-md-12"> <input type="text" class="form-control" name="email" placeholder="Email address"> </div> </div> <div class="form-group row"> <div class="col-md-12"> <textarea name="textarea" id="" class="form-control" placeholder="Write your message." cols="30" rows="10"></textarea> </div> </div> <div class="form-group row"> <div class="col-md-6 mr-auto"> <input type="submit" class="btn btn-block btn-primary text-white py-2 px-5" value="Send Message"> </div> </div> </form> </div> </div> -
.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value
I am trying to locally connect to Microsoft sql server with django. This is my database config in settings.py and I haven't added anything in this file to override the values. settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'Name': 'ApartmentDB', } } I checked the connection as shown below as it is offered here in a separate file, using python manage.py shell />>> exec(open("path/to/testdb.py").read()): testdb.py from django.db import connections from django.db.utils import OperationalError db_conn = connections['default'] try: c = db_conn.cursor() except OperationalError: connected = False else: connected = True This I tried with python and it works with the same information provided (although I'm using pyodbc for that) I have been stuck with this problem for two days and I checked every similar problem but non them worked for me, plus no once faced this issue trying to connect to mssql server. I'm wondering if I'm missing something. -
In django how a user can block another user? [closed]
i"m thinking about in follwers list a user can block another user. And if the login user blocked other users, the users who are blocked can't see the user that blocks him ,their post. can it be done? -
Display second dropdown list only if a value from one dropdown list is selected and repeat it
I've two dropdown lists. I want to display second dropdown list value only if a value from first dropdown is selected. Can someone tell me how to do this? (P.S : You can take any random example and explain this to me) -
'datetime.time' object has no attribute 'date' in django admin
I'm trying to open an object in my Django application /admin, but this object gives me the error 'datetime.time' object has no attribute 'date despite I have no special calls or variables inside the model, here is the model : class LeaveRequest(models.Model): options = ( ('Leave', 'Leave'), ('Absence', 'Absence'), ) choices = ( ('Approved', 'Approved'), ('Rejected', 'Rejected'), ('Pending', 'Pending'), ) user = models.ForeignKey(User, related_name="leaverequest_user", on_delete=CASCADE) employee = models.ForeignKey(Employee, related_name="leaverequest_employee", on_delete=CASCADE) type = models.CharField(choices=options, max_length=50) status = models.CharField(choices=choices, max_length=50) text = models.CharField(max_length=500) date = models.DateField(auto_now_add=False, auto_now=False, null=True) time = models.DateTimeField(auto_now_add=False, auto_now=False, null=True) note am adding data field and DateTime field because I have 2 different types of requests that one only depends on the date and the other depends on date and time. -
Does Django automatically retrieve the parent object when a retrieved child object references that object?
In the Spring framework when an object A has a ManyToOne relation to object B: public class objectA{ private Long id; @ManyToOne private objectB objectB; } Then that objectB is only fetched when the getter method for objectB is called somewhere i nthe code. In that case an extra SQL query is made to fetch objectB of that particular objectA instance. You can change that behaviour by changing the fetch strategy to EAGER, in that case objectB is also fetched during the initial query to fetch objectA. My question is: What is the default fetch style that Django uses? Does Django always fetch any referenced parent objects or childobjects eagerly? Or does it differ per relation? Thank you -
Django: TypeError: an integer is required (got type str)
here i am getting the error, File "C:\Users\DEEDEVTR01\Desktop\python\pyenv\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\DEEDEVTR01\Desktop\python\pyenv\lib\site-packages\MySQLdb\connections.py", line 179, in init super(Connection, self).init(*args, **kwargs2) TypeError: an integer is required (got type str) views.py from rest_framework import views from rest_framework.views import APIView import MySQLdb from testpro.settings import connection cur, conn = connection() class Product_ListAPIView(APIView): def get(self,request,format=None): cur,conn = connection() query = ''' SELECT * FROM products''' try: with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(query) result = cursor.fetchall() data = list(result) return Response({"data":result},status=status.HTTP_200_OK) except Exception as e: print(e) -
How to add markers and send the locations to postgres/postgis database in django-leaflet
I added a django-leaflet map to display place markers. I couldn't display the markers as click events and send these to postgres/postgis database. I used django-leaflet forms to input the data. I wonder how I could display the place markers as well as send these to the backend along with other model fields. {% load static %} {% include 'base.html' %} {% load leaflet_tags %} <style> .leaflet-container { /* all maps */ width: 1400px; height: 800px; align-content: right; } </style> <html> <head> {% leaflet_js plugins="forms" %} {% leaflet_css plugins="forms" %} </head> <body> {% leaflet_map "map" callback="window.map_init_basic" %} <h2>Edit Apartment ID {{ Apartment.apt_id }}</h2> <h2>Edit Apartment Location {{ Apartment.location }}</h2> <form action="POST"> {{ form }} <input type="submit"/> </form> </body> </html> <script type="text/javascript"> window.addEventListener("map:init", function (e) { var detail = e.detail; L.marker([38.7578, 8.9806]).addTo(detail.map); }, false); </script> -
How do I extract all distint values for a specific key inside JSONField in Django running on Postgres?
Summary: For a dropdown I need to compute the distinct values for a specific key stored inside a JSONField in a table in Postgres database. Worst case scenario: The table contains 1-10 million entries. Background: I'm developing a setup in which I have multiple deployments (one for each customer). Each deployment contains a backend and multiple clients. Logs are posted continuously from clients to the backend. These logs will contain a field log_meta, which includes a key named origin, that describes from where the log-entry came. From customer to customer the value of origin may vary, and I don't want to enforce a restricted set of values for origin, but in general they denote the environment in which the client is running; "DEV" and "PRODUCTION" are potential values for origin. In practice, there might be only 1-2 distinct values for origin in a single deployment. The number of logs can be expected to be in the range of 1-10 millions. from jsonfield import JSONField from django.db import models class Log(models.Model) # Other fields log_json = JSONField(default=list) log_meta: JSONField(default=dict) # Will contain a key named origin In an "administrator frontend" I want to support that the administrator can filter (via a … -
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from view, but received `<class 'NoneType'>`
I have the following model - class Userdetails(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, blank=True, null=True) userno = models.CharField(max_length=200, blank=True, null=True And following View - @api_view(['GET', 'POST']) def useroptions(request): # to create new user if request.method == 'GET': names = Userdetails.objects.values("name","userno","id") return Response(names) elif request.method == 'POST': count = Userdetails.objects.count() serializer = userdetailsSerializer(data=request.data) usernos = Userdetails.objects.values("userno") names = Userdetails.objects.values("name") list_of_names = [] for ele in names: list_of_names.append(ele["name"]) list_of_usernos = [] for ele in usernos: list_of_usernos.append(ele["userno"]) This gives me this error on CMD - Internal Server Error: /view/pardel/2/multiuser Traceback (most recent call last): File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 507, in dispatch self.response = self.finalize_response(request, response, *args, **kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 422, in finalize_response % type(response) AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` [13/Feb/2020 08:09:14] "POST /view/pardel/2/multiuser HTTP/1.1" 500 17234 I am not getting the reason for this error and Please me to sort … -
Django ManytoManyField Display User Profile
i got stuck when trying to display User Name as Manytomanyfield in django template, but always display with ]>. how can i display it without queryset bla bla bla... just User 1 (First Name or Last Name or Full Name) class Refferal(models.Model): ref = models.ManyToManyField(Profile, related_name='ref') profile = models.ForeignKey(Profile, on_delete=models.PROTECT) def __str__(self): return str(self.ref) {% for tree in tree %} <section> <span class="diagram-icon"></span> <span class=diagram-label>{{ tree.ref.all }}</span> </section> {% endfor %} -
Django 'docker' is not recognized as an internal or external command,
when i type this docker run -p 6379:6379 -d redis:2.8 in pycharm terminal I receive this error did i miss something? -
Configuring HTTPS redirect fails
I am hosting a Django application on digitalocean. I follow this tutorial to finish its SSL certification. Following that tutorial I don't know where to add this line of code: return 301 https://$server_name$request_uri; I tried adding it in /etc/nginx/sites-enabled/leptitox_pro server { listen 80; server_name 68.183.203.33 yahkut.com www.yahkut.com; return 301 https://$server_name$request_uri; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/leptitoxadmin/pyapps/Leptitox; } location /media/ { root /home/leptitoxadmin/pyapps/Leptitox; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } when it didn't work I added it in /etc/nginx/sites-available/leptitox_pro server { listen 80; server_name 68.183.203.33 yahkut.com www.yahkut.com; return 301 https://$server_name$request_uri; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/leptitoxadmin/pyapps/Leptitox; } location /media/ { root /home/leptitoxadmin/pyapps/Leptitox; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } it didn't work there as well, so I added below the server block of code in /etc/nginx/nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { server { # new listen 80; # new server_name yahkut.com; # new return 301 https://$server_name$request_uri; # new } ## # Basic Settings ## sendfile on; tcp_nopush on; } I then restarted ngnix and run nginx …