Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page loader while retrieving data from a PostgreSQL database in Django
I'm using Django with a PostgreSQL database to create a website for entering and viewing data. On the data viewing page there are several tables that are populated with data from the database. I'm trying to implement a page loader that will display until the data has been retrieved from the database and the webpage is fully loaded. At the moment, the page loader does not appear until after the data is retrieved and then only flashes briefly while the page fully loads. How can I make it appear from when I first click on the link to go to the page? Here is my html: <div id="page-loader"> <div class="loader-spinner"></div> <p class="loader-message">Loading...</p> </div> My CSS: #page-loader { display: flex; align-items: center; justify-content: center; width: 300px; z-index: 999999; background-color: rgba(75, 75, 75, 0.75); border-radius: 10px; } .loader-spinner { width: 50px; height: 50px; border: 2px solid #FC6620; border-radius: 50%; border-top: 2px solid #fff; animation: spin 1s linear infinite; margin: 0; z-index: 999999; } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .loader-message { margin-left: 10px; font-size: 24px; color: #FC6620; z-index: 999999; } and my Javascript: document.addEventListener('readystatechange', () => { document.getElementById("page-loader").style.display = "visible"; }) window.onload = function() … -
Error when trying to save a form in django
I am new to django and I am working on a project whereby users fill a form from frontend and the data is saved to a gig model where the writer extends from a profile foreignkey. The error says ValueError at /seller_profile/ The Gig could not be created because the data didn't validate. Here is the models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='avatar.jpg', null=True, blank=True) about = models.CharField(max_length=100) def __str__(self): return self.user.username class Gig(models.Model): writer = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False) category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False) title = models.CharField(max_length=500, null=True, blank=True) description = models.CharField(max_length=500, null=True, blank=True) image = models.ImageField(null=False, blank=False) gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Views.py: def createGig(request): gig = request.user.profile form = CreateGigForm() if request.method == 'POST': form = CreateGigForm(request.POST, request.FILES) if form.is_valid: gig = form.save(commit=False) gig.writer = gig gig.save() messages.info(request, 'Profile Succesfully Created') return redirect('create') else: messages.error(request, 'Gig Not Created! Try Again Later') context = {'form':form} return render(request, 'starter/create_gig.html', context) And here is a screenshot of the error message: Error message screenshot -
Pip error with requirements while deployng Django to Digital Ocean
I am trying to Deploy my Django API to a droplet in Digital Ocean, with ubuntu. I freezed my environment with pip freeze > requirements.txt command, and pulled it into the server. When I ask to install dependencies, into the activated virtual environment, with pip install -r requirements.txt it says that ERROR: Could not find a version that satisfies the requirement apturl (from versions: none) ERROR: No matching distribution found for apturl If id does matter, here is the actual requirements file: apturl beautifulsoup4==4.11.1 blinker==1.4 Brlapi certifi==2020.6.20 chardet==4.0.0 charset-normalizer==2.1.1 cliapp==1.20180812.1 click==8.0.3 colorama==0.4.4 command-not-found==0.3 cryptography==3.4.8 cupshelpers==1.0 dbus-python==1.2.18 defer==1.0.6 distlib==0.3.4 distro==1.7.0 distro-info===1.1build1 filelock==3.6.0 Flask==2.2.2 Flask-Login==0.6.2 Flask-SQLAlchemy==3.0.1 git-filter-repo==2.38.0 greenlet==1.1.3.post0 gunicorn==20.1.0 httplib2==0.20.2 idna==3.3 importlib-metadata==4.6.4 itsdangerous==2.1.2 jeepney==0.7.1 Jinja2==3.1.2 keyring==23.5.0 language-selector==0.1 launchpadlib==1.10.16 lazr.restfulclient==0.14.4 lazr.uri==1.0.6 llfuse==1.3.8 louis==3.20.0 macaroonbakery==1.3.1 Markdown==3.3.6 MarkupSafe==2.1.1 more-itertools==8.10.0 netifaces==0.11.0 oauthlib==3.2.0 olefile==0.46 pexpect==4.8.0 Pillow==9.0.1 pipenv==11.9.0 platformdirs==2.5.1 protobuf==3.12.4 psycopg2-binary==2.9.5 ptyprocess==0.7.0 pycairo==1.20.1 pycups==2.0.1 Pygments==2.11.2 PyGObject==3.42.1 PyJWT==2.3.0 pymacaroons==0.13.0 PyNaCl==1.5.0 pyparsing==2.4.7 pyRFC3339==1.1 python-apt==2.3.0+ubuntu2.1 python-dateutil==2.8.1 python-debian===0.1.43ubuntu1 python-dotenv==0.21.0 pytz==2022.1 pyxdg==0.27 PyYAML==5.4.1 reportlab==3.6.8 requests==2.28.1 SecretStorage==3.3.1 six==1.16.0 soupsieve==2.3.2.post1 SQLAlchemy==1.4.41 systemd-python==234 ttystatus==0.38 typing_extensions==4.4.0 ubuntu-advantage-tools==27.12 ubuntu-drivers-common==0.0.0 ufw==0.36.1 unattended-upgrades==0.1 urllib3==1.26.5 virtualenv==20.13.0+ds virtualenv-clone==0.3.0 wadllib==1.3.6 Werkzeug==2.2.2 xdg==5 xkit==0.0.0 zipp==1.0.0 I tried to install dependencies by hand, update pip and Python ( version 3.10 ), and build-essentials, but nothing worked. I deleted the versions from the file, and it … -
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