Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
got this error in django (command prompt)
Exception happened during processing of request from ('127.0.0.1', 52633) Traceback (most recent call last): File "c:\users\sonu sharma\appdata\local\programs\python\python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\users\sonu sharma\appdata\local\programs\python\python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\users\sonu sharma\appdata\local\programs\python\python38\lib\socketserver.py", line 720, in init self.handle() File "C:\Users\sonu sharma\Desktop\myenv\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\sonu sharma\Desktop\myenv\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\users\sonu sharma\appdata\local\programs\python\python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
Download file after payment with Django (digital product)
I am building a digital ecommerce platform with Django. I want my users to get automatically a file after payment. So when they complete a payment they get automatically the file downloaded. thanks -
Django query related objects by there content_type
I have a Hit table at my Django project that stores view-counts for multiple object_types e.g. Post, Products & Profile models ... What I do not understand is how I can pull out object out of my Hit table that belong to a specific content_type or in other words, how to build the query correctly. Take the following query(s) as an example where I want to get all objects by there content_type out of my Hit Table: def recently_viewed_proposals(): hit = Hit.objects.all() queryset_p = Hit.objects.filter(pk__in=hit.filter(content_type=12).values_list('id', flat=True)) queryset_psm = Hit.objects.filter(pk__in=hit.filter(content_type=15).values_list('id', flat=True)) queryset_pso = Hit.objects.filter(pk__in=hit.filter(content_type=20).values_list('id', flat=True)) hit_elements = chain( queryset_p.random(len(queryset_p)), queryset_psm.random(len(queryset_psm)), queryset_pso.random(len(queryset_pso)) ) post_elements_list = list(hit_elements) print(post_elements_list) n_proposals = min(len(post_elements_list), config.MAX_RECENTLY_VIEWED_PROPOSALS) recently_viewed_proposals = random.sample(post_elements_list, n_proposals) return recently_viewed_proposals 12 = content_type id of Post model This is how my Hit table look like: class Hit(models.Model): objects = RandomManager() content_type = models.ForeignKey(ContentType, limit_choices_to=hit_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') viewer = models.ForeignKey(User, verbose_name="Viewer", on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now=True) But I just get back the pk of the Hit model and not the pk's of the Post objects I stored at the Hit table. How can I access the pk's of my Post objects? -
pass attrs to BoundField.as_widget() django
I want to pass html attributes with BoundField.as_widget() by passing them to attrs in the method. Django doc says BoundField.as_widget(widget=None, attrs=None, only_initial=False)¶ Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field’s default widget will be used. So I tried passing attributes like this: BoundField.as_widget(attrs={'class': 'container'}), which didn't work. forms.py class HiddenForm(forms.Form): testfield = forms.CharField(max_length=100, widget=forms.HiddenInput(attrs={'class': 'container'})) class BlahForm(forms.ModelForm): class Meta: model = Blah views.py. Model Blah is OneToOneField relationship to Model A. def myview(request, arg): a = get_object_or_404(A, somefieldname=arg) initial = {'blah': a} form = BlahForm(request.POST or None, initial=initial) # ModelForm from Model Blah value = a.pk hidden_input = HiddenForm(request.POST or None) hidden_input['testfield'].as_widget(attrs={'value': value }) # This is the reason I want to pass attrs with as_widget. I want to pass value to the hidden input form, so that the hidden form can handle submitting disabled form value, which I did on purpose to keep user from changing the value. if form.is_valid(): form.save() return redirect('somewhere', someparameter=arg) context = { 'form': form, 'value': value, 'hidden_input': hidden_input } return render(request, 'someapp/sometemplate.html', context) sometemplate.html <form method="post"> {% csrf_token %} {{ form|crispy }} {# disabled input data not submitted, so … -
How to check if BinaryField in Django is empty
I have a model which includes a BinaryField. E.g.: class AccountDetails(models.Model): logo = models.BinaryField() Now I want to check if that field is empty or not. Currently I use this: account_details = AccountDetails.object.get(id=1) if account_details.logo is b'': pass Is there a better way to do this than check against b''? -
How to choose between empty values or NULLs in a Django model with a UniqueConstraint based on two fields where one of them is optionnal?
I have a Django model with a Uniqueconstraint based on two fields values, one of them is mandatory the latter being optionnal. What is the best pratice here for the "optionnal" field (and why) to store "no value" between: No value = empty No value = NULL models.py class Foos(models.Model): name = models.CharField(max_length=50, blank=False, null=False) # Optionnal field alias = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = True db_table = 'foos' def __str__(self): constraints = [models.UniqueConstraint(fields=['name', 'alias'], name='unique_foo')] object_name = self.name return object_name Note that I need to insert a bunch of values from an external source file, value for 'alias' could be equals to None and data is not inserted through a form. -
Django want to not show models class
i have one models in Models are some object for example Aries , Taurus and etc . In object are some fields image , title and etc . i want to not show some fields (image, title) in Django admin site ,because this fields is not static it's default. it's is possible ? Model.py from django.db import models class SignsList(models.Model): Title = models.TextField(blank=True, null=True) Image = models.TextField(blank=True, null=True) Date = models.TextField(blank=True, null=True) Daily = models.TextField(blank=True, null=True) Love = models.TextField(blank=True, null=True) Finance = models.TextField(blank=True, null=True) Views.py def singCategory(request,slug,cat): sign = SignsList.objects.get(Title=slug) args = {'sign':sign, 'cat':cat, 'slug':slug,'daily':daily} return render(request,'base3.html',args) Html.file <div class="full_descr"> {%if cat == 'Daily' %} {{ sign.Daily }} {% elif cat == 'Love' %} {{ sign.Love }} {% elif cat == 'Finance' %} {{ sign.Finance }} {% endif %} </div> -
How can a delete request be redirected to a specific url in django rest framework?
Currently, I have made a "Like" model and have implemented "Like" and "Uike" by post and delete requests, respectively. So after implementing Like, I want to implement Unlike, and I know that in order to implement it, I have to select the pk of that Like object, map it to url, and then send a delete request to that url. However, this method requires both url called "/post_id/like/like_id" and "/post_id/like_id", which I do not do, but try to redirect from views to "/post_id/like/like_id" when a delete request is sent to url called "/post_id/like/like". How can I make logic to proceed with the code as I think? Here's my code. views.py class CreateReadLikeView (ModelViewSet) : serializer_class = LikeSerializer permission_classes = [IsAuthenticated] queryset = Like.objects.all() is_saved = False def get_queryset (self) : return super().get_queryset().filter(post=self.kwargs.get('post_id')) def perform_create (self, serializer) : postId = self.kwargs.get('post_id') post = Post.objects.get(pk=postId) try : like = self.queryset.get(post=post, liked_people=self.request.user) except Like.DoesNotExist : serializer.save(liked_people=self.request.user, post=post) self.is_saved = True def create (self, request, *args, **kwargs) : super().create(request, *args, **kwargs) if self.is_saved is True : self.is_saved = False return Response({'success': '해당 게시물을 좋아요 했습니다.'}, status=200) return Response({'message': ['이미 해당 게시물을 좋아요 하였습니다.']}, status=400) def list (self, request, *args, **kwargs) : postId = self.kwargs.get('post_id') … -
Django Search Page with Query Pagination
Hello i have implemented a simple search form and search view to show search result. Now i want to paginate them. But there is a problem with the page in the url. My search url looks like ../search?q=Bla Now if i try to add pagination like: ../search?q=Bla?page=2 (at least thats how i understand it would work) it takes the whole string after q= to my database filter. I took a look at how stackoverflow handles searching and pagination and found out using '&' here is the view code: def search(request): # get query search parameters page = request.GET.get('page', 1) query = request.GET.get('q', '') # query none or empty if query is None or query == '': return redirect('home') # query valid else: # icontains make sure to ignore character sensitivity post_list = Post.objects.filter(title__icontains=query) paginator = Paginator(post_list, 5) try: posts_l = paginator.page(page) except PageNotAnInteger: posts_l = paginator.page(1) except EmptyPage: posts_l = paginator.page(paginator.num_pages) return render(request, 'search.html', {'post_list': posts_l, 'query': query}) and here the HTML Snippet: {% if post_list.paginator.num_pages > 1 %} <div class="pagination"> <span class="step-links mb-5 mx-auto"> {% if post_list.has_previous %} <a class="mr-3" href="?page={{ post_list.previous_page_number }}&q={{ query }}">zurück</a> {% endif %} <span>Seite {{ post_list.number }} von {{ post_list.paginator.num_pages }}</span> {% if post_list.has_next … -
Customize request made by Django drf-yasg
I want to change the request drf-yasg generates and executes in the 'Try it out' editor. My API endpoint accepts a request with query params like query_params = { data: [1, 2], field: "string_value" } <url>?data[]=1&data[]=2&field=string_value but when I have annotated my endpoint with @swagger_auto_schema( method="GET", manual_parameters=[ Parameter("data", IN_QUERY, type=TYPE_ARRAY, items=Items(type=TYPE_STRING)), Parameter("field", IN_QUERY, type=TYPE_STRING), ], ) the 'Try it Out' editor generates the request as <url>?data=1,2&field=string_value Is there any way I can cganhe the way drf-yasg generates the request for a specific type? -
Getting "Incorrect type. Expected pk value, received str." error with Django REST Framework when trying to POST data
While I am aware that there are several topics with the same general problem, I haven't been able to fix my problem using the solutions recommended in them. Most likely due to my total inexperience with Django REST, but nonetheless I am desperate for an answer at this point. I'm creating an application using TypeScript + React in the front and SQLite + Django + DRF on the back. In practice I am creating a questionnaire in which an user goes through questions and answers them. In the end I am trying to send the users answers to my server to be saved in my database. To this end I have an AnswerSet model that contains an array of Answer objects. Here are the models: class AnswerSet(models.Model): questionnaire = models.ForeignKey( Questionnaire, related_name='answer_set', on_delete=models.SET_NULL, blank=True, null=True ) class Answer(models.Model): value = models.CharField(max_length=1000, null=True, blank=True) answerSet = models.ForeignKey( AnswerSet, related_name='answers', on_delete=models.SET_NULL, blank=True, null=True ) question = models.ForeignKey( Question, related_name='answer', on_delete=models.SET_NULL, blank=True, null=True ) As you can see the AnswerSet also has a relation to one Questionnaire and the Answers have a relation to the AnswerSet they belong to as well as the Question they belong to (that's what I'm trying to do … -
Building wheel for psycopg2 ... error pip3 install psycopg2?
When I'm running pip3 install -r requirements.txt then show me errors I show you bellow I'm using python version 3.8 PostgreSQL 13.0 (Ubuntu 13.0-1.pgdg20.04+1) see my requirement.txt files here certifi==2018.4.16 chardet==3.0.4 click==6.7 croniter==0.3.24 Django==2.0.5 django-rq==1.1.0 et-xmlfile==1.0.1 idna==2.7 jdcal==1.4 lxml==4.2.3 openpyxl==2.5.4 #pkg-resources==0.0.0 psycopg2==2.7.5 psycopg2-binary==2.8.5 python-dateutil==2.7.3 python-decouple==3.1 pytz==2018.5 redis==2.10.6 requests==2.19.1 rq==0.12.0 rq-scheduler==0.8.3 six==1.11.0 Unipath==1.1 urllib3==1.23 so show me this error in terminal I share with you complete command message that i typed already pip3 install -r requirements.txt ✔ 2186 17:28:42 Requirement already satisfied: certifi==2018.4.16 in /usr/local/lib/python3.8/dist-packages (from -r requirements.txt (line 1)) (2018.4.16) Requirement already satisfied: chardet==3.0.4 in /usr/lib/python3/dist-packages (from -r requirements.txt (line 2)) (3.0.4) Requirement already satisfied: click==6.7 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 3)) (6.7) Requirement already satisfied: croniter==0.3.24 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 4)) (0.3.24) Requirement already satisfied: Django==2.0.5 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 5)) (2.0.5) Requirement already satisfied: django-rq==1.1.0 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 6)) (1.1.0) Requirement already satisfied: et-xmlfile==1.0.1 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 7)) (1.0.1) Requirement already satisfied: idna==2.7 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 8)) (2.7) Requirement already satisfied: jdcal==1.4 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 9)) (1.4) Requirement already satisfied: lxml==4.2.3 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 10)) … -
A Value Error As "attempted relative import beyond top-level package"
My Project looks like this : https://imgur.com/B7fHzb4 how do I import the views.py in the pages app onto urls.py file of the trydjango app? when I do : import pages.views gives ValueError: attempted relative import beyond top-level package. when i do: from ..pages import views it says no module pages as hint. -
How are many-to-many relationship handled in Django?
I have a shirt which can contain multiple colors, and multiple colors which can have multiple shirts. Normally I would express it the following way: In django I have the many-to-many (https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/) Example: publications = models.ManyToManyField(Publication) -- Can I create the table "Item_colors" consisting of 2 columns (no "ID" primary key) and design the models according to my diagram using the composite key: class Item_colors(models.Model): class Meta: unique_together = (('cloth_item_id', 'color_id'),) cloth_item_id = models.ForeignKey(Cloth_item, on_delete=models.CASCADE) color_id = models.ForeignKey(Color, on_delete=models.CASCADE) How is the many-to-many relation handled in a DB context, and does it yield better performance? -
Should I use environmental variables or decouple to store sensitive data in Django?
What would be the best option to store sensitive information in a Django project? What’s the difference between Environmental variables or decouple and when should I use each? -
Defining get_queryset in a view, attribute error
I'm trying to write a custom get_queryset function because I want to access the user's email from 'request.user.email', and use that to form another query, that i want to display using my view cartv(generic.ListView). First time asking a question here, scoured the site but haven't found anything similar, but if you do find something just direct me there i''l delete this asap Environment: Request Method: GET Request URL: http://192.168.24.169:8000/products/cart/ Django Version: 3.1.2 Python Version: 3.6.9 Installed Applications: ['products.apps.ProductsConfig', 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/nirman/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/nirman/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/nirman/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/nirman/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/nirman/.local/lib/python3.6/site-packages/django/views/generic/list.py", line 142, in get self.object_list = self.get_queryset() File "/home/nirman/Desktop/login/products/views.py", line 91, in get_queryset self.user = request.user Exception Type: AttributeError at /products/cart/ Exception Value: 'cartv' object has no attribute 'user' views: class cartv(generic.ListView): model = cart context_object_name = 'cart_list' template_name='products/cartview.html' def get_queryset(request): qs = cart.objects.filter(user__email=request.user.email) #error points here if qs.exists(): c = qs[0] return c.items.all() else: return redirect('failure') -
Django Admin Panel Choices from Database
I have a model that has a IntegerField and in the admin. I want to add choices to the widget as "University" field. There is no problem if i add the universities in list as "uniList". But I do not know how can add these universities from UniversityList Class. I want to add new universities to UniversityList on admin panel and then i want to choose these added universities in Mainland2 admin page. In this case i recieved error massage as "in get raise self.model.MultipleObjectsReturned(mainpage.models.MultipleObjectsReturned: get() returned more than one UniversityList -- it returned 5!" Thank you for in advance... from django.db import models from django import forms from django_countries.fields import CountryField from django.core.exceptions import ValidationError class UniversityList(models.Model): name = models.CharField(max_length=50) class Mainland2(models.Model): unilist = [ (0, "---"), (1, "Uni 1"), (2,"Uni 2"), (3,"Uni 3"), ] graduatedList=[ (0, "Diğer"), (1, "Lise"), (2, "Lise (Öğrenci)"), (3, "Ön Lisans"), (4, "Ön Lisans (Öğrenci)"), (5, "Lisans"), (6, "Lisans (Öğrenci)"), (7, "Yüksek Lisans"), (8, "Yüksek Lisans (Öğrenci)"), (9, "Doktora"), (10, "Doktora (Öğrenci)") ] def validate_digit_length(idName): if not (idName.isdigit() and len(idName) == 11): raise ValidationError('%(idName)s en az 11 karakter olmalıdır', params={'idName': idName}, ) name = models.CharField(max_length=20, verbose_name="Ad") midName = models.CharField(max_length=20, verbose_name="Orta Ad", null=False, blank=True) surName … -
full join 3 django models with ORM
I have following models Django: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nickname = models.CharField(max_length=48, blank=True) bio = models.CharField(max_length=60, blank=True) about = models.TextField(blank=True) class SocialItem(models.Model): """ Renders available social network icons and placeholders on UI. Can only be added by admins """ name = models.CharField(max_length=64, unique=True) icon = models.ImageField(upload_to='social_icons', unique=True) placeholder = models.CharField(max_length=128, unique=True) class AccountSocialLink(models.Model): """Adds social network url to user's account""" account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='social') item = models.ForeignKey(SocialItem, on_delete=models.PROTECT) url = models.URLField() I have an account endpoint that returns the account data in this way: { "id": 5, "nickname": "Constantine", "bio": "Bio", "about": "" "social": [ { "id": 1, "item": 2, "url": "https://www.youtube.com/constantine" }, { "id": 2, "item": 3, "url": "https://www.instagram.com/constantine" }, { "id": 3, "item": 5, "url": "https://www.twitter.com/constantine" } ] } The SocialItem model is used for rendering on UI like in a form. For example, there are 5 social items available, but user has only 3 like above. But I do need to give the user options to fill out the remaining 2. What I need is an aggregation of these 3 models in one output so that the user can update their account by one request. The desired output is: { "id": 5, "nickname": "Constantine", … -
Django manage.py failing. module not found but actually installed in virtualenv
This is a very weird situation. I've been using django and venv for a while and during my last pull of code, when trying to run python manage.py collectstatic I ran into a "module not found" problem. however, this module is installed and if I try to reinstall it pip tells me I already have it. The strange thing is I'm seeing importlib using my system python path ("/usr/lib/python3.6...") which I think it should be my virtualenv path... If I run which python I get the correct venv python path... please help. I attach the error below: File "/home/ubuntu/venv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/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 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django-mailbox' -
How to use SQL database and noSQL database in the same django app?
Is there a good practice to use a SQL database like PostgresSQL with a No SQL database like MongoDB in the same Django app? I know I can define more databases in the settings.py, but how do I tell my models which database to use? Is it a good idea after all or should I use one database in a given Django app? -
Enable to login into the application in Django tests
I am writing the test cases to my application. Please find below code snippet of tests.py class TestGetDetailsPositive(SimpleTestCase): def setUp(self): self.credentials = { 'username': '****', 'password': '****' } @responses.activate def test_get_details(self): self.client.login(username='****', password='****') response = self.client.get('/accounts/selectdetails/') self.assertContains(response, 'National', status_code=200) self.assertTemplateUsed(response, 'accounts/select-details.html') def test_view_url_exists_at_desired_location(self): url = reverse('selectdetails') self.assertEquals(resolve(url).func.view_class, SelectDetails) I am getting below error as follows. AssertionError: Database queries to 'default' are not allowed in SimpleTestCase subclasses. Either subclass TestCase or TransactionTestCase to ensure proper test isolation or add 'default' to accounts.tests.tests.TestGetBanksPositive.databases to silence this failure. Database configuration looks like below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '****', 'USER': '****', 'PASSWORD': '****', 'HOST': '****', 'PORT': '****', } } Where I am doing wrong? -
create foreignkey object w/ extra actions on post
I have a financials serializer and nested serializers for balancesheets, income statements and cashsflows statements which have their own serializers for each respective componennt I am trying to post through an extra action on the Stock object to create a Financials instance, but receive the error below. what am I doing wrong ? BalanceSheet Serializer 309 class BalanceSheetSerializer(WritableNestedModelSerializer): 310 assets = AssetsSerializer() 311 liab_and_stock_equity = LiabAndStockEquitySerializer() 312 313 class Meta: 314 model = BalanceSheet 315 316 fields = [ 317 # "ticker", 318 "periodicity", 319 "assets", 320 "liab_and_stock_equity", 321 "end_date", 322 "start_date", 323 ] Stock Extra Action 25 @action(detail=True, methods=["post", "get"]) 26 def financials(self, request, ticker=None): 27 if request.method == "GET": 28 stock = self.get_object() 29 financials = stock.get_financials() 30 financials = FinancialsSerializer(financials) 31 return Response(financials.data) 32 if request.method == "POST": 33 stock = self.get_object() 34 serializer = FinancialsSerializer(request.data) 35 Financials.objects.create(serializer.data) 36 Financials.save() ERROR web_1 | AttributeError: Got AttributeError when attempting to get a value for field `assets` on serializer `BalanceSheetSerializer`. web_1 | The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. web_1 | Original exception text was: 'str' object has no attribute 'assets'. web_1 | [14/Oct/2020 11:23:26] "POST /stocks/aapl/financials/ HTTP/1.1" … -
'Select a valid choice' error in Dependent/Chained Dropdown List even if its valid
i'm trying to implement this tutorial:https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html on how to Implement Dependent/Chained Dropdown List with Django he said that we will get an error about select a valid choice i implemented the fix that he provided but the error still there i have been verifying my code from yesterday and it looks fine and the same as the tutorial here is my view class GlobalLessonView(CreateView): model = Lesson form_class = GlobalLessonForm success_url = reverse_lazy('globalform') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(request=self.request) return kwargs forms.py from django.conf import settings db_name = settings.DATABASES['default']['NAME'] class GlobalLessonForm(forms.ModelForm): class Meta: model = Lesson fields = '__all__' def __init__(self, request, *args, **kwargs): school_id = request.session['school_id'] super().__init__(*args, **kwargs) self.fields['subject'].queryset = Subject.objects.none() #change to .all() to see list of all subjects self.fields['level'].queryset = Level.objects.filter(school__id= school_id) if 'level' in self.data: try: level_id = int(self.data.get('level')) self.fields['subject'].queryset = Subject.objects.extra(where=[db_name+'.scolarité_subject.id in( select subject_id from '+db_name+'.scolarité_levelsubject where level_id='+level_id+')']) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subject'].queryset = self.instance.level.subject_set lesson_form.html <form method="post" id="globallessonform" data-subjects-url="{% url 'ajax_load_subjects' %}" novalidate> {% csrf_token %} <table> {{ form.as_table}} </table> <button type="submit">Save</button> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_level").change(function () { var url = $("#globallessonform").attr("data-subjects-url"); // get the url of the … -
"Cannot import ASGI_APPLICATION module %r" % path channels problem
I got this error: ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) Here is my routing.py: from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack from django.urls import path from messanger.contacts.consumers import ChatConsumer application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ path('user-notification', ChatConsumer) ] ) ) ) }) When i remove this line of code, runserver work: from messanger.contacts.consumers import ChatConsumer But i don't understand what's wrong with my consumers file in contacts app: from channels.consumer import AsyncConsumer class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): await self.send({ "type": "websocket.send", "text": event["text"], }) -
Django compilemessages doesn't work with some uft-8 characters
I'm setting up internationalization in a Django project using i18n. In /landing/locale/es/LC_MESSAGES, I created a po file with phrases and started python manage.py compilemessages, it worked fine, but when starting the server I get this error: File ".../venv/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 10, in <module> from django.contrib.auth.models import User File "...venv/lib/python3.6/site-packages/django/contrib/auth/models.py", line 33, in <module> class Permission(models.Model): File ".../venv/lib/python3.6/site-packages/django/db/models/base.py", line 111, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. This occurs only in Spanish, or with the '`' symbol. If you delete the .mo translation file, the server starts normally. I think the problem is the encoding. Is there any way to set UTF-8 encoding for translation files? I use UTF-8 encoding for .po files