Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: filter by conditions on related model
I have the following schema: class Client(models.Model): name = models.CharField(max_length=100) country = models.CharField(max_length=100) city = models.CharField(max_length=100) street = models.CharField(max_length=100) class Invoice(models.Model): client = models.ForeignKey(Client) ... Given some complex filter on Client objects, I want to find all their Invoices. For example all Invoice of Clients, that contain letter 'a' in their address: Invoice.objects.filter( Q(client__name__icontains='a') | Q(client__country__icontains='a') | Q(client__city__icontains='a') | Q(client__street__icontains='a') ) But I don't want to keep all the details of the filtering logic in this place. Ideally I would like to have a separate function that contains all the filtering logic, for example: def get_client_filter_for_contains_letter_a(): return Q(name__icontains='a') | Q(country__icontains='a') | ... and then I would like to use it to filter Invoices, for example: Invoice.objects.filter(get_company_filter_for_contains_letter_a()) # does not work - should use 'company__name__icontains' instead of 'name__icontains' but maybe also Products on those Invoices: class Product(models.Model): invoice = models.ForeignKey(Invoice) Product.objects.filter(get_company_filter_for_contains_letter_a()) # does not work - should use 'invoice__company__name__icontains' instead of 'name__icontains' So far I figured out I could do some prefix string concatenation, i. e.: def get_client_filter_for_contains_letter_a(prefix: str): return Q(**{'{prefix}client__name__icontains': 'a'}) | Q(**{'{prefix}client__country__icontains': 'a'})) | ... Product.objects.filter(get_company_filter_for_contains_letter_a(prefix='invoice__company__')) Is there a better, clean, preferably object-oriented way to do it? -
Remove the database exception error on a page reload
I am on Django Framework and implemented an interface where a user can do Insert and Update operations on a MySQL table. My table does not allow duplicates, so I display an Exception error to the user to let them know their request failed. However, when I reload the page the error message still get's displayed when it shouldn't. The message only disappears when I submit a successful request that has no duplicates. It seems like the error message keeps getting displayed because on page reload it is returning a POST request and it re-enters the duplicate key which spits out the Exception message. How can I stop this request from submitting twice, or is there a better approach to accomplish this? views.py def generate_student_info(request): # Retrieve inputted value current_student_name = request.POST.get('student_name') current_student_id = request.POST.get('student_id') # Read the table from the database connection = db.open_connection(read_only=False) sql_str = f"""SELECT * FROM {students_table};""" df = db.read(sql_statement=sql_str, connection=connection) # creating a formset insert_formset = formset_factory(StudentInfoForm, extra=0) formset = insert_formset(request.POST or None, initial=[{'student_id': df['student_id'][i], 'student_name': df['student_name'][i]} for i in range(len(df))]) context = {'formset': formset, 'db_error_message': '', 'display_error_message': False} if request.method == 'POST': # Insert MySQL query if 'student_name' in request.POST: try: insert_query = f"""INSERT … -
How do I authorize using Spotipy on Django?
I am having a great deal of trouble trying to authorize Spotipy. It does fine in IDLE, but as soon I try to do it together with Django, hell lets loose. Where I have gotten the farthest, is where I have gotten the code from the callback. But what do I do after that? This piece of code below takes def add_song(request, pk, uri): scope = "user-read-recently-played user-top-read user-read-playback-position user-read-playback-state user-modify-playback-state user-read-currently-playing user-read-private playlist-modify-private playlist-read-private" token = util.prompt_for_user_token("username", scope, client_id=SECRET,client_secret=SECRET,redirect_uri='http://localhost:8000/rooms/callback/') sp = spotipy.Spotify(auth=token) sp.add_to_queue(uri) auth_manager = spotipy.oauth2.SpotifyOAuth(scope='user-read-currently-playing playlist-modify-private', show_dialog=True) if request.GET.get("code"): # Step 3. Being redirected from Spotify auth page auth_manager.get_access_token(request.GET.get("code")) return redirect('/') return render(request, 'rooms/{0}.html'.format(pk)) def callback(request): return redirect(reverse("index")) The URL patterns: urlpatterns = [ path('<int:pk>/add_song/<str:uri>', views.add_song, name='add_song'), path('callback/<str:token>', views.callback, name="callback") ] I really need something to continue on. I have been googling so much, but there isn't really anything I know what to do with. Could you provide an example of Django Python authorization or try to help me? -
Django admin interface display content of file when adding it
I have a model who contain a FileField How can I do to display the content of the file in the admin interface when I add the file ? -
Django: How to render an admin form with admin action queryset
I have a push notification model which is used to send users push notifications to their mobile phones, but what I'm trying to make right now is an admin action that would send multiple users push notifications. So here's my admin action which lets to select users and then the action which is `Send Push Notification': So far I have just created an action and an empty HTML template which I'm thinking that I could somehow extend the other app which is a notification form. This is the notification form that I would like to open when the users are selected. As you can see this is how we are used to sending the notifications right now, just one user once a time. So basically I would like to return this form, but with a list of users that were selected before from the user's tab, I would simply call it queryset, right? {% extends "admin/....?html" %} {% block content %} <form action="" method="post"> {% csrf_token %} <p>Are you sure you want to execute this action on the selected items?</p> {% for order in orders %} <p>{{ order }}</p> <input type="hidden" name="_selected_action" value="{{ order.pk }}" /> {% endfor %} <input … -
How to return custom response if request is Unauthorized in Django Rest
If any request failed to authenticate this view, the user is getting the default Django-Rest page. How I can customize this response in case of an unauthorised request. @api_view(['GET']) @authentication_classes([JWTTokenUserAuthentication]) @permission_classes([IsAuthenticated]) def home_view(request): ----- -
Django - cache view response for the remainder of the day
So, django.views.decorators.cache defines a cache_page decorator that will automatically cache the view’s response for you, such as: from django.views.decorators.cache import cache_page @cache_page(60 * 15) def my_view(request): ... I'm hoping this is a super simple "yes" - but can this be set dynamically? So I want to calculate on the fly the number of seconds left from say, dt_now (which is now) to the end of the day, so dt_now.replace(hours=23, minute=59, ..., microseconds=9999999). Is it possible to evaluate the cache page dependent on such a dynamic value? -
Can I query an IntegerRangeField by int?
I'm currently assessing the IntegerRangeField for a new model. The docs give this usage example: >>> Event.objects.filter(ages__contains=NumericRange(4, 5)) <QuerySet [<Event: Soft play>]> Will Event.objects.filter(ages__contains=4) work as well? (Can I query IntegerRangeField by a Python int?) -
Django rest framework partial update (PATCH)
I am trying to do a partial update of a user so that not all the fields should be sent in a request. For this I have created a view like this: elif request.method == 'PATCH': user_serializer = UserSerializer(user, data=request.data, partial=True) if user_serializer.is_valid(): user_serializer.save() return Response({'message': 'User updated correctly'}, status=status.HTTP_200_OK) else: return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have seen that if the partial = True parameter is activated then it will call the partial_update () function of the serializer, but it does not: def partial_update(self, request, *args, **kwargs): print("partial update") So, how can I do this partial_update to update a user field? -
django 2.2.21 file path
since django did this security issue https://www.djangoproject.com/weblog/2021/may/04/security-releases/ iam not able to open file for test data: iam using import os from django.core.files import File file = File(os.path.join(os.path.dirname(__file__), "data", "tests", "test_pdf.pdf")) then Model.objects.create(name="test". file=file) getting error: django.core.exceptions.SuspiciousFileOperation: File name 'apps/app/data/tests/test_pdf.pdf' includes path elements any workaroud of this? or whats a correct way to load the pdf? -
How to execute django commands from another django project?
I have two django project on the same server. Project 1 : is running (with gunicorn) to receive rest request and display data. Project 2: is used only to execute django commands and is not running. I would like to run a command from project2 inside project1 but when i do nothing is happening. I tried : Popen(["/opt/xxx/venv3/bin/python", "/opt/xxx/src/manage.py", "custom_commands", "params"]) os.system("/opt/xxx/venv3/bin/python /opt/xxx/src/manage.py custom_commands params") without success (i tried to read the ouput of Popen but it's empty). When i run the same command inside a python shell on the server it works so its must be related to calling a django command from another django project. Thanks in advance. -
Import data from csv file to tables with Foreignkeys in django
Im trying to import data from an excel file to my database. The data is of the format [1]: https://i.stack.imgur.com/gztLF.png The values from question_no , question columns are to be stored in ExamQuestion table which has a Foreignkey to QuestionBank model and the rest of the column values are to be stored in ExamOptions table which has a Foreignkey to ExamQuestion model .So far i could save the question_no , question part but could not find a way to store the rest of the data. Here is my code def import_question_option(request, pk=None): if request.method == 'POST': question_resource = resources.modelresource_factory(model=ExamQuestion)() new_ques = request.FILES['myfile'] dataset = tablib.Dataset( headers=['question_no', 'question',] ).load(new_ques .read().decode('utf-8'), format='csv') dataset.append_col( col=tuple(f'{pk}' for _ in range(dataset.height)), header='question_bank_id' ) result = question_resource.import_data(dataset, dry_run=True) if not result.has_errors(): question_resource.import_data(dataset, dry_run=False) qs_lst = dataset.get_col(0) qs_obs = ExamQuestion.objects.filter(question_no__in=qs_lst).order_by('-id') option_resource = resources.modelresource_factory(model=ExamOptions)() dataset = tablib.Dataset( headers=['options', 'options_code',] ).load(new_events.read().decode('utf-8'), format='csv') # required code to add options to ExamOptions model return HttpResponse("Success") else: qust_bank = QuestionBank.objects.get(id=pk) return render(request, 'student/import_questions.html', {'qbank':qust_bank.name ,'pk': pk}) the models are class QuestionBank(models.Model): name = models.CharField(max_length=64, null=True) language_id = models.ForeignKey(Languages, on_delete=models.SET_NULL, null=True) description = models.TextField(null=True) class ExamQuestion(models.Model): question_no = models.IntegerField(verbose_name=_('question_no'), null=True) question = models.CharField(max_length=250) image = models.ImageField(upload_to='images/',null=True) question_bank_id = models.ForeignKey(QuestionBank, on_delete=models.SET_NULL, null=True) class ExamOptions(models.Model): … -
Django - Update field when datetime field expires
I am looking for a solution to update my field when DateTime field expires. So basically, what I want is let's say DateTime is set for an hour from now, I want to make it that when the current time gets to that set time, it updates another field "missed" to True Process: Field = 2021/05/05 16:24 Time gets to 16:24 It gets triggered -> Field missed gets changed to True -
Failed to generate executable file for Django by pyinstaller
I have tried to find solutions on google, but it seems that there aren't some suitable solutions. OS: Win 10 Python version: 3.7 Django version: 3.1.5 pyinstaller version: 4.2 There are the generate steps I followed: 1.excute command pyi-makespec -D manage.py in the project directory 2.excute command pyinstaller manage.spec However in the second step something bad happened, the log shows: 19337 INFO: Analyzing hidden import 'django.db.backends.__pycache__.base' 19362 ERROR: Hidden import 'django.db.backends.__pycache__.base' not found 19362 INFO: Analyzing hidden import 'django.contrib.gis.db.models' 20603 INFO: Processing module hooks... 20604 INFO: Loading module hook 'hook-win32ctypes.core.py' from 'd:\\python\\lib\\site-packages\\_pyinstaller_hooks_contrib\\hooks\\stdhooks'... 21318 INFO: Loading module hook 'hook-difflib.py' from 'd:\\python\\lib\\site-packages\\PyInstaller\\hooks'... 21340 INFO: Excluding import of doctest from module difflib 21341 INFO: Loading module hook 'hook-distutils.py' from 'd:\\python\\lib\\site-packages\\PyInstaller\\hooks'... 21355 INFO: Loading module hook 'hook-distutils.util.py' from 'd:\\python\\lib\\site-packages\\PyInstaller\\hooks'... 21358 INFO: Excluding import of lib2to3.refactor from module distutils.util 21358 INFO: Loading module hook 'hook-django.contrib.py' from 'd:\\python\\lib\\site-packages\\PyInstaller\\hooks'... Traceback (most recent call last): File "<string>", line 21, in walk_packages File "d:\python\lib\site-packages\django\contrib\gis\admin\__init__.py", line 5, in <module> from django.contrib.gis.admin.options import GeoModelAdmin, OSMGeoAdmin File "d:\python\lib\site-packages\django\contrib\gis\admin\options.py", line 2, in <module> from django.contrib.gis.admin.widgets import OpenLayersWidget File "d:\python\lib\site-packages\django\contrib\gis\admin\widgets.py", line 3, in <module> from django.contrib.gis.gdal import GDALException File "d:\python\lib\site-packages\django\contrib\gis\gdal\__init__.py", line 28, in <module> from django.contrib.gis.gdal.datasource import DataSource File "d:\python\lib\site-packages\django\contrib\gis\gdal\datasource.py", line 39, in <module> … -
How to generate an excel file and save it directly to a path in Django
I am new to Django and I was wondering if the following is possible: Now, in my django app(not admin page) I create xls files using the xlwt library. Pushing a button the user choose where he wants to save the generated file, but isn't what I want. The ideal for me is when the user clicks on the "Save Excel" button then I want the file to be generated and directly be saved in a specific path in the server or in the database(via FileField), not somewhere in the user's pc. Without asking the user . Thanks in advance. -
Django Admin show Image immediately after upload
maybe this issue is answered elsewhere, but I have no luck of finding it. Here is my issue: I have a Django admin site that has an ImageField to upload image look like this In order to show the uploaded image, I will have to click on Save/ Save and add another/ Save and continue editing. What I really want is show preview of the picture immediately after I upload it. Is there anyway to trigger it via ImageField override or somehow? Any suggestion would be appreciated -
Image is not uploading to the specific destination
I tried several ways to upload images to a specific destination. Showing no error but the image is not uploading to the destination. views.py from django.views.generic.edit import CreateView from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['name', 'weblink', 'image'] success_url = reverse_lazy('posts') template_name = 'base/post.html' def form_valid(self, form): # form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user return super().form_valid(form) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): name = models.CharField(max_length=200) weblink = models.CharField(max_length=200) image = models.ImageField(default='default.png', upload_to='uploads/%Y/%m/%d/') author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'Added {self.name} Profile' urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ..... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I added also the media root and URL in the settings file. I didn't any clue but unable to upload the file to the specific location. -
How can I make django model in this situation?
I make a stock market project using django. So I want to make 2 database table. table stocklist (ticker, name) table stockPrice (code, date, price, open, high, close etc...) I want to make second table name is stock ticker. so I though this is many to one relation. And I made django model.py class StockList(models.Model): ticker= models.CharField(max_length=10,primary_key=True) company = models.CharField(max_length=50) last_update = models.DateTimeField() class stockPrice(models.Model): ticker = models.ForeignKey('stockList', on_delete=models.CASCADE) date = models.DateTimeField() open = models.FloatField() high =models.FloatField() low = models.FloatField() close = models.FloatField() diff = models.FloatField() volume = models.FloatField() But it isn't work. How I make django model? And is it many to one relation? Thank you. -
Check if current user email ends with
I want to check if the current logged in user email ends with a certain string. I tried to do request.user.email__endswith ... but that doesn't work. I know you can do User.objects.filter(email__endswith) But how do I do that in the view with the current user? -
Django: How to handle 'dynamic' ModelChoiceField forms?
I'm working on a form with 2 fields from 2 different models linked together. See below : class FirstModel(models.Model): name = models.CharField(max_length=32) class SecondModel(models.Model): name = models.CharField(max_length=32) first_model = models.ForeignKey(FirstModel, on_delete=models.CASCADE) I want the user to select a FirstModel with a first widget. And a SecondModel using a second widget only filled with SecondModel that match the FirstModel that the user selected. My idea: using two ModelChoiceField with all the data in it and filter in the browser using javascript, but I can't find any way to do it. What am I doing wrong ? -
from .exceptions import InvalidKeyError ModuleNotFoundError: No module named 'jwt.exceptions'
I am trying to send an email verification link to a registered user but i keep getting this error, i dont know why but anytime i send a post request to this endpoint i keep getting this error Internal Server Error: /auth/register Traceback (most recent call last): File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/SRC/users/views.py", line 28, in post print(token) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework_simplejwt/tokens.py", line 80, in __str__ from .state import token_backend File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework_simplejwt/state.py", line 3, in <module> from .backends import TokenBackend File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework_simplejwt/backends.py", line 3, in <module> from jwt import InvalidAlgorithmError, InvalidTokenError, algorithms File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/jwt/algorithms.py", line 5, in <module> from .exceptions import InvalidKeyError ModuleNotFoundError: No module named 'jwt.exceptions' Here is my views.py class RegisterView(GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() user_data = serializer.data user = … -
Upper index does not seem to work with iexact Django field lookup
I have some references (strings) that I want to use to filter a query with a case-insensitive exact match. To do so, I used iexact Django field lookup. Model.objects.filter(column1__iexact=reference) Since I have a very large number of rows on that table, I wanted to create an index to speed up the query. Django uses the UPPER function to perform the iexact lookup. So I created the following migration (DB is Postgresql): class Migration(migrations.Migration): dependencies = [ ('app', 'previous_migr'), ] operations = [ migrations.RunSQL( sql=r'CREATE INDEX "index_name_idx" ON "table" (UPPER("column1") );', reverse_sql=r'DROP INDEX "index_name_idx";' ), ] Unfotunately, this index does not seem to be used while querying. Why do I think this ? Here are the request times with : iexact ~= 17s exact < 1s Here is the generated (truncated) SQL query : SELECT "table"."id" FROM "table" WHERE ( "table"."is_removed" = false AND (UPPER("table"."column1"::text) = UPPER('blablabla') OR UPPER("ordering_order"."column2"::text) = UPPER('blablabla'))) ORDER BY "table"."id" ASC ) Is there something wrong with my migration ? Any other option to do this query with good performance ? -
Can I use redis as a backend proxy server for storing WebSocket connection instances of a Chat Application
I am building a chat application using Django Channels and REST framework as the backend and a React frontend. I want to make sure each chat room has a single websocket connection. How can Redis serve as a Proxy server and help achieve this goal. -
how i can add update user data using django-allauth
how i can add update user data using django-allauth , i want allow users to change first name and 2nd name after signup so how to do that ? my code | models.py : class Profile(models.Model): first_name = models.CharField(max_length=125) last_name = models.CharField(max_length=125) user_pic = models.ImageField(upload_to='images/',null=True, blank=True) def __str__(self): return self.first_name forms.py : # update user data Form class ProfileForm(forms.ModelForm): first_name = forms.CharField(required=False,label='First Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter First Name '}) ) last_name = forms.CharField(required=False,label='Last Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter Second Name '}) ) user_pic = forms.ImageField(required=True,label='Your photo') class Meta: model = User fields = ('first_name', 'last_name','user_pic') def save(self, commit=True): user = super(ProfileForm, self).save(commit=False) if commit: user.save() return user views.py : # Edit Profile View @login_required(login_url='accounts/login/') class ProfileView(UpdateView): model = User form_class = ProfileForm success_url = reverse_lazy('profile') template_name = 'account/profile.html' def get_object(self, queryset=None): return self.request.user html page : <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" style="background-color:#7952b3" value="update"> </form> when i open page in browser it don't show the form field but the update button appear -
django.contrib.auth.models.AnonymousUser object at 0x000001F13FE409A0 "Mpesa.Paid_user" must be a "User" instance
I would like to save to the database the currently logged-in user but it keeps throwing out the error above, any insight would be appreciated. below are some snippets. views.py our_model = Mpesa.objects.create( Paid_user = request.user, MpesaReceiptNumber = mpesa_receipt_number, PhoneNumber = phone_number, Amount = amount, TransactionDate = aware_transaction_datetime, ) our_model.save() models.py class Mpesa(models.Model): Paid_user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) MpesaReceiptNumber = models.CharField(max_length=15, blank=True, null=True) PhoneNumber = models.CharField(max_length=13, blank=True, null=True) Amount = models.IntegerField(blank=True, null=True) TransactionDate = models.DateTimeField(blank=True, null=True) Completed = models.BooleanField(default=False)