Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels can't "socket.send" when trying to constantly send data to client from server
I am trying to create a game on django using channels. For that I need server to send data to client after certain amount of time. I managed to achieve it but now I can not socket.send anything back to the server. I am having hard time trying to figure out why is that. What I try to achieve is having server constantly sending the data and receive data from the client to save it to database. Second part being where I am stuck currently. consumers.py from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from channels.db import database_sync_to_async from django.utils.crypto import get_random_string from .models import Model import asyncio import json import random from hashlib import pbkdf2_hmac @database_sync_to_async def get_round(): a = Model.objects.last() return a.round_number class Game(AsyncWebsocketConsumer): async def connect(self): self.connected = True self.room_name = 'gameName' self.room_group_name = 'game_room' await self.channel_layer.group_add( self.room_group_name, self.room_name ) await self.accept() while self.connected: await asyncio.sleep(5) server_seed = get_random_string(length=64) public_seed = random.randint(0, 999999) round = await get_round() hash = pbkdf2_hmac('sha256', bytes(server_seed, 'utf-8'), bytes(public_seed), round) result = int(hash[0:8].hex(), 16) % 15 await self.send(text_data = json.dumps({ 'round_result': result })) async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) self.connected = False async def receive(self, text_data): data = json.loads(text_data) print(data) # … -
Django Test: Incorrect type. Expected pk value, received str
I have a simple model having a foreign key: class Job(models.Model): resource = models.ForeignKey(Resource, on_delete=models.RESTRICT, related_name="resource_jobs") required_resource = models.FloatField(default=0) Here is the viewset: class JobViewSet(ModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer I am writing a test to create this Job object like this. self.detail_url: str = "factory:jobs-detail" self.resource = Resource.objects.create(**self.resource_data) self.job_data = { "resource": self.resource, "required_resource": 20, } def test_create(self) -> None: response: Response = self.client.post( self.list_url, data=self.job_data ) print(response.data) self.assertEqual(response.status_code, 201) Upon running the test I get an error: {'resource': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]} How do I pass this object in this dictionary. Thank you for any help. -
Django the JSON object must be str, bytes or bytearray, not NoneType
I am creating an ecommerce website with the help of Django and I am using Local Storage as my cart and also using some jquery and ajax to post my data on server side but when I am sending my local storage to the server Side I am getting the error like this, See the error My cart.html is like this from where I am sending the data to checkout, <form action="/checkout" method="post" > {% csrf_token %} <button class="button-78" role="button">Proceed to buy</button> </form> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <script> $('.plus').click(function(e){ console.log("hello"); e.preventDefault(); cartt=JSON.parse(localStorage.getItem('cart')); console.log(cartt) var idstr=this.id.toString(); cartt[idstr]=cartt[idstr]+1; localStorage.setItem('cart',JSON.stringify(cartt)) $.ajax({ type:"POST", url:"http://127.0.0.1:8000/cart", data:{ prodd:localStorage.getItem('cart'), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ location.href = "/cart" } }); }); $('.minus').click(function(e){ e.preventDefault(); cartt=JSON.parse(localStorage.getItem('cart')); var idstr=this.id.toString(); cartt[idstr]=cartt[idstr]-1; localStorage.setItem('cart',JSON.stringify(cartt)) $.ajax({ type:"POST", url:"http://127.0.0.1:8000/cart", data:{ prodd:localStorage.getItem('cart'), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ location.href = "/cart" } }); }); $('.button-42').click(function(e){ e.preventDefault(); cartt=JSON.parse(localStorage.getItem('cart')); var idstr=this.id.toString(); delete cartt[idstr]; localStorage.setItem('cart',JSON.stringify(cartt)) $.ajax({ type:"POST", url:"http://127.0.0.1:8000/cart", data:{ prodd:localStorage.getItem('cart'), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ location.href = "/cart" } }); }); $('.button-78').click(function(e){ $.ajax({ type:"POST", url:"http://127.0.0.1:8000/cart", data:{ prodd:JSON.stringify(localStorage.getItem('cart')), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ location.href = "/checkout" } }); }); </script> And this is my views.py file, def checkout(request): if request.method == "POST": global context dict=json.loads(request.POST.get('prodd')) ldict=list(map(int,dict.keys())) objects=product.objects.filter(pk__in=ldict) print(dict) context={'object':objects,'dict':dict} return render(request,'checkout.html',context) I tried multiple methods like json.loads() and json.dump() and both … -
QuillField not showing in django admin
Quill editor v0.1.40 works fine on my local computer, but when in production, QuillFileds are invisible on admin panel – only labels appear: When inspecting the admin page on Chrome, I see such errors on the console: GET https://my site.com/static/django_quill/django_quill.css net::ERR_ABORTED 404 (Not Found) GET https://my site.com/static/django_quill/django_quill.js net::ERR_ABORTED 404 (Not Found) Uncaught ReferenceError: QuillWrapper is not defined at (index):261:27 at (index):263:11 django_quill.css and django_quill.js fail to load. I can't figure out why it works on my local project which has the same setup, except that on local I use python 3.9/Django 4.0.1 while in production, it's v3.8/4.0.2. Another difference is that, in production, django_quill folder is under myenv/lib/python3.8/site-packages/ directory. On my computer, there is no django_quill folder under myenv/lib/python3.9/site-packages/. In fact, there is no such folder anywhere on my drive, nor the related django_quill.css or django_quill.js files. I have no problem while migrating from old TextField's, or viewing the content on the templates. Any suggestion or feedback will be welcomed and greatly appreciated. Thank you. -
How to get CST Timezone for Django DateTimefield column
I want to update existing DB data and it should update the "DateTimeStamp" field in database with current time (Central time). DB Table configuration : DateTimeStamp field is having default value as CURRENT_TIMESTAMP. Django setting.py configuration : TIME_ZONE = 'US/Central' Django models.py configuration : DateTimeStamp = models.DateTimeField() Django views.py : dt = datetime.now().astimezone(pytz.timezone('US/Central')) when I check "dt", it shows date in Central only, but when I update the table, it is not reflecting in Central time table.objects.filter(col1=col1).update(col2=col2,col3=col3,DateTimeStamp=dt) dt = 2022-03-14 07:53:19 database field got updated with 2022-03-14 23:23:19 Can someone please assist me what's going wrong here. -
Django tried these URL patterns, in this order
from django.contrib import admin from django.urls import path from App import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('qui_sommes_nous/', views.qui_sommes_nous, name='qui_sommes_nous'), path('equipe/', views.equipe, name='equipe'), path('galerie/', views.galerie, name='galerie'), path('avendre/', views.avendre, name='avendre'), path('alouer/', views.alouer, name='alouer'), path('realisation/', views.realisation, name='realisation'), path('contact/', views.contact, name='contact'), path('details_des_appartement/', views.details_des_appartement, name='details_des_appartement'), ] please help me solve this problem, when I click on a link it always comes out not found while on the home page it goes well -
Django server & Gunicorn - 502 Bad Gateway
I have running two Django servers in my raspberry pi and serve them with Gunicorn and Nginx. One of them is running fine, but the other one is giving me a 502 Bad Gateway issue. I would appreciate if someone could help me to debug this issue. Here are the logs when I run sudo journalctl -u portfolio: pi@raspberrypi:/etc/systemd/system $ sudo journalctl -u portfolio -- Logs begin at Mon 2022-03-14 11:41:15 GMT, end at Mon 2022-03-14 12:32:28 GMT. -- Mar 14 12:07:10 raspberrypi systemd[1]: Started gunicorn daemon. Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4623] [INFO] Starting gunicorn 20.1.0 Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4623] [INFO] Listening at: unix:/run/portfolio.sock (4623) Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4623] [INFO] Using worker: sync Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4626] [INFO] Booting worker with pid: 4626 Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4630] [INFO] Booting worker with pid: 4630 Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4631] [INFO] Booting worker with pid: 4631 Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4626] [ERROR] Exception in worker process Mar 14 12:07:11 raspberrypi gunicorn[4623]: Traceback (most recent call last): Mar 14 12:07:11 raspberrypi … -
Error when deleting AbstractBaseUser user instance
The user model class is defined as follows: enter image description here The settings are configured as follows: enter image description here The views code is as follows: enter image description here I use the following command to generate sql: python3 manage.py makemigrations rbac python3 manage.py sqlmigrate rbac 0001 Then I generate the table in the database: enter image description here Then I am using Delete to call the API: http://127.0.0.1:8000/rbac/user/21 So django raise an exception: django.db.utils.ProgrammingError: (1146, "Table 'mds.django_admin_log' doesn't exist") I don't know why this is happening, I hope you can help me solve this problem -
Filter object where queried number is within a range
Lets say I have a model with a range_low and a range_high, and want to find that instance if a number falls within that range. ID Prefix Low High 3 GH 1 300 4 GH 450 700 If I were to search GH250 then I should get back the instance with ID of 3 in this example. I considered using range() to get a list of all the numbers within a range, but this would require me to query every instance with a prefix of GH first & then build a range for each & every one of them to find which one overlaps. To limit this, I do at least have the low & high available, so I could query all instance with a prefix of GH where high is under 250 and that somewhat scales the results down, but this is still a pretty big query. This is my current query which just looks for the prefix being exact & the low or high containing the number. prefix = search[:2] number = search[2:] queryset = queryset.filter( Q(Q(low__icontains=number) | Q(high__icontains=number)) & Q(prefix__icontains=prefix) ) What tools might be available to me to efficiently filter results to get the block that … -
Saving Form Data Based On The Input Label
I am building a form that utilizes dynamic question/answers with Question and Answer models so that new questions can be created by non-devs. Here are my current models (missing some unnecessary information for this question) models.py class Question(models.Model): question = TextField() is_active = BooleanField(default=False) def __str__(self): return self.question class Answer(models.Model): answer = TextField() question = ForeignKey(Question, on_delete=CASCADE, default=None) In the view I create the form like this. views.py def survey(request): custom_questions = Question.objects.filter(is_active=True) if request.method == "POST": formset = [] for q in custom_questions: formset.append(AnswerForm(request.POST)) ### Here is where I would like to process this data else: formset = [] for q in custom_questions: answer_form = AnswerForm() answer_form.fields['answer'].label = q.question formset.append(answer_form) return render(request, 'template.html', {'formset': formset}) How would I process this data based on the question that was asked? Here is what I tried just to see what information was being processed in the form: for q in custom_questions: answer_form = AnswerForm(request.POST) if answer_form.is_valid(): print(answer_form.cleaned_data['answer'] However, when it printed the data it only printed the same answer multiple times. I would like to: Use the label that was defined in the GET request to Question.objects.get(question=) in order to set the foreignkey field to the Answer model. Get the correct data … -
How to order queryset by foreign key field without duplicates?
I have Django models Ticket and Confirmations: class Ticket(Model): name = models.TextField() class Confirmation(Model): ticket = models.ForeignKey( "ticket.Ticket", related_name="confirmations", ) expire_date = models.DateTimeField() I want to order them by expire date of confirmations, and it works but if ticket has more than one confirmation then it will be returned in queryset multiple times: tickets = Ticket.objects.order_by('confirmations__expire_date') for ticket in tickets: print(f"id: {ticket.id}") > id: 1 id: 2 id: 1 id: 3 id: 4 id: 1 I don't want to return duplicates. I just need the first element and get rid of the rest. I need to take into account the latest confirmation in response. -
how to view/edit data after submitting form through template
How do I have the data visible/editable on the form after submitting the form and coming back to this URL "checkout/" again, so the user can edit the address again and submit it and the data gets updated in the database, I can't seem to find a way to do this I would really appreciate if you can help, Thx! views.py def checkout(request): if request.method == 'POST': form = ShippingForm(request.POST) if form.is_valid(): new_shipping = form.save(commit=False) new_shipping.customer = customer new_shipping.order = order new_shipping.save() return redirect('store:checkout_shipping') else: form = ShippingForm() else: form = ShippingForm() models.py class ShippingForm(forms.ModelForm): address_one = forms.CharField(max_length=200) address_two = forms.CharField(max_length=200) urls.py path('checkout', views.checkout, name="checkout"), -
Django admin Unknown field with underscore
class UserControlAdmin(ExportActionMixin, admin.ModelAdmin): resource_class = UserResource list_display = ('get_branch', 'get_segment', 'get_team', 'get_position', 'user', 'get_gender') list_filter = ('team_control__company_group__branch', 'team_control__company_group__segment', 'team_control__team') fields = ('team_control__company_group__branch', 'team_control__company_group__segment', 'team_control__team', 'user',) I'm trying to add fields with underscore separated field names and I got error: Unknown field(s). How can I fixed that? -
`Cannot query "<class 'models.declaration.gentmodel.Beast'> Must be "ContentType" instance.`
I am using Django3. I have model class Option and it has members like these. class Option(models.Model): item_type = m.ForeignKey( ContentType, related_name="item_%(class)s_set", on_delete=m.CASCADE,null=True) item_id = m.PositiveBigIntegerField(null=True) item = GenericForeignKey('item_type', 'item_id') This can accept any class instance in item However I have trouble when filtering this model. For example in this case, I have rows which have Beast class as item so I try to filter by Beast and id def get_queryset(self): queryset = super().get_queryset() queryset = queryset.filter(item_type=Beast,item_id=1) This error comes Cannot query "<class 'models.declaration.gentmodel.Beast'>": Must be "ContentType" instance. How can I solve this? Any help appreciated. thank you. -
Multi container application
I have to create a dockerized web application. In my idea, I would like to create 3 containers: A Python Django container that can query a container that contains an R-script. An R container A Postgres database container. My question is this: how can I query the R container from the Django container? Thank you for your support. -
Set Unique Constrait only under the direct parents (Django MPTT)
I created "Category" model with Django MPTT: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") But, with this "Category" model, I could add the duplicated data "3F" and "4F" under "Building B"(Direct Parent) as shown below: USA New York Building A 3F 4F Building B 3F // Here 3F // Here 4F // Here 4F // Here So I added "unique=True" to "name" field in the model "Category": from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): // Here name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") But with this "Category" model, I couldn't add the data "3F" and "4F" under "Building B" anymore because "3F" and "4F" already exist under "Building A" in "Category". I found adding "unique=True" to "name" field in "Category" model sets Unique Constrait in whole "Category" model about "name" field. So if there are the same "name" values such as "F3" and "F4" anywhere in "Category", we cannot add the same "name" values such as "F3" and "F4" anywhere in "Category". In short, if "3F" and "4F" already exist anywhere in "Category", we cannot add "3F" and … -
SMTPConnectError (421, b'Server busy, too many connections')SMTPConnectError (421, b'Server busy, too many connections')
I have checked every single solution on other questions but they are of zero help,using bulk email services also require having a domain name already meanwhile my django website is still in development but i also want to send actual mails not mail on django console.I have allowed access to less secure apps,used app password and re capcha all to no avail,i even changed my email host to yahoo mail still the same thing,the fact that email verification is a core part of authentication and there's little to no support or help is very annoying,already looked through all youtube videos it worked for them but non worked for me my settings file: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_USE_SSL = False the error mesage: SMTPConnectError (421, b'Server busy, too many connections') -
Make the filter from class method or get the queryset from class method
What I want to do finally is like this using is_special MyObjectForm = forms.ModelChoiceField( queryset=MyObj.objects.filter(is_special=False),required=False) However is_special is not the member of the model but method. class MyObj(models.Model): key = m.CharField(max_length=20,null=False,unique=False) class Meta: db_table = 'myobj' def is_special(self): return SpecialMember.is_key_exist(self.key) So, I come to two ideas. Using method as filter variable Geting the queryset by object method. Is it possible? -
I get this error when i want to run my django app :
ImportError: cannot import name 'froms' from 'django' -
AWS ElasticBeanstalk instance protection for leader_only node
I have a django application running on EBS. My application runs celery beat on 1 of the instances by using the ebextension container command: 03_celery_tasks: command: "cat .ebextensions/files/celery_configuration.txt > /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh && chmod 744 /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true 04_celery_tasks_run: command: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true During auto-scaling/or routine cleanup EBS might remove the leader_only node which cause celery scheduled task to stop running. I know there is the ability to protect instances during scale-in/out moments However I am not sure how to enable instance protection for my leader node specifically (the one running celery beat) -
django graphene pytest mock query not working
I have a simple test case like: @patch('helpers.queries.Query.resolve_profile_lookup') def test_profile_lookup(mock_resolve_profile_lookup, client, client_query): mock_resolve_profile_lookup.return_value = [ {"name": "First name"}, {"address": "First address"}, ] response = client_query( """ query profileLookup($search: String!){ profileLookup(search: $search) { name address } } """, variables={"search": "jack"}, ) content = json.loads(response.content) assert mock_resolve_profile_lookup.called Here, I want to mock the resolve_profile_lookup query that I have in Query. From my understanding the function I patch is mocked while running test case, but its not working here. Anything that I am missing here ? -
how do increment all column values in db table after certain integer values in that column (django)?
Suppose I have created "X" database table in Django which has column id(autofiled), name(charfield) and occurrence(integerfield), now suppose 3 rows are already available in it id name occurrence 1 ABC 1 2 BCD 2 3 CDE 3 I want to get data based on (ordering) the occurance number, I am facing a problem that, I want to add a row with an occurrence number 2 (already present), and all the rows with occurrence numbers greater than 2 update and increment automatically. (Basically, It is a inserting data on index number, where value is name and index is occurrence ignore id). For Example- id name occurrence 1 ABC 1 2 BCD 3 3 CDE 4 4 XYZ 2 Thanks in advance. -
Can you import the BUILD_ID of a cloud build into your Cloud Run python container?
We want to use django's redis cache feature that allows us to specify version numbers which will effectively invalidate cache values of a previous build (before the code changed). GCP's Cloud build has a default $BUILD_ID value available to the build yaml files, but is there a way for a deployed container to access this BUILD_ID value? If we could, we could us it (or a modulo value of it) to be our unique cache version. See https://cloud.google.com/build/docs/configuring-builds/substitute-variable-values for GCP build variables See https://docs.djangoproject.com/en/4.0/topics/cache/#cache-arguments for django cache documentation -
Override response in a Class Based View Django
I have a view that I'd also like to export data from as a CSV also with search parameters & filters. I want the exported data to be exactly the same queryset as this view, so what I have currently is inefficient. Note: The code below may look pretty silly & some sections pointless, but I'm just being careful with my NDA so omitted down to an anonymous reproduction. class ModelListView(LoginRequiredMixin, ListView): model = Model template_name = 'list.html' paginate_by = 15 def get_queryset(self): if not self.request.user.is_staff: queryset = Model.objects.filter() queryset = Model.objects.filter() search = self.request.GET.get("search", None) if search: queryset = queryset.filter( Q(type__icontains=search) | Q(status__icontains=search) | Q(prefix__icontains=search) | Q(created__icontains=search) | Q(message__icontains=search) ) # Save most recent queryset to session for # use with exporting & retrieval on other pages. self.request.session["queryset"] = serializers.serialize('json', queryset) return queryset Currently towards the end there I save the queryset to request.session & then use it in a separate ExportView, which works, but comes with a can of worms. I'm wondering where I might override the response for a Class-Based View so I could instead set a query param like ?format=csv & have the same view return a CSV response instead. I'm sure this is possible, but … -
Cannot resolve keyword annotated field django
this is my model class ExchangeReportTime(models.Model): creator = models.ForeignKey('accounts.Account', on_delete=models.CASCADE, null=True, verbose_name=_('Creator')) create_time = models.DateTimeField(default=timezone.now) exchange = models.ForeignKey(BorseExchange, on_delete=models.SET_NULL, null=True, related_name='report_times') actual_fiscal_month = models.CharField(max_length=255, null=True, blank=True) fiscal_month = models.CharField(max_length=5, null=True, blank=True) fiscal_year = models.CharField(max_length=255, null=True, blank=True) is_fiscal_year_changed = models.BooleanField(null=True, blank=True) period_ending_date = models.CharField(max_length=15, null=True, blank=True) statement_key = models.IntegerField(null=True, blank=True) statement_type = models.CharField(max_length=50, null=True, blank=True) ... fiscal_month and fiscal_year are string so i change types and query as below exchange = BorseExchange.objects.get(tse_code=exchange_number) last_12_season = exchange.report_times.filter( statement_type='InterimIncomeStatement', period_type='seasonally' ).annotate( fiscal_month_number=Cast('fiscal_month',IntegerField()), fiscal_year_number=Cast('fiscal_year',IntegerField()), ).order_by( '-fiscal_year_number', '-fiscal_month_number' ).distinct( 'fiscal_month_number', 'fiscal_year_number' )[:records_count] but i give error: django.core.exceptions.FieldError: Cannot resolve keyword 'fiscal_month_number' into field. Choices are: actual_fiscal_month, attachment_url, auditing, company_key, create_time, creator, creator_id, currency, exchange, exchange_id, fiscal_month, fiscal_year, html_url, id, is_empty, is_fiscal_year_changed, period_ending_date, period_type, publish_date, publish_time, report_items, scenario, statement_key, statement_type where is the problem? python3.6 and django 2.2.*