Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update javascript files
I'm developing a django app and I need my production server to tell browsers to update cached js files on every build. How do I do that. As you have probably guessed I've updated js files but my (and every other user's) browser cached previous version of those js files. I want those files to always be updated. Maybe I can tell browsers not to cache any data from page, or I can directly tell browsers to update js files. I accept any solutions, please help me. -
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`, AssertionError
AssertionError:Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view views.py # Create your views here. from rest_framework import serializers from rest_framework import views from rest_framework.views import APIView from rest_framework.generics import ListAPIView from rest_framework.response import Response from rest_framework.status import ( HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST, ) import MySQLdb from testpro.settings import connection cur, conn = connection() class Product_ListAPIView(ListAPIView): 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) print(request.data) return Response({"data":result},status=status.HTTP_200_OK) except Exception as e: print(e) I think the connection is proper but I am not sure why I am getting this error, it would be great if anyone can help me figure out what I am doing wrong -
GIT - Pushing from server to GitHub triggers a Pull error
I am quite new to git versioning so excuse me in advance if the query may seem trivial. I have a django project on my local computer and I pushed it on a GitHub repository. I cloned the repository on the online linux server hosting the project. So far so good. Due to the tight schedule I need to work on, I made some patches directly on the online code. Then i decided to push these changes on the github repository so that i can pull them on my local computer and start implementing new changes to push back on GitHub at a later stage. Once i run the push command from the server to GitHub an error informing me to consider pulling before pushing as another user (the local one) is pushing on the same GitHub repository is displayed. My questions are: is it safe to pull from GitHub on the server? I am afraid the patches I have applied directly on the server will disappear as a result of pulling from GitHub (which does not contain the patches) if it is safe to pull, what is the correct command sequence? Pull, add ., commit, push? Thanks in advance. -
Problem with adding additional attributes to django-oscar with solr and haystack
Im new here and its my first question, sorry if Im missing something. It seems django-oscar have a problems with search facets. However I have a project where its working with defaults "price range" and some default fields like "product class" and "raiting". Im trying to add my own attributes to solr, which was added true models.py: location = models.TextField(('Location'), blank=True, default=None, null=True) duration = models.TextField(('Duration'), blank=True, default=None, null=True) I added this lines to my search_indexes.py class ProductIndex(indexes.SearchIndex, indexes.Indexable): product_class = indexes.CharField(null=True, faceted=True) <-- deafult working location = indexes.CharField(null=True, faceted=True) duration = indexes.CharField(null=True, faceted=True) def prepare_product_class(self, obj): return obj.get_product_class().name <-- default working def prepare_location(self, obj): return obj.get_location_class().name def prepare_duration(self, obj): return obj.get_duration_class().name Im added them to settings.py OSCAR_SEARCH_FACETS = { 'fields': OrderedDict( [('product_class', {'name': _('Type'), 'field': 'product_class'}), ('rating', {'name': _('Rating'), 'field': 'rating'}), ('location', {'name': _('Location'), 'field': 'location'}), ('duration', {'name': _('Duration'), 'field': 'duration'}), ]), So the first problem is with command python manage.py build_solr_schema > solr/schema.xml building schema.xml which is not working - solr gives errors to some id field, and there is no fields that i wanted to add. Okay, I get working schema.xml from github, its working! And I added there two fields manually: <field name="location" type="edge_ngram" indexed="true" stored="true" … -
How to nest validation errors in Django
I am trying to nest validation errors into one response. How can I group them into fields? Using this example, instead of raising each error, group everything into one response. The example desired output is below. Here is my example: class HighScoreSerializer(serializers.BaseSerializer): def to_internal_value(self, data): score = data.get('score') player_name = data.get('player_name') # Perform the data validation. if not score: raise serializers.ValidationError({ 'score': 'This field is required.' }) if not player_name: raise serializers.ValidationError({ 'player_name': 'This field is required.' }) if len(player_name) > 10: raise serializers.ValidationError({ 'player_name': 'May not be more than 10 characters.' }) # Return the validated values. This will be available as # the `.validated_data` property. return { 'score': int(score), 'player_name': player_name } My desired result: {'player_name': ['This field is required.', 'May not be more than 10 characters.'], 'score': ['This field is required.']} -
I want to update a group of model object but it doesn't work
I am trying to assign these to users and using a form for the same model to update it but it doesn't work for some reason, this is the code def assign_blanks(request): if request.method == 'POST': form = assign_blank_form(data=request.POST) from_value = request.POST.get("from_value", "") to_value = request.POST.get("to_value", "") blanks = blank.objects.all() for b in blanks: if b.number >= int(from_value) and b.number >= int(to_value): b.advisor = form.instance.advisor print(b.number) return render(request, 'assign_blanks.html') else: form = assign_blank_form return render(request, 'assign_blanks.html', {'form':form}) class assign_blank_form(ModelForm): class Meta: model = blank fields = ['advisor'] <form class="box" method = "post"> {% csrf_token %} <h1>Air Ticket Sales</h1> {{ form }} assign from: <input type="number" name="from_value" value="{{ from_value }}"> assign to: <input type="number" name="to_value" value="{{ to_value }}"> <input type="submit" name="" value="Assign blanks"> </form> -
Is there a way to set different id for each ValidationError in Django?
This is how my form looks: class TestForm(forms.ModelForm): class Meta: model = Restaurant fields = [ 'title', 'content', ] def clean(self, *args, **kwargs): title = self.cleaned_data.get("title") content = self.cleaned_data.get("content") error_dict = {} if len(title) < 3: error_dict['title'] = ValidationError("testerror1") if len(content) < 3: error_dict['content'] = ValidationError('testerror2') if error_dict: raise ValidationError(error_dict) If I try to submit the form with empty title and content it shows two error messages (testerror1, testerror2), they appear above each field label and looks like this: <ul class="errorlist"> <li>test2</li> </ul> But I want to hide each of them if client click on input, so I tried with Jquery: $("#my_form_id").find('input, textarea').click(function() { $(this).closest('ul').hide(); }) Without success (it doesn't found any <ul> element. My question is, is there a way to set different id for each error? So that I can manage each one separately. -
Using Motor or any other async MongoDB driver in Django 3 projects
Is there any way using Motor or any other async MongoDB driver in Django 3 projects? I tried using motor clients First: motor_asyncio.AsyncIOMotorClient and Second: motor_tornado.MotorClient. The first one raises below exception: Task <Task pending coro=<SessionMiddlewareInstance.__call__() running at SOMEWHERE>> got Future <Future pending cb=[run_on_executor.<locals>._call_check_cancel() at SOMEWHERE]> attached to a different loop The second one doesn't raise any exceptions but it stops at the line that I insert messages in db with insert_one method. Is there any way to insert and read data from MongoDB asynchronously? -
Why don't work permissions in post method?
I get following viewset class ThankYouMessageViews(mixins.RetrieveModelMixin, mixins.CreateModelMixin, GenericViewSet): lookup_url_kwarg = 'id' permission_classes = (IsDonatedProductOwnerOrReadOnly,) def get_serializer_class(self): if self.action == 'create': return ThankYouMessagesCreateSerializer return ThankYouMessagesGetSerializer def perform_create(self, serializer): pass Why don't work permission in create method? But permission works in retrieve method -
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)