Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Does Django clean malicious requests for safety?
I am wondering if using the below method is considered safe if the param being passed by client side is not checked. classmodel.objects.filter(id=1).update(data=user_passed_param) Can user send something malicious to the database that causes any issue? I do understand this is not raw sql request being used here meaning User cant delete anything in the Database as Django will be updating the data field only if that field was TextField or CharField it will be updated similarly to a string “user_passedtextetc” meaning user cant pass anything to the database like in a raw sql request. -
How to collect all validations errors when using custom class validator
I'm using a custom class validator to validate serializer fields, and I would like to raise ValidationError for all fields so API error response has fields with all errors instead of a single error, instead, now I'm getting the validation error only for single fields. Before I've used method validations inside my serializer and it worked as I need, but this is not the case with class validators. Here is how validators look like class TitleValidator: MIN_TITLE_LENGTH = 20 def __call__(self, attrs: dict): title = attrs.get("title", "") if len(title) < self.MIN_TITLE_LENGTH: raise ValidationError(f"Min title length is {self.MIN_TITLE_LENGTH}") return title class SlugsValidator: def __call__(self, attrs): slug = attrs.get("slug", "") if len(slug) < 10: raise ValidationError("Slug must be at least 10 characters long") return slug -
change the label of a field in a django form
I am working on a blog website project. I am using Django crispy form to create blog posts. Users can post articles by clicking the post button. On the add post page, users have to provide title, content, image. User also have to select category. blog/model.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True, blank=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(null=True, blank=True, default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) content = models.TextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) views.py from django.shortcuts import render from .models import Post from django.views.generic import CreateView from django.contrib.auth.mixins import LoginRequiredMixin class UserPostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'image', 'cid'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) 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|crispy }} </fieldset> <div class="form-group"> <button type="submit" class="btn btn-outline-primary btn-sm btn-block"> Post </button> </div> </form> </div> {% endblock … -
Django: get only objects with max foreignkey count
question is quite simple but possible unsolvable with Django. For example i have a model class MyModel(models.Model) field_a = models.IntegerField() field_b = models.CharField() field_c = models.ForegnKey(MyOtherModel) Question is how to select only objects that have maximal count of relations with MyOtherModel and preferable(almost mandatory) with only single queryset? Lets say, we have 100 entries alltogether, 50 pcs. point to field_c_id=1, 40 pcs. to field_c_id=2 and rest 10 pcs. entries to field_c_id = 3. I need only those which point to field_c_id=1? as 50 would be maximal count. Thanks... -
How to exclude routes with mozilla-django-oidc
In a django app how can I exclude Authorization for some endpoints? I am using mozilla-django-oidc . With a custom class EnhancedOIDCAuthentication(OIDCAuthentication): in order to get the roles from the JWT. For requests with a valid JWT token the authorization works fine. However, I am trying to find a way to exclude some APIs. I have tried @permission_classes([IsAuthenticated]) but without any effect. This class works only rest_framework.authentication The official documentation doesn't state something https://mozilla-django-oidc.readthedocs.io/en/stable/index.html -
Redirection after submit not working after adding extra code on top. Probably a priority problem
I have a script that redirects the user to the previous page_id after submit: a user would connect to page page_A Would click on product_1, Be redirected to product_1 page, Leave a review and upon clicking submit be redirected to page_id This has been working fine for a while. I decided to implement djang-hitcount in a function base view (used the code here how to use Django Hitcount in a function based view rather than a class?), as I wanted to see how many unique IP addressed where connecting. Since then the comment submission code is not working anymore. As an example: If User land on Page_A the URL would show this: http://localhost:8000/Page/A When clickin on product_1, the url would then display the following:http://localhost:8000/product/1?next=/Page/A When submitting a review the user would be redirected to : http://localhost:8000/Page/1 However now, the user is redirected to http://localhost:8000/Page/1 which obvioulsy does not exist - it should be Page A, but instead attributes the product_id to the page_id. I suspect it's because the new django-hitcount code has taken over some of the initial logic. Maybe some indention problem? Here it goes: Views.py def show_event(request, event_id): submitted = False form = 'ReviewForm' formonpage = 'ReviewForm' ###<-- …