Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django passing parameter from one funttion to another
I am trying to pass the value from the drop down menu to the next function other_funtion() missing 1 required positional argument: 'descrip' python def Home(request): # Description = menu_options.description() if env('ENVIRONMENT') == "TEST": current_user = f"{request.META['USERNAME']}" else: current_user = request.META['REMOTE_USER'] Description = Some_model.objects.raw(""" SELECT min(bgd.id) as id, groups, [Description] FROM [dbo].[description] bgd INNER JOIN [dbo].[auth_group] ag ON bgd.groups= ag.[groups] INNER JOIN [dbo].[auth_user_groups] aug ON ag.id = aug.group_id INNER JOIN [dbo].[auth_user] au on au.id = aug.[user_id] WHERE bgd.Status= 'Active' AND au.[username] = %s group by [Description], groups """,[current_user]) if request.method == 'POST': descrip = request.session.get('Description') request.session['Description'] = descrip other_funtion(descrip) # request.session['Description'] = Description print(descrip) return {"Description":Description} return render(request, "index.html",{"Description":Description}) def other_funtion(request): descrip = descrip print(descrip) return render(request, somehtml.html, {}) html ` <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> {% for results in Description %} <a class="dropdown-item" href="{% url 'BidderPref' %}" target="_self name="descript" value="{{results.Description}}">{{results.Description}} </a> {% endfor %} </div> ` Expected the value to pass if I change the section in the opening funtion to still have the issue def other_funtion(request, descrip) also tried descrip = request.session['Description'] #in the section funtion is try similar with the class Any help would be greatly appreciated -
Django fetch data in specific format
I have two table sale which has field like this And other table is product I am fetching tag count and avg product price with this query today = timezone.now().today() start_date = today - relativedelta(months=12) end_date = today sale_filters = ( Q(tags__name__in=['Device','Mobile']) & (Q(date_created__gte=start_date) & Q(date_created__lte=end_date)) ) sale_year = Sale.objects.using('read_rep') \ .prefetch_related('products') \ .annotate(month=TruncMonth('date_created')) \ .filter( sale_filters ).values( 'tags__name','date_created' ).annotate( tags_count=Count('tags__name'), price_avg=Coalesce(Avg('products__price'), Decimal('0')), price_sum=Coalesce(Sum('products__price'), Decimal('0')) ).order_by('date_created') Result: {'tags__name': 'Device', 'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('234.000000'), 'price_sum': Decimal('234.00')}, {'tags__name': 'Mobile', 'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('234.000000'), 'price_sum': Decimal('234.00'), 'fee_sum': Decimal('7.02')}, {'tags__name': 'Device', 'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')}, {'tags__name': 'Mobile', 'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')} I want result like this {'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'Device': 1, 'Mobile': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')} {'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'Device': 1, 'Mobile': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')} Is there any way that I can achieve this data format. Any help will be appreciated. -
What is the difference between @action and @api_view to create routes in Django Rest Framework
Both decorators appear to simply create a route for you. But what would be the practical difference (if any)? In the documentation, it is not clear. I even created two routes the same way and there was no difference -
Is there a way to optimise the time taken for uploading multipart data in a django + react app?
I have an app that has a django rest framework backend and a react frontend. As usual the user has an option to edit the details he has initially submitted. The details also contain a profile picture of the user. The update view works fine, but what I have noticed in the network tab is, if the user tries to update his profile it takes upt 5-8s and sometimes 27s for the react frontend to receive a response from backend. Question Is there any way to reduce this time or any performance optimisation method? I am also posting my code incase I am doing something wrong. react part export const editTeacherDetail = async (detailsData, photo) => { console.log("detailsData before in main api = ", detailsData); console.log("photo before in main api = ", photo); let formData = new FormData(); formData.append("name", detailsData.name.toUpperCase()); formData.append("state", detailsData.state); formData.append("adhaar_number", detailsData.adhaar_number); formData.append("current_profession", detailsData.current_profession); formData.append("phone", detailsData.phone); formData.append("location", detailsData.location.toUpperCase()); formData.append("full_address", detailsData.full_address.toUpperCase()); formData.append("date_of_birth", detailsData.date_of_birth); formData.append("gender", detailsData.gender.toUpperCase()); formData.append("name_of_school", detailsData.name_of_school.toUpperCase()); formData.append("experience", detailsData.experience); formData.append("teach_for_no_days", detailsData.teach_for_no_days); formData.append("subject", detailsData.subject.toUpperCase()); formData.append("teach_class", detailsData.teach_class); formData.append("home_tuition", detailsData.home_tuition); formData.append("fees", detailsData.fees); formData.append("home_tuition_fees", detailsData.home_tuition_fees); formData.append("shift", detailsData.shift.toUpperCase()); formData.append("board", detailsData.board.toUpperCase()); if (typeof photo !== "string") { formData.append("profile_photo", photo); } try { console.log("formData = ", formData); let response = await axiosInstance.put(`/teacher/edit-detail/`, formData); console.log(response); return response; … -
I don't have permission to pip install in docker shell
I have a Django app in a docker container, I'd like to install djangorestframework, but when I enter the container's shell, docker exec -t -i <container id> shell, and run pip install djangorestframework, then I get: ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/.local' Check the permissions. It might be useful to know that I am using a Linux machine and had an issue with Docker running Django proceses as root, which meant I needed superuser privleges to edit Django files that were created by Django manage.py functions. I overcame this by adding: user: "${user_id}:${group_id}" To the docker-compose.yml file -
Doing select_related() twice - using the output queryset
I am trying to join two models together. Project has an FK to org (orgid) People has an FK to org (orgid) But, I want the result of org + project + people, So I tried to do select_related() and then select_related on the outcome to join the new queryset to the other model. It didn't work :( a = people.objects.filter(personid=user, status='approved').select_related('orgid') b = a.select_related('projectid') In SQL this would be simply SELECT * from( SELECT app_org.orgid as orgid, orgname, username, role from app_org LEFT JOIN app_people on app_people.orgid = app_org.orgid)x LEFT JOIN app_project in x.orgid = app_project.orgid Can anyone please help me? I also tried a = people.objects.filter(personid=user, status='approved').select_related('orgid__projectid') -
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.