Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django blocktranslate passed variable with jinja include
I need to pass variable in include html and tranlate that passed variable in Django. In about.html file I include like that: include "includes/breadcrumb.html" with dir_path="About us" %} And in breadcrumb.html file I get variable {{dir_path}} - it gives as expected: "About us" But I tried like that to be able to translate it, but not working {% blocktranslate with dir_path=dir_path %} {{dir_path }} {% endblocktranslate %} -
Run celery task when testing (pytest) in Django
I have three Celery tasks: @celery_app.task def load_rawdata_on_monday(): if not load_rawdata(): # run synchronously notify_report_was_not_updated.delay() @celery_app.task def load_rawdata(): # load and process file from FTP return False # some error happened @celery_app.task def notify_rawdata_was_not_updated(): pass # send email by Django I need to test that email was sent if load_rawdata task (function) returns False. For that I have written some test which does not work: @override_settings(EMAIL_BACKEND='django.core.mail.backends.memcache.EmailBackend') @override_settings(CELERY_ALWAYS_EAGER=False) @patch('load_rawdata', MagicMock(return_value=False)) def test_load_rawdata_on_monday(): load_rawdata_on_monday() assert len(mail.outbox) == 1, "Inbox is not empty" assert mail.outbox[0].subject == 'Subject here' assert mail.outbox[0].body == 'Here is the message.' assert mail.outbox[0].from_email == 'from@example.com' assert mail.outbox[0].to == ['to@example.com'] It seems notify_rawdata_was_not_updated still being run asynchronously. How to write proper test? -
Searching through an array in an Elasticsearch field
I have a collection of Elasticsearch documents that look something like this: { "_score": 1, "_id": "inv_s3l9ly4d16csnh1b", "_source": { "manufacturer_item_id": "OCN1-1204P-ARS4", "description": "TLX Headlight", "ext_invitem_id": "TDF30907", "tags": [ { "tag_text": "Test Tag" } ], "id": "inv_s3l9ly4d16csnh1b", }, "_index": "parts" } I want to able to search for documents by tag_text under tags, but I also want to search other fields. I put together a multi_match query that looks like this: { "query": { "multi_match": { "query": "Test Tag", "type": "cross_fields", "fields": [ "tags", "description" ] } } } But I don't get any results. Can someone tell me what's wrong with my query? -
ValueError: The 'Image' attribute has no file associated with it
It says 'Image' attribute has no file associated what does that mean? How do I solve this issue? I tried to search in internet and couldn't understand anything because I've only started learning. My view: def bookdata(req): if req.method == "POST": b_name = req.POST.get('book name') a_name = req.POST.get('author name') p_year = req.POST.get('published year') price = req.POST.get('price') image = req.FILE['image'] obj = BookDetails(Name=b_name, A_Name=a_name, P_Year=p_year, Price=price, Image=image) obj.save() return redirect(add_books) My model: class BookDetails(models.Model): Name = models.CharField(max_length=30, null=True, blank=True) A_Name = models.CharField(max_length=30, null=True, blank=True) P_Year = models.IntegerField(null=True, blank=True) Price = models.IntegerField(null=True, blank=True) Image = models.ImageField(upload_to="book images", null=True, blank=True) Template: <table class="table table-bordered"> `<thead>` <tr> <th>Name</th> <th>A_Name</th> <th>P_Year</th> <th>Price</th> <th>Image</th> </tr> </thead> {% for i in data %} <tr> <td>{{ i.Name }}</td> <td>{{ i.A_Name }}</td> <td>{{ i.P_Year }}</td> <td>{{ i.Price }}</td> <td> <img src="{{ i.Image.url}} "> </td> </tr> {% endfor %} -
How to hide the default registration form created by the response from the server?
So... I am facing a very unusual problem. I'm making an application on react + django. I decided to use djoser for authorization. This works fine until I try to call any method with incorrect authorization data. For example, with or without the wrong token. Then django returns a 401 error, as it should, and at the same time this form appears. The problem is that this is the first time I see something like this in the browser and I don't even know what it's called in order to accurately Google information about it. This screenshot uses yandex browser -
Django HttpResponseRedirect return redirect to browser, but browser does not redirect
def auth(request): if request.method == 'GET': return render(request, 'Study/auth.html') elif request.method == 'POST': try: data = dict_from_raw_data(request.body) user = User.get_user(data['login'], data['password']) request.session['cookie'] = user.cookie return HttpResponseRedirect(reverse('main')) except django.core.exceptions.ObjectDoesNotExist: return JsonResponse(USER_DOES_NOT_EXIST) path('', main, name='main')... function getCookie (name) { let cookie_value; let cookies = document.cookie.split(';'); for (let idx = 0; idx < cookies.length; idx++){ if (cookies[idx].split('=')[0].trim() == name){ cookie_value = cookies[idx].split('=')[1].trim(); return cookie_value; } } } function send (data, csrftoken) { let request = new XMLHttpRequest(); request.open('POST', document.location, false); request.setRequestHeader('X-CSRFToken', csrftoken); data = JSON.stringify(data); console.log(data); request.send(data); console.log(request.responseType); } let button = document.getElementById('button'); let csrftoken = getCookie('csrftoken'); button.onclick = () => { let form = document.getElementById('auth'); let data = new Object(); for (let i = 0; i < form.elements.length; i++){ data[form.elements[i].name] = form.elements[i].value; } console.log(data); send(data, csrftoken); } The user submits a form for authorization and, if successful, the server returns a redirect. But the redirect does not happen. The console displays the html code of the page I need. Django shows that the get requests passed with code 200. How can this problem be solved? I tried to use redirect, HttpResponseRedirect, but i don't know what is the reason -
FileField get filename to delete file in AWS
So I finally managed to delete a file from AWS like this: s3 = boto3.resource('s3', aws_access_key_id = 'BLABLABLABLA', aws_secret_access_key = 'bLABla+2+bLbLABlaABla') bucket_name = 'mydoc' file_name = 'some_path/12bw.png' s3.Object(bucket_name, file_name).delete() To delete the record and AWS file I created in views.py: def slett(request, id): dokument = Dokument.objects.get(id=id) s3 = boto3.resource('s3', aws_access_key_id = 'BLABLABLABLA', aws_secret_access_key = 'bLABla+2+bLbLABlaABla') bucket_name = 'mydoc' file_name = dokument.file.url s3.Object(bucket_name, file_name).delete() dokument.delete() return HttpResponse(file_name) This is not working. I'm getting the complete URL for the file. What I need is the path from bucket. Like file_name = 'some_path/bw.png' I am new to this. To delete the file took me forever to figure out. Now I have spent hours trying to get the path... Thank you for any help. -
Django and using bcrypt to hash and check login passwords
I use bcrypt in another API and it works for me there, I copied the code over to my django app and I am getting the error: TypeError: Strings must be encoded before checking What type of field should my password field be set to in my database model? Currently it is models.CharField password = models.CharField(max_length=200, default=None) To set the password in the database I am doing: passW = self.context['request'].data["password"] encodedPass = passW.encode('utf8') instance.userprofile.password = bcrypt.hashpw(encodedPass, bcrypt.gensalt(rounds=14)) instance.userprofile.save() To check the password when they enter it in frontend I am doing: passW = self.context['request'].data["password"] encodedPass = passW.encode('utf8') print(f"raw password {passW}") print(f"encoded pass {encodedPass}") print(f"stored pass {instance.userprofile.password}") # Checks if the supplied passcode matches the user's login passcode if bcrypt.checkpw(encodedPass, instance.userprofile.password): return instance encodedPass returns b'omitted' and the stored pass returns b'omitted' -
Django-is it possible to use template filters inside "with"?
I have a template filter called "get_data_id" that returns a value; I want to use that value as an argument for another filter called "get_data": {% with variable_v= "x|get_data_id" %} <p> {{ variable_v|get_data }} </p> {% endwith %} But django returns: 'with' expected at least one variable assignment Is it possible to use template filters in "with clause" ? -
How to manually select a database when updating a model using DRF viewset
I'm trying to manually select the db with using() it works fine when retrieving the data, but for when i try to update the object, the is_valid() method in the serializer uses the default database and ignores the using(). Expected behaviour is to use the same queryset when updating object What actually happened is it uses the default database and not the manually selected DB in the queryset I tried the below code class TestViewSet( mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): serializer_class = TestSerializer def get_queryset(self): return Test.objects.using(self.user.name).all() -
I am getting this error for my project can anyone tell me solution
When i click probe test after some time in execution index out of range exception is showing in python django Actually I didnt try anything as it can cause more problem -
how to make drf-yasg generate schema to add accept content type application/json for all the requests
I want to add to all the paths that generated automatically by drf-yasg accept content type application/json by default. something like: "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/schema" } } }, "required": true }, I found something in DRF settings (setting.py) for the response but not for the request. Any help? -
django RichTextField is not displaying rich text editor in the form
I want to use RichTextEditor in my Django project. It works perfectly in the admin panel. But it does not display the rich text editor in the form template to show it in the browser. post_form.py {% extends 'users/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Add Post</legend> {{ form.media|crispy }} {{ form.as_p|crispy }} </fieldset> <div class="form-group"> <button type="submit" class="btn btn-outline-primary btn-sm btn-block"> Post </button> </div> </form> </div> {% endblock content %} I got this error: KeyError at /post/new/ 'Unknown media type "0"' How to fix this problem? -
Filter by geometry and group by location in Django
I have a SQL query similar to the following: SELECT Fip.fipcode, COUNT(Land.id) FROM Land, Fip WHERE ST_Intersects(Fip.geometry, Land.geometry) GROUP BY Fip.fipcode I have the following models implemented: class Land(models.Model): id = models.IntegerField(primary_key=True, db_column="id") geometry = models.GeometryField(null=False, db_column="geometry", geography=True) class Fip(models.Model): fipcode = models.CharField(db_column="fipcode", max_length=5) geometry = models.GeometryField(srid=4326, geography=False, db_column="geometry") I would like to use Django's models to do the filtering/grouping instead of running raw SQL queries. How would I go about doing this? Sorry if this kind of question has already been answered, I couldn't find a good answer. I have tried varius filter annotation commands with my models, but I can't get it to work as expected. Django's Docs are not the best. -
ORM Django annotate to convert string field to sorted list
I have a table containing a string field with a value like the following: '["value1", "value3", "value2"]'. Using the Django ORM, I require to convert that string type value to a list containing the values sorted alphabetically. It is necessary to keep the data type as string but to store a list inside it. So far I managed to convert it to a list but I can't sort the data. .annotate( my_field=Cast('field', output_field=JSONField()), ) -
django datetime fromisoformat: argument must be str error
I'm trying to save the date information to the database but I'm getting a typeerror def message_send(request): if request.user.is_authenticated: if request.method == 'POST': name = request.user.username email = request.user.get_email title = request.POST.get('title') message = request.POST.get('message') date = models.DateTimeField(default=timezone.now) support = supportmessages(name=name,email=email,title=title,message=message,date=date) support.save() messages.success(request, 'Your mesaage has been sent') return render(request,"messagesend.html") return render(request,"messagesend.html") else: return redirect(request,"{% url 'home' %}") the codes in this views.py file I try timezone.now but it doesn't work -
Passing data from a form to a view Django
I have two functions in views.py, the first one allows you to display information from tables. The second is to get data from the form and redirect to the page with the result. How can I pass the data received from the form to the first function to display information from the tables based on this very data? In the first function: def SuOp(request): allrooms = Rooms.objects.all() allfood = Food.objects.all() alltours = Tours.objects.all() data = { 'allfood': allfood, 'allrooms': allrooms, 'alltours': alltours, } return render(request, './obj.html', data) in the second function: def Main(request): error = '' if request.method == 'POST': form = SearchMain(request.POST) if form.is_valid(): budget = form.cleaned_data.get("budget") arrival_date = form.cleaned_data.get("arrival_date") departure_date = form.cleaned_data.get("departure_date") number_of_people = form.cleaned_data.get("number_of_people") count_days = (departure_date-arrival_date).days return redirect('allobject') else: error = 'The form has been filled out incorrectly' form SearchMain() data = { 'formS': form, 'error': error, } return render(request, './main.html', data) urls.py: urlpatterns = [ path('', views.Main, name='main'), path(r'allobject/$', views.SuOp, name='allobject') ] -
How to join these 2 tables by date with ORM
I have two querysets - A = Bids.objects.filter(*args,**kwargs).annotate(highest_priority=Case(*[ When(data_source=data_source, then Value(i)) for i, data_source in enumerate(data_source_order_list) ], .order_by( "date", "highest_priority" )) B= A.values("date").annotate(Min("highest_priority)).order_by("date") First query give me all objects with selected time range with proper data sources and values. Through highest_priority i set which item should be selected. All items have additional data. Second query gives me grouped by information about items in every date. In second query i do not have important values like price etc. So i assume i have to join these two tables and filter out where a.highest_priority = b.highest priority. Because in this case i will get queryset with objects and only one item per date. I have tried using distinct - not working with .first()/.last(). Annotates gives me dict by grouped by, and grouping by only date cutting a lot of important data, but i have to group by only date... Tables looks like that A | date |highest_priority | price | |--------------|-----------------|-------| | 2022/11/17 | 0 | 13 | | 2022/11/17 | 1 | 13 | | 2022/11/16 | 1 | 44 | | 2022/11/15 | 0 | 23 | | 2022/11/15 | 1 | 24 | | 2022/11/15 | 2 | 22 … -
How to get a Queryset from a list of IDs without using loop?
I want to get data from the database using a list of IDs. I have a model. class Point(models.Model): p1 = models.IntegerField() p2 = models.IntegerField() This model has bunch of data in my database. I have a list of IDs whose data is available in my database. [1,2,3,3,4,1] I want to get the data from my list's IDs. I know the solution that I can apply a loop here and get the data by iterating over the list. I was looking for a better solution. I have seen some similar solution with Point.objects.filter(id__in=[1,2,3,3,4,1]) but it does not return the objects of repeating values like 1 and 3 in my list's case. I want the queryset to have duplicates values if my list has duplicate values. Thanks in advance. -
Django ORM, displaying the nested for loops in the template
I'm building a school management system and right now I have implemented the backend for the 'Absences' of the student app, but I am not able to display it properly for the currently logged in student, bacause if the absence model exists on the same day more than once it is displaying everything once again. Here is my code: models.py > import datetime > from django.db import models > from django.utils.translation import gettext_lazy as _ > from accounts.models import User > > > class Hour(models.Model): > value = models.IntegerField(_('value'), unique=True) > time_period = models.CharField(_('time period'), max_length=55, unique=True) > > class Meta: > ordering = ('value',) > verbose_name = _('hour') > verbose_name_plural = _('hours') > > def __str__(self): > return str(self.value) > > > class Type(models.Model): > name = models.CharField(_('name'), max_length=55, unique=True) > > class Meta: > ordering = ('name',) > verbose_name = _('type') > verbose_name_plural = _('types') > > def __str__(self): > return self.name > > > class Absence(models.Model): > student = models.ForeignKey(User, on_delete=models.CASCADE, related_name='student1') > teacher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='teacher1') > hour = models.ForeignKey(Hour, on_delete=models.CASCADE) > type = models.ForeignKey(Type, on_delete=models.CASCADE) > day = models.DateField(_('day'), default=datetime.date.today) > date_created = models.DateTimeField(auto_now_add=True) > date_updated = models.DateTimeField(auto_now=True) > > class Meta: > ordering … -
Hosting a Dash Interactive App in Django - InvalidConfig `routes_pathname_prefix` needs to start with `/`
I have already build a Dash App that has its callback functions and everything I need. Now I want to host that in a Django app. Ive been trying for three days now but keep getting : routes_pathname_prefix needs to start with / When debugging I notice my url_base_pathname starts with 'https', but I am new to this so I'm very confused. My App app = DjangoDash(name='SimpleExample', ) Settings PLOTLY_COMPONENTS = [ 'dash_core_components', 'dash_html_components', 'dash_table', 'dash_renderer', 'dpd_components', ] X_FRAME_OPTIONS = 'SAMEORIGIN' ASGI_APPLICATION = "core.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379), ], }, }, } STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django_plotly_dash.finders.DashAssetFinder', 'django_plotly_dash.finders.DashComponentFinder', ) INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "home", "generate_train_data", "preprocess_train_data", "django_plotly_dash.apps.DjangoPlotlyDashConfig", "channels", "channels_redis", ] My HTML extension {% extends 'home.html' %} {% block content %} {% load plotly_dash %} <body> <div class="{% plotly_class name="SimpleExample" %} card" style="height: 100%; width: 100%;"> {% plotly_app name="SimpleExample"%} </div> </body> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> {{script| safe}} {% endblock content %} The urls urlpatterns= [ path("", include('preprocess_train_data.urls')), path("", include('prediction.urls')), path("django_plotly_dash/", include('django_plotly_dash.urls')),] + static(settings.STATIC_SUFFIX, document_root=settings.STATIC_ROOT) It seems like nomatter what I do it won't work, any help is highly appreciated. -
what are the cons and pros of SQL and NoSQL databases usage in the same project?
actually, I'm not sure if Stackoverflow is a suitable platform for asking such questions or not but I looked for this question many times and found many answers, and all answers agreed that NoSQL usage is perfect for real-time data transfer. what I want to ask is that during a conversation between me and someone I used Django Celery to achieve the task using PostgreSQL where I used to Update data in real-time but he advised me that SQL is not the preferable database to execute such that task because it's slower so, he advised me to use NoSQL database instead or something like MongoDB. I take a while to search for what he advised me and I found that NoSQL structure is good for Graphs and Real-time data transactions and SQL for other purposes such as relationships between data and other. but there are many questions that I want to ask for these: 1 - first of all, Is that right that SQL is slower than NoSQL when it deals with data in Real-time? if yes, so why? 2- if NoSQL is good for some purposes and bad for others unlike SQL then, Can I use two different databases … -
django python datetime not showing my linux server time
I deployed my Django project into my ubuntu server and at that time I set the timezone to UTC. Now I want to change the timezone. I changed my server time with sudo timedatectl set-timezone Asia/Tehran and when I check the date with date the command shows the right time with my timezone, but the problem is the time of my python Django project didn't change. whenever I get the time of my project it doesn't show any updates from UTC to my timezone. I use the DateTime module to get the time. I restarted my Nginx, daphne, and gunicorn with sudo systemctl restart Nginx sudo systemctl restart daphne sudo systemctl restart gunicorn but it didn't help me. how can I solve this problem? -
OAuth2 grant for a concrete scenario
I have to use the OAuth2 protocol to perform the authorization in our system. The idea is to have a separated Authentication/Authorization server and a resource server (an API, could be more in the future). Then we have a web application (backend+frontend) that needs to use the API (the resource server). It is important to say that this web application needs user + password to perform the authentication, and user and pass will be placed at the authentication/authorization server. So: WebApp -> uses user + password to authenticate against -> auth server Then we need to perform the authorization. Which OAuth2 grant is the right one here? I have reviewed all the OAuth2 grants but it is not clear because here I don't have a "third party" with their own credentials to apply Auth Code + PKCE. The web application I mentioned it is being developed by our own organization and the credentials are centralized in the auth server. So I have a separated API and a web app that needs to use the API to authenticate and to access to the protected resources. The ** password grant flow** is the one closer to my thoughts but I read that … -
Cannot import name error in Django split models
I have split the Django models into multiple model files following the follow file tree structure, +-api(app)-+ +-__init__.py +-models -+ | +-__init__.py +-model1.py +-model2.py +-model3.py +-serializers-+ | +-__init__.py +- model1_serializer.py +-views +-apps.py ... my __init__.py in models looks like, from .model1 import * from .model2 import * and serializer __init__.py files look like this, from .model1_serializer import MBTITypeSerializer I have splitter views files and serializer files. When I try to import models some of them imports without any problem, but some imports not working. I have observed if I change the import order in __init__.py file the working imports change. This is how I tried to import models, in serializers from api.models import MBTIType ... Here is the error trace, Traceback (most recent call last): File "C:\Users\ \AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\ \AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "D:\ \implementation\backend\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\\implementation\backend\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "D:\\implementation\backend\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\\implementation\backend\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "D:\\implementation\backend\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\\implementation\backend\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\\implementation\backend\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\\implementation\backend\venv\lib\site-packages\django\apps\config.py", line 301, in …