Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django looking in wrong directory for templates
I followed a tutorial that taught to structure your templates directory as follows ~/project/main/templates/main to avoid and confusion. Now I'm trying to create another project and use the same structure as good practice. I get a TemplateDoesNotExist error when trying to render html located at /home/arch/project/main/templates/main/index.html it says Django is looking in /home/arch/project/templates/main/index.html settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] main/views.py from django.shortcuts import render, redirect def homepage_view(request): return render(request, "main/index.html") main/urls.py from django.urls import path from . import views app_name = "main" urlpatterns = [ path("", views.homepage_view, name="homepage_view") ] structure of my project . ├── db.sqlite3 ├── main │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── templates │ │ └── main │ │ ├── includes │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── media ├── project │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── settings.cpython-37.pyc │ │ ├── urls.cpython-37.pyc … -
How to redirect to user profile page after log in?
I'm looking for a way to redirect to the user profile page after log in. The problem I'm facing is that I can figure out how to pass the user_id into the url to get the redirection to complete. I understand that this is a common issue and I've tried following many suggested solutions I found from other people's issues, however none have allowed me to find a solution. <div class='registration'> <form method="post" action="{% url 'auth_login' %}">{% csrf_token %} <p> &nbsp;{% trans form.username.label_tag %} &nbsp;{{ form.username }}</p> <p> &nbsp; {% trans form.password.label_tag %} &nbsp; {{ form.password }}</p> <p>{% blocktrans %}<a href="{{ auth_pwd_reset_url }}">Forgot</a> your password? </br> <a href="{{ register_url }}">Need an account</a>?{% endblocktrans %}</p> <input class='login-button' type="submit" value="{% trans 'login' %}" /> <input class= 'login-button'type="hidden" name="next" value="{{ next }}" /> </form> </div> LOGIN_REDIRECT_URL = '/' path('profile/<int:user_id>', core_views.user_profile, name='profile'), Things I've tried (LOGIN_REDIRECT_URL = '/profile/')- this gave me a 404 error. -(LOGIN_REDIRECT_URL = '/profile/')- this gave me a NoReverseMatch error. input class= 'login-button'type="hidden" name="next" value="{% url profile request.user_id %}" I've tried making a login in view but that didn't work either. I've been stuck for a while on this and any help would be greatly appreciated! -
Using ternary operators in Q objects and avoid query with None values
While chaining Q objects in django, how can I avoid using a Q object if a particular value is None? I wrote the following: print("Doing an AND search") SearchResult = customer.objects.filter( Q(cstid=HospitalID if HospitalID else None) & Q(insurance_number__lower__contains=insurance_number.lower() if insurance_number else None) & Q(name__lower__contains=name.lower() if name else None) & Q(ageyrs=ageyrs if ageyrs.isdigit() else None) & Q(agemnths=agemnths if agemnths.isdigit() else None) & Q(mobile__contains=mobile if mobile else None) & Q(alternate__contains=alternate if alternate else None) & Q(email__lower__contains=email.lower() if email else None) & Q(address__lower__contains=address.lower() if address else None) & Q(city__lower__contains=city.lower() if city else None) ,linkedclinic=clinicobj) SearchResult = customer.objects.filter(my_q, linkedclinic=clinicobj) I get the error: POST data <QueryDict: {'csrfmiddlewaretoken': ['YN6riYcjKaYUi6wtwPCY6AzqPt8JwL5VZiZKo0y8r4zBlBBv4ncpWLvubclroSVE'], 'HospitalID': [''], 'insurance_number': [''], 'name': [''], 'ageyrs': [''], 'agemnths': [''], 'email': ['rie'], 'mobile': [''], 'alternate': [''], 'address': [''], 'city': [''], 'include_all_terms': ['on']}> Doing an AND search 2019-08-11 01:04:33,826 django.request ERROR Internal Server Error: /clinic/checkin Traceback (most recent call last): File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/joel/myappointments/venv/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/joel/myappointments/venv/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/joel/myappointments/venv/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/joel/myappointments/clinic/views.py", line 2840, in checkin_patient_specific ORSearchResult = ORSearch_Patients(HospitalID, clinicobj, name, ageyrs, agemnths, mobile, alternate, email, address, … -
Registration problem in DJANGO REST FRAMEWORK
I have a User model and ı want to create user register API. I created API but it doesn't work. I think I did something wrong but ı can't fix it. it looks like on swagger UI like this: It doesn't show the body item in swagger UI How can ı fix this register problem? view.py: class RegistrationView(APIView): authentication_classes = (CsrfExemptSessionAuthentication,) # permission_classes = (XHROnly,) def post(self, request, *args, **kwargs): serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(raise_exception=False): user = serializer.save() user = authenticate(email=user.email, password=serializer.validated_data['password1']) if user is not None: token, created = Token.objects.get_or_create(user=user) if user.is_active: login(request, user) return Response({'status': 'success', 'token': token.key, 'user': UserSerializer(user, context={'request': self.request}).data}, status=201) else: return Response({'status': 'success', 'token': token.key, 'user': UserSerializer(user, context={'request': self.request}).data}, status=201) else: return Response({'status': 'error', 'errors': serializer.errors}, status=203) else: return Response({'status': 'error', 'errors': serializer.errors}, status=203) serializers.py: class RegistrationSerializer(Serializer): full_name = CharField( max_length=200, style={'input_type': 'text', 'placeholder': 'İsim'} ) email = EmailField( max_length=100, style={'placeholder': 'Email'}) password1 = CharField( max_length=100, style={'input_type': 'password', 'placeholder': 'Şifre'} ) password2 = CharField( max_length=100, style={'input_type': 'password', 'placeholder': 'Şifre Tekrar'} ) def validate(self, data): if data['password1'] == data['password2']: return data else: raise ValidationError('Girdiğiniz şifreler uyuşmamakta.') def validate_full_name(self, value): return value def validate_email(self, value): try: user = User.objects.get(email=value) raise ValidationError("Bu email kullanılmaktadır.") except User.DoesNotExist: return … -
Django response setting a json as a cookie
I would like to set the value of a client side cookie from django as a javascript dictionary object. I know you can set a cookie value of a string like this in django: response = HttpResponseRedirect( reverse('app:home') ) response.set_cookie( 'cookiekey', 'value' ) return response I can then read the cookie on the client side like this: Cookies.get( 'cookiekey' ) using the Cookies library ( https://github.com/js-cookie/js-cookie ) What I am unable to do is set the cookie to be a dictionary/json object: I have tried this: response.set_cookie( 'cookiekey', {'value' : 'value'} ) and import json response.set_cookie( 'cookiekey', json.dumps( {'value' : 'value'} ) ) and then tried to read the cookie back on the client side using: Cookies.getJSON( 'cookiekey' ) but this doesn't seem to give me back a javascript dictionary object (neither does Cookies.get) but instead a string: var message = Cookies.getJSON( 'cookiekey' ); alert( typeof message ); -
Updating Django Model After Serialization from DRF
I currently have an API endpoint that receives data from the client and kicks of a scrapy crawler job. The problem is I need to create the Job model instance, kick off the scrapy job, then update the model with the task_id returned by the scrapy job. The model is successfully updated, but the serialized data returned by DRF does not have the updated data. I need to create the model instance prior to kicking off the job so that the scrapy job has the primary key of the job to update its status and add data as it finishes the job. I know why JSON response does not have my new data: I am updating the model in the view after DRF has done its work. I cannot edit the serialized data once .save() has been called on the serializer instance. views.py class StartJobView(views.APIView): def post(self, request): # map incoming 'id' field to 'client_id' request.data['client_id'] = request.data['id'] serializer = JobSerializer(data=request.data) if serializer.is_valid(): # create job entry serializer.save() id = serializer.data.get('id') # get pk to pass to spider settings = { 'id': id, } task_id = scrapyd.schedule('default', 'tester', settings=settings) Job.objects.filter(id=id).update(task_id=task_id) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) JSON response: { "id": … -
Serializce Multiple models in django
I need to serialize multiple models in order to have one single JSON as an answer. The serializers.py i made it's like this from rest_framework import serializers from .models import SnpsFunctionalelement,Snps,Functionalelement,Celllines class SnpsSerializer(serializers.ModelSerializer): class Meta: model = Snps fields = ['rsid'] class FunctionalElementSerializer(serializers.ModelSerializer): class Meta: model = Functionalelement fields = ['name'] class CelllinesSerializer(serializers.ModelSerializer): class Meta: model = Celllines fields = ['name'] class SnpsFunctionalelementSerializer(serializers.ModelSerializer): snps = SnpsSerializer(many = True) functional = FunctionalElementSerializer(many = True) cellline = CelllinesSerializer(many = True) class Meta: model = SnpsFunctionalelement fields = ['snps__rsid', 'functional__name', 'cellline__name', 'countexperiments', 'filetype'] def to_internal_value(self, data): snps_info = {kv: data[kv] for kv in data if kv in list(SnpsSerializer.Meta.fields)} functional_info = {kv: data[kv] for kv in data if kv in list(FunctionalElementSerializer.Meta.fields)} cellline_info = {kv: data[kv] for kv in data if kv in list(FunctionalElementSerializer.Meta.fields)} return super(SnpsFunctionalelementSerializer, self).to_internal_value({ 'snps__rsid': snps_info, 'functional__name': functional_info, 'cellline__name': cellline_info }) where to_internal_value is made for having a plain JSON made like this { "rsid":.... "name":.... ..... "filetype":... } { "rsid": ..... } etc. etc. but it gives me an error that says The field 'cellline' was declared on serializer SnpsFunctionalelementSerializer, but has not been included in the 'fields' option. So if someone could tell me if there is another way to … -
How to write sql COALESCE in Django
I'm new to Django. How to write COALESCE sql queryset in to django orm. query = 'SELECT COALESCE(max(CAST(order_no as UNSIGNED)), 0) as o,id from nanossc_Sales_master' models.py class Sales_master(models.Model): slno = models.IntegerField(blank=True, null=True) order_no = models.CharField(max_length=50, blank=True, null=True) type = models.CharField(max_length=50, blank=True, null=True) customer_id = models.CharField(max_length=50, blank=True, null=True) customer_name = models.CharField(max_length=50, blank=True, null=True) brand_name = models.CharField(max_length=50, blank=True, null=True) name = models.CharField(max_length=50, blank=True, null=True) -
Replacing function attribute with variable containing string
I want to write code in a singe line to replace the following if-else code. Can I somehow use the status variable in the filter function directly as an attribute ? status = request_queries.get('status', None) if(status = 'saved'): queryset = queryset.filter(saved = True) elseIf (status = 'shortlisted'): queryset = queryset.filter(shortlisted = True) elseIf (status = 'accepted'): queryset = queryset.filter(accepted = True) elseIf (status = 'rejected'): queryset = queryset.filter(rejected = True) -
How to set default image from not from media directory
I don't know how to correctly set default path to none-media image. I've tried to add /, but it doesn't help: ... image = models.ImageField(... default='/static/course_lesson/resources/images/default.jpg') ... And in HTML page image.url looked as follows: ... src="/media/static/course_lesson/resources/images/default.jpg" ... -
where `form.as_p`in django templates come from?
I have a generic view and a form template. my view is: class BlogCreateView(CreateView): model = Post template_name = "post_new.html" fields = "__all__" and my form template is: {% extends "base.html" %} {% block content %} <h1>New Post</h1> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> {% endblock content %} now my question is about form.as_p or specifically form. Where did that come from? help me please. thanks a lot -
Writing script tag outside or inside block?
Please Consider the following pieces of code. <!--templates/home.html--> {% extends 'base.html' %} {% load static %} {% block content %} {% for post in object_list %} <div class = 'post-entry'> <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</h2> <p>{{ post.body }}</p> </div> {% endfor %} <script type = "text/javascript" src = "{% static 'js/test.js' %}"></script> {% endblock content %} and <!--templates/home.html--> {% extends 'base.html' %} {% load static %} {% block content %} {% for post in object_list %} <div class = 'post-entry'> <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</h2> <p>{{ post.body }}</p> </div> {% endfor %} {% endblock content %} <script type = "text/javascript" src = "{% static 'js/test.js' %}"></script> The first one executes successfully but the second one does not. Is it necessary to load an external static file from inside a django template block and if not then why does the second code not execute? PS: I am new to django. For purpose of clarity i am also providing the code for the base template here. <!--templates/base.html--> {% load static %} <html> <head><title>Django Blog</title> <link href = "{% static 'css/base.css' %}" rel = "stylesheet"> </head> <body> <header><h1><a href = "{% url 'home' %}">Django Blog</a></h1></header> <div> {% … -
How to manage change Emailid and Change Password for user logged in using Social Media in Django all-auth?
How can I give the option to change Email-Id and change Password for users logged in through AllAuth [Gmail / Facebook]. -
How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip
I am trying to install django-heroku using pip but it keeps running into an error. I have seen suggestions telling me to make sure my python version in heroku is up to date. I have already done that. After pushing to heroku master, i ran the install command but it gives me the following errors. pip install django-heroku Error: ERROR: Command errored out with exit status 1: command: /Users/user/Dev/trydjango/new_env/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/xl/s533dc515qs8sd3tpg7y5ty80000gp/T/pip- install-xqsix26g/psycopg2/setup.py'"'"'; egg_info --egg-base pip-egg-info cwd: /private/var/folders/xl/s533dc515qs8sd3tpg7y5ty80000gp/T/pip- install-xqsix26g/psycopg2/ Complete output (23 lines): running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg- info/dependency_links.txt writing top-level names to pip-egg-info/psycopg2.egg- info/top_level.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add t . he directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full … -
How to serialize foreign key from model X in model Y, where model X has the relation to model Y?
I need to serialize my Contracts view in my Registration view. I understand how to do it if there was a foreign key in the Registration model relating the Contract model, but in this case there is a relation from the Contract model to the Registration model. I need to do this in a bigger project, this is just a simple boiler plate. Basically, I want my output to be this: [ { "id": 1, "client": "John Doe", "contract": { "id": 1, "client": "John Doe", "name": "New Identity", "registration": 1 } }, { "id": 2, "client": "Jane Doe", "contract": { "id": 2, "client": "Jane Doe", "name": "Identity theft", "registration": 2 } } ] Models: class Client(models.Model): name = models.CharField(max_length=250) address = models.CharField(max_length=250) email = models.EmailField() class Registration(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) class Contract(models.Model): name = models.CharField(max_length=150) client = models.ForeignKey(Client, on_delete=models.CASCADE) registration = models.ForeignKey(Registration, on_delete=models.CASCADE) Viewsets: class ClientViewSet(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = ClientSerializer class RegistrationViewSet(viewsets.ModelViewSet): queryset = Registration.objects.all() queryset = queryset.select_related("client") serializer_class = RegistrationSerializer class ContractViewSet(viewsets.ModelViewSet): queryset = Contract.objects.all() queryset = queryset.select_related("registration").prefetch_related( "client" ) serializer_class = ContractSerializer Serializers: class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" class ContractSerializer(serializers.ModelSerializer): client = NameSerializer() class Meta: model = Contract fields = … -
Django models many to many relations
I'm moving my first steps with django and I'm trying to figure out a thing. Suppose that we have a model.py made like this where NameEffect has a many to many relation class Name(models.Model): nameid = models.IntegerField() name = models.CharField(max_length=255) class Effect(models.Model): effectid = models.IntegerField() effect = models.TextField() class NameEffect(models.Model): nameid = models.IntegerField() effectid = models.IntegerField() start = models.PositiveIntegerField() strand = models.PositiveIntegerField() and I want to create a QuerySet where every entry contains name,effect,start,strand of the researched name. Fact is that the only solution I found was using raw SQL queries but I can't understand how to do it with the django models approach -
Django RawQuerySet Subtraction with raw query
I'm trying this query in postgres it working select (SELECT sum(amount) FROM expense_expense WHERE flow='INFLOW')- (SELECT sum(amount) FROM expense_expense WHERE flow='OUTFLOW') AS balance; Getting Out Put balance| -------| 6370.77| But when i try with Django RawQuerySet It is asking for primary key In [168]: r = Expense.objects.raw("select(select sum(amount) FROM expense_expense where flow='INFLOW') - (select sum(amount) FROM expense_expense where flow='OUTFLOW') as balance;") In [169]: r.columns Out[169]: ['balance'] In [170]: r[0] --------------------------------------------------------------------------- InvalidQuery Traceback (most recent call last) <ipython-input-170-8418cdc095ae> in <module> ----> 1 r[0] ~/Desktop/workspace/projects/python/django/expenditure/venv/lib/python3.7/site-packages/django/db/models/query.py in __getitem__(self, k) 1433 1434 def __getitem__(self, k): -> 1435 return list(self)[k] 1436 1437 @property ~/Desktop/workspace/projects/python/django/expenditure/venv/lib/python3.7/site-packages/django/db/models/query.py in __iter__(self) 1393 1394 def __iter__(self): -> 1395 self._fetch_all() 1396 return iter(self._result_cache) 1397 ~/Desktop/workspace/projects/python/django/expenditure/venv/lib/python3.7/site-packages/django/db/models/query.py in _fetch_all(self) 1380 def _fetch_all(self): 1381 if self._result_cache is None: -> 1382 self._result_cache = list(self.iterator()) 1383 if self._prefetch_related_lookups and not self._prefetch_done: 1384 self._prefetch_related_objects() ~/Desktop/workspace/projects/python/django/expenditure/venv/lib/python3.7/site-packages/django/db/models/query.py in iterator(self) 1408 model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order() 1409 if self.model._meta.pk.attname not in model_init_names: -> 1410 raise InvalidQuery('Raw query must include the primary key') 1411 model_cls = self.model 1412 fields = [self.model_fields.get(c) for c in self.columns] InvalidQuery: Raw query must include the primary key In [171]: Is there anything I'm missing or anything I need to do, please let me know how can … -
Django coverage on travis-ci returns ModuleNotFoundError
This is my first project where I setup an CI test coverage analysis. My django project has some tests and settings files for various environmens. The layout looks like ├── manage.py ├── papersquirrel │ ├── __init__.py │ ├── __pycache__ │ ├── settings │ │ ├── base.py │ │ ├── ci.py │ │ ├── example.py │ │ ├── __init__.py │ │ └── __pycache__ │ ├── urls.py │ └── wsgi.py ├── readme.md ├── requirements.txt ├── res ├── squirrel │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── management │ │ └── commands │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ ├── models.py │ ├── __pycache__ │ ├── templates │ │ └── squirrel │ ├── tests │ │ └── basic-html.html │ ├── tests.py │ ├── urls.py │ ├── utils.py │ └── views.py ├── static When I execute the coverage analysis on my local virtualenv, it works by invoking coverage run manage.py test --settings papersquirrel.settings.ci . But when I invoke this command via .travis.yml I get only ModuleNotFoundError: No module named 'papersquirrel.settings.ci' I tried various combinations and reviewed a lot of docs and howtos, but it seems, that my travis virtualenv seems to have problems … -
Change span text when clicked
I'm creating a social media page, and I am adding a functionality where if a posts characters is greater than 50, show a shorter version, and append a ...more at the end. In my models.py i have a function that displays 50 characters and beyond, and I want to use this when the ...more is presses. Currently when pressed the text just completely disappears. models.py class Post(models.Model): file = models.FileField(upload_to='files/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.user.username def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def summary_pretty(self): return self.summary[:50] def summary_rem(self): return self.summary[50:] home.html {% extends 'accounts/base.html' %} {% block content %} {% load widget_tweaks %} {% load static %} {% for post in posts %} <div class="container pl-5"> <div class="row pt-3"> <img src="{% static 'rect.jpg' %}" width="600px" height="60px"> <div class="pt-3 pl-5" style="position: absolute;"> <b> {{ post.user.username }} </b> </div> <br> <div class="card" style="width: 600px;"> <img src="{{ post.file.url }}" width="599px"> </div> <br> <img src="{% static 'rect.jpg' %}" width="600px" height="150px"> <div class="col-6"> <script> function addMore(e) { e.innerText = "{{ post.summary_rem }}"; } </script> {% if post.summary|length > 50 %} <div class="" style="position: absolute; bottom: 75px; left: 35px;"> <b> {{ post.user.username }} </b> {{ post.summary_pretty }} <span … -
deleted all migrations with __init__.py file django
I have accidentally deleted all of my init.py files while trying to reset migrations i have recreated the migrations file on each of my apps with a blank init.py file but some errors seem to pop up like: no module named "myprojectname.users". -
No handler for message type websocket.group_send, how tofix?
i switch from one user websocket connection to make chat room, that 2 people can connect each other, but on switch, in recieve method, need now group_send, and after that it stoped work, how to fix? Full Traceback > Exception inside application: No handler for message type > websocket.group_send File > "D:\Dev\Web\Chaty\lib\site-packages\channels\sessions.py", line 183, > in __call__ > return await self.inner(receive, self.send) File "D:\Dev\Web\Chaty\lib\site-packages\channels\middleware.py", line 41, > in coroutine_call > await inner_instance(receive, send) File "D:\Dev\Web\Chaty\lib\site-packages\channels\consumer.py", line 59, in > __call__ > [receive, self.channel_receive], self.dispatch File "D:\Dev\Web\Chaty\lib\site-packages\channels\utils.py", line 52, in > await_many_dispatch > await dispatch(result) File "D:\Dev\Web\Chaty\lib\site-packages\channels\consumer.py", line 75, in > dispatch > raise ValueError("No handler for message type %s" % message["type"]) No handler for message type websocket.group_send > WebSocket DISCONNECT /messages/dildo/ [127.0.0.1:58910] Consumer import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print('Connected', event) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] thread_obj = await self.get_thread(me, other_user) chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ 'type':'websocket.accept' }) async def websocket_receive(self, event): print('Recive', event) front_response = event.get('text', None) if front_response is not None: compiled_response_data = json.loads(front_response) if 'FormData' in compiled_response_data: … -
run tika python with django in docker
I've a django site that parses pdf using tika-python and stores the parsed pdf content in elasticsearch index. it works fine in my local machine. I want to run this setup using docker. However, tika-python does not work as it requires java 8 to run the REST server in background. my dockerfile: FROM python:3.6.5 WORKDIR /site COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 EXPOSE 9200 ENV PATH="/site/poppler/bin:${PATH}" CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] requirements.txt file : django==2.2 beautifulsoup4==4.6.0 json5==0.8.4 jsonschema==2.6.0 django-elasticsearch-dsl==0.5.1 tika==1.19 sklearn where (dockerfile or requirements) and how should i add java 8 required for tika to make it work in docker. Online tutorials/ examples contain java+tika in container, which is easy to achieve. Unfortunately, couldn't find a similar solution in stackoverflow also. -
Fastest way to iterate over django queryset and trigger post_save signal
I have a project that has lots of models and some of these models have over +9.5M entry. I should iterate over whole entry and trigger post_save method. How can I do this in a fastest way? -
how to change the format of date in django validation error
class Registration(models.Model): Date_of_birth=models.DateField(blank=True, default='', null=True) class Meta: db_table = "gym_registration" -
why my django framework shows me this error in terminal?
every time i want to start my django project developement server its shows me error ? (base) C:\Users\asus\PycharmProject\textutils\textutils\textutils>python manage.py runserver python: can't open file 'manage.py': [Errno 2] No such file or directory