Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Override the automatic generated view_name in Django Rest Framework
I'm creating a Restful API with Django REST Framework. What I have is a project with two different apps. One app is called project/catalog and one is called project/environment. Both of the apps have a model called Device and their own url.py file, which will be included in the project/url.py file. The urls from the apps are included with a namespace in project/url.py: # project/url.py urlpatterns = [ path(r'api/', include(('environment.urls', 'environment'))), path(r'api/', include(('catalog.urls', 'catalog'))) ] The basename for the urls are automatic generated because in the viewSet I have a attribute queryset My question is: Is it possible to override the automatic view_name generation to use the pattern with a namespace? What it says in the documentation is that the view_name is generated like this (model_name)-detail for example. What I want is that the view_name will be generated like this (app_name):(model_name)-detail I can use the namespace when I create the HyperlinkedIdentityField by my self and add the view_name attribute, like below: # project/catalog/serializer.py class DeviceSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='catalog:device-detail') class Meta: model = models.Device fields = [ 'url', ... # project/environment/serializer.py class DeviceSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='environment:device-detail') class Meta: model = models.Device fields = [ 'url', ... But once I remove the … -
How to explicitly set default language in wagtail?
I have a website which has 2 languages. Everything works perfect but i just need to set the default language for every user. Users can change the language if they want but i want to serve the website in default language. I've made some search and found that maybe i can do it with django.views.i18n.set_language() but couldn't find how. Any help would be great. Thanks. -
Heroku: Django backend is not working, getting error GET http://localhost:8000/api/todos/ net::ERR_CONNECTION_REFUSED
I actually created a fullstack todo app with django as backend and react as frontend. The frontend is working perfectly fine, you can that here -> https://ym-todo-application.herokuapp.com. But somehow my application cannot connect to the django backend, also on inspecting on browser i saw this error -> GET http://localhost:8000/api/todos/ net::ERR_CONNECTION_REFUSED. Containing lot of files and code so i pushed them on bitbucket to make it easier to debug. here's the link https://bitbucket.org/Yash-Marmat/todo-app-fullstack/src/master/. Thanks in advance. -
Get the first 3 records from database with django
I have a problem. I want to get with a django query the first 3 records from my database and I really don't have any idea how can I do that. I didn't find nothing for this. -
Help_text under input description, Django forms
I have: street = models.CharField('Street', max_length=100, blank=True, help_text="(optional field)") Help_text displays under input, but i want help_text "(optional field)" under label "Street". Maybe I should do it another way? -
How To make fields of different model unique in django
I have a url field in 3 different models is there any pre defined way in rest framework or django so that they will be unique?? or i have to write the whole unique thing logic manually?? class A(models.Model): url = models.CharField() class B(models.Model): url = models.CharField() class C(models.Model): url = models.CharField() -
How can I prefetch nested data in Django?
I have the following models: class Contract: products = models.ManyToManyField( to="Product", through="ContractProductThroughModel", related_name="contracts" ) class Product: garage = models.ForeignKey( to="Garage", on_delete=models.CASCADE ) class Garage: ... Is there a way to prefetch all contracts for all garages? I tried it like this answer: garages = Garage.objects.all().prefetch_related("product_set").prefetch_related(Prefetch("product_set__contracts", to_attr="cached_contracts")) but I want to access the cached contracts for each garage object like this garage.cached_contracts. Is that possible? -
Getting "Module 'myproject' has no attribute 'celery'" when executing Celery in top root
Small Django & Celery question here. I'm trying to execute celery in the root level of my Django project. I have the following structure: ./myproject// dir |-- ./myproject/db.sqlite3 // dir |-- ./myproject/manage.py |-- ./myproject/myproject// dir |-- ./myproject/tasks.py `-- ./myproject/users // dir In my ./management/tasks.py file I have: app = Celery('myproject', broker=settings.CELERY_BROKER) I run from root level: python3 -m celery -A myproject worker --loglevel=INFO But get: Unable to load celery application. Module 'myproject' has no attribute 'celery' -
How to get group of currently logged in user
How to get group of currently logged in user? I have basic users from django.contrib.auth grouped into two groups: student, teacher. I want to show the group of currently logged in user in following template: {% block content %} <h2> Witaj {{ user.first_name }} {{ user.last_name }} ! </h2> {% endblock %} This is my views.py file: def login(request): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) else: return index(request) def index(request): return render(request, 'index.html') def logout(request): logout(request) -
HOW CAN I FILTER USERS IN DJANGO MANY TO MANY FIELDS?
HERE IS MY MODEL: class Course(models.Model): title = models.CharField(max_length=100) students = models.ManyToManyField(User,related_name="students") crated_at = models.DateField(auto_created=True) How can I filter all the users in a course? -
Django: Celery worker in production, Ubuntu 18+
I'm learning Celery and I'd like to ask: Which is the absolute simplest way to get Celery to automatically run when Django starts in Ubuntu?. Now I manually start celery -A {prj name} worker -l INFO via the terminal. Can I make any type of configuration so Celery catches the changes in tasks.py code without the need to restart Celery? Now I ctrl+c and type celery -A {prj name} worker -l INFO every time I change something in the tasks.py code. I can foresee a problem in such approach in production if I can get Celery start automatically ==> need to restart Ubuntu instead?. (setup: VPS, Django, Ubuntu 18.10 (no docker), no external resources, using Redis (that starts automatically) I am aware it is a similar question to Django-Celery in production and How to ... but still it is a bit unclear as it refers to amazon and also using shell scripts, crontabs. It seems a bit peculiar that these things wouldn't work out of the box. I give benefit to the doubt that I have misunderstood the setup of Celery. -
How do I change the local path of a language in Django?
Django by default has the English local path defined as /en, If possible I want the language to be 'en' but the url to be myurl.com/us, how would you recommend me to make this change? I have a web set up with 3 languages (['es', 'en', 'it']) in Angular that works with the Django server. The structure is the following: -apps --webapp ---templates ----webapp -----en (inside index.html) -----es (inside index.html) -----it (inside index.html) -conf --settings.py -middleware --locale.py conf.settings.py have this language configuration LANGUAGES = ( ('es', _('Spanish')), ('it', _('Italian')), ('en', _('English')), ) LANGUAGE_CODE = 'es' LANGUAGE_CODES = [language[0] for language in LANGUAGES] Additionally I have configured a middleware to recognize the user's location and place the corresponding language code in the URL from django.conf import settings from .utils.geolocation import get_language_by_ip cookie_name = settings.LANGUAGE_COOKIE_NAME class LocalizationMiddleware(object): def get_language_cookie(self, request): return request.COOKIES.get(cookie_name) def set_language_cookie(self, request, value): request.COOKIES[cookie_name] = value def get_i18n_url_language(self, request): url = request.path.split('/') if len(url) > 1 and len(url[1].split('-')[0]) == 2: return url[1] return None def process_request(self, request): language = self.get_i18n_url_language(request) if language is not None and language not in settings.LANGUAGE_CODES: return if language is None: language = self.get_language_cookie(request) if language is None: language = get_language_by_ip(request) if language is None: … -
Django skips broken template's pats
I'm using Django==1.11.17, python 3.5 When template has error, for example invalid tag, locally django throws exception and returns response with 500 status code. But I found that in production django do not throws exceptions, it just skip broken template part. This makes debug a little bit tricky. Could someone explain why django skips broken templates? Is it possible make production environment throw exceptions instead of ignoring errors? -
Problem in adding releated field to serializer
I have two classes which are Land and UTMPoint: class UTMPoint(models.Model): x = models.CharField(max_length=20) y = models.CharField(max_length=20) z = models.CharField(max_length=20) land = models.ForeignKey('Land', on_delete=models.DO_NOTHING) And their serializers are: class UTMPointsSerializer(serializers.ModelSerializer): class Meta: model = UTMPoint fields = ('id', 'x', 'y', 'z', 'land',) read_only_fields = ('id',) class LandSerializer(serializers.ModelSerializer): user = UserSerializer() utm_points = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Land fields = ('id', 'user', 'activity_field','activity_location', 'area', 'part', 'location','verification_code', 'verified', 'description', 'approved', 'receipt_bank_name', 'receipt_serial', 'receipt_date', 'receipt_amount','utm_points',) read_only_fields = ('id', 'approved',) def create(self, validated_data): user = validated_data.pop('user') user = User.objects.create(**user) user.save() land = Land.objects.create(user=user,**validated_data) land.save() return land As you see Land has utm_points releated field but when I run this test: def test_create_land(self): """test creating land""" payload = { 'activity_field': 'farming', 'user': {'national_code': '12333', 'password': 'passW@rd'}, 'activity_location': 'Kermanshah', 'area': 'sw', 'part': 'sp', 'location': 'the old address', 'verification_code': '1', 'verified': '0', 'description': 'sb is calling for it', 'approved': True, 'receipt_bank_name': 'meili', 'receipt_serial': '12312', 'receipt_amount': '10000', } res = self.client.post(LAND_URL, payload, format='json') self.assertEqual(res.status_code, status.HTTP_201_CREATED) I get this error AttributeError: 'Land' object has no attribute 'utm_points' I have no idea why this error is throwing Land has properly the related field utm_points so why it happes? -
safe, force_escape, etc. What is the exact django template escaping algorithm?
So in the documentation of Django 3.1 template builtins, I've found the following escape-related built-in filters: force_escape escape safe safeseq As well as the following escape-realted tag(s): autoescape (on|off) safeseq especially catches my attention and makes me wonder what exactly the django template escaping algorithm is; among others, how does it interact with custom filters. Indeed, the documentation gives this example: {{ some_list|safeseq|join:", " }} With the following explanation: You couldn’t use the safe filter directly in this case, as it would first convert the variable into a string, rather than working with the individual elements of the sequence. What I'm looking for is: A graphic (draw.io?plantuml?dia?) which explains the steps the data goes through in the simplest case: {{ data }}, depending on the Python type of the variable. A similar graphic which explains more complex cases such as {{ data | myfilterfunction }}, again, taking into account the Python type of the input variable and output value of the custom filter. An explanation or a graphic of how {{s|escape|safe}} is different from both {{s}} of {{s|safe}} in normal auto-escaping context (if it is). Supplementary explanations of how force_escape, escape, safe, safeseq and autoescape work and interact with one … -
django.db.utils.OperationalError: attempt to write a readonly database
I'm using docker + nginx + uwsgi + django. Trying to deploy firstly in my laptop. When i'm run my web application using django server everything ok, also it looks ok when i'm trying start web app with docker without nginx, but when i'm using nginx proxy have a problem with writing data to DB (login/logout user sessions) Problem with rights of my default database issue picture app_1 | Internal Server Error: /logout/ app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute app_1 | return self.cursor.execute(sql, params) app_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute app_1 | return Database.Cursor.execute(self, query, params) app_1 | sqlite3.OperationalError: attempt to write a readonly database (venv) yhobby@hp-probook-450-g5:~/PycharmProjects/web_naas$ ls -la total 52 drwxrwsrwx 8 www-data yhobby 4096 Nov 19 15:16 . drwsrwsrwt 9 yhobby yhobby 4096 Nov 18 16:09 .. drwxrwsrwx 6 www-data yhobby 4096 Nov 19 13:59 app -rwxrwxrwx 1 yhobby yhobby 293 Nov 19 14:51 docker-compose-deploy.yml -rwxrwxrwx 1 yhobby yhobby 202 Nov 19 11:35 docker-compose.yml -rwxrwxrwx 1 yhobby yhobby 701 Nov 19 15:16 Dockerfile drwxrwsr-x 8 yhobby yhobby 4096 Nov 19 09:06 .git -rw-rw-r-- 1 yhobby yhobby 100 Nov 19 08:40 .gitignore drwxrwsr-x 3 yhobby yhobby 4096 Nov … -
(index):1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
i am new in django and i am work on ecommerce project. when i try to fetch data i have error (( Uncaught syntax error )) and in terminal in server i have error (( Not Found: /update_item/ )) this is my function.js :: function updateUserOrder(productId, action){ console.log('User Is Logged In, sending data..') var url = '/update_item/' fetch(url, { method: 'POST', headers: { 'Content-Type' : 'application/json', 'X-CSRFToken' : csrftoken, }, body:JSON.stringify({'productId': productId, 'action' : action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) }) } and this is my main.html :: <script type="text/javascript"> var user = '{{request.user}}' function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> can anyone help me??!! -
Creating user throws TypeError
When trying to createsuperuser django throws: NOTIMPORTANT/.virtualenvs/venv/lib/python3.9/site-packages/django/contrib/auth/password_validation.py", line 26, in get_password_validators klass = import_string(validator['NAME']) TypeError: string indices must be integers All my AUTH_PASSWORD_VALIDATORS in settings.py are commented out. It happend when I migrated my project onto production, no longer in development but I don't want anny password validators. -
How to send a GET request using Django and write the response to the database?
Need to send a POST request with the name of the movie, Django sends a request to an external Api and receives full information and saves the response to the database -
I still cant under stand how to use virualenv or wirtualenvwrapper in vscode
I am currently trying to learn django framework, and I am stuck because of the virtual environment setup in vscode, I know how to create a virtual environment and how to activate it and how to install packages inside of it , but my problem is that I cant know if I am using it correctly , and where it should be, for example : which directory should the virtual environment be at when working on a project , should it be with that project at the same directory or what? and also I do not know how to set it up in vscode , so please guys help me with that and give me step by step how I can set the virtual environment in vscode , and in which directory should it be , I am so confused and blocked at this point. -
django combining two query set and called it to html
I have this queryset in views.py, I am using union to combine the two queryset, how am i combine the two queryset using another models, (INNER JOIN in sql) and called it to the html? please check also the html ive given specially in temperature company = FmCustomerUsers.objects.filter(user=request.user.id) employee = FmCustomerEmployeeSupplier.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')) feedback = TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')).filter( fmCustomerEmployeeSupplierID__in=employee.values_list('id')).union(TrCustomerEmployeeSupplierSubmittedRecords.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name'))).filter( fmCustomerEmployeeSupplierID__in=employee.values_list('id')) this is my models.py class FmCustomerEmployeeSupplier(models.Model): fmCustomerID = models.ForeignKey('FmCustomer', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer") fmCustomerLocationID = models.ForeignKey('FmCustomerLocation', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerLocation") dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) lastname = models.CharField(max_length=500, blank=True, null=True) firstname = models.CharField(max_length=500, blank=True, null=True) middleInitial = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField() fmCustomerSectionID = models.ForeignKey('FmCustomerSection', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerSection") contact_number = models.CharField(max_length=500, blank=True, null=True) employee_number = models.CharField(max_length=500, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) email = models.CharField(max_length=500, blank=True, null=True) class TrCustomerEmployeeSupplierSubmittedRecords(models.Model): fmCustomerID = models.ForeignKey('FmCustomer', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer") fmCustomerLocationID = models.ForeignKey('FmCustomerLocation', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerLocation") dateSubmitted = models.DateField(null=True, blank=True) firstname = models.CharField(max_length=500, blank=True) middleInitial = models.CharField(max_length=500, blank=True) lastname = models.CharField(max_length=500, blank=True) bodyTemperature = models.FloatField() fmCustomerSectionID = models.ForeignKey('FmCustomerSection', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerSection") employee_number = models.CharField(max_length=500, blank=True, null=True) contactNumber = models.CharField(max_length=500, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) email = models.CharField(max_length=500, blank=True, null=True) class TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords(models.Model): fmCustomerEmployeeSupplierID … -
Mutual certificate authentication in Azure Web Application
I have a Django application in a Docker that is published in an Azure Web Application (Linux). For some particular API paths that are a gateway backend, I need to setup certificate authentication. For now, I have the web application settings "Incoming client certificates" in mode "Allow" because I need some path to be available without certificate. My application automatically check the certificates if there is a need to so no problems here it works well. My problem is the following, whenever some persons go the frontend I have in the same application that are situated in https://DNS.com/, they are systematically asked on the browser if they want to provide a certificate. The azure web application option provide an option for a whitelist of path, but I don't want to put all my frontend path in the whitelist (because they will be a path that will not be in it). I would prefer an option to ask certificate only at certains URL like for example https://DNS.com/api/gateways/ . My questions are: Is there a way to do that in Azure Web App ? If I put the "Incoming client certificates" to Ignore, will the certificate be checked by the Azure frontend … -
How to send a task to Celery without waiting?
I have the following code in my tasks.py file: @app.task(bind=True) def create_car(self, car): if car is None: return False status = subprocess.run(["<some_command_to_run>"]) return True It should run the command <some_command_to_run> but for some reason the website waits it to finish. I thought the whole point of Celery that it will be run in the background and return status. How can I submit this task in asynchronous way? The wanted behaviour: user asked to create a new car instance, it will add a task to the queue and return true that indicating that the car was requested correctly. In the background it will run that command and return (somewhere - not sure yet where) that status. How to do it? -
i use command location.reload() but its not working
im still new to django and i was trying to make my cart icon to have numbers that show how many items. when i press the add button its didnt work and i must to self reload before see the numbers + or -. can someone found the mistake and write in comment, that will really help me . function updateUserOrder(productId, action) { console.log('User is logged in, sending data...') var url = '/update_item/' fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'productId': productId, 'action': action }) }) .then(response => response.json()) .then((data) => { console.log('data:', data) location.reload() }) } -
ERROR: Your view return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view
I am working on a Django Project where i add an event to the database and then send an email to all the subscribers after adding event. I want to do the sending email task async, i followed some blog post and come up with this. from asgiref.sync import sync_to_async import asyncio This is the add event view @login_required(login_url='/login/') async def add_event_view(request): if request.method == 'POST': title = request.POST.get('title') description = request.POST.get('editor') menu = request.POST.get('menu') tags = request.POST.get('tags') banner = request.FILES.get('banner') data = request.FILES.get('data', None) organised_by = request.POST.get('organised_by', None) sponsored_by = request.POST.get('sponsored_by', None) event_date = request.POST.get('event_date', None) uploaded_at = request.POST.get('uploaded_at') Event.objects.create(user_id=request.user, event_title=title, event_description=description, event_category=menu, event_tags=tags, event_banner=banner, event_data=data, organised_by=organised_by, sponsored_by=sponsored_by, event_date=event_date, uploaded_at=uploaded_at) await sync_to_async(send_email(title)) return redirect(etab_view) This is the email sending function async def send_email(title): event = Event.objects.get(event_title=title) content = render_to_string("email.html", {'et': event}) subs = Subscriber.objects.values_list('email_address', flat=True) email = EmailMultiAlternatives('Emagazine Update', content, settings.EMAIL_HOST_USER, list(subs)) email.attach_alternative(content, "text/html") email.fail_silenty = False email.send() I am getting the following error: The view EMAG_APP.views.add_event_view didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view. Can anyone help me out?