Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to correctly configure Django to send emails with Gmail and what are the correct settings for the Gmail account?
I would appreciate some help with setting up Gmail with a Django application. I am trying to send send an email using gmail through Django to reset user passwords. My settings.py SMTP configuration is: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASWORD = 'mypassword' For the password I tried using both, the actual account password and the generated 16 digit password for apps which don't support 2-step authentication. I enabled the IMAP access and access for less secure apps in my gmail settings. I am still getting this error when trying to reset the password on my Django app: SMTPSenderRefused at /reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError s21sm6387949wmc.10 - gsmtp', 'webmaster@localhost') Any ideas what am I doing wrong? I am not sure if this is an issue with my configuration in Django or Gmail settings. Thanks in advance. -
Upload large video file in Django asynchronously
For one of the projects I need to upload a large video file(>1GB) to Django server. from django.db import models class Video(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") Issue is, it is taking a long time. In production this will cause error as it will be a bad user experience and secondly it will throw error with nginx server more than 30 sec. Is there any way to upload the file to the server asynchronously using the same model...?? -
Error AttributeError: 'str' object has no attribute 'year' when querying a model
I get startdate and enddate, but they are passed as a string. How do I convert them to a date? startdate = request.POST["startdate"] enddate = request.POST["enddate"] queryset = paidparking.objects.all() qsstats = QuerySetStats(queryset, date_field='expirationdate') values = qsstats.time_series(startdate, enddate, interval='days') return render(request, 'index/template.html', {'values': values}) Error in: values = qsstats.time_series(startdate, enddate, interval='days') -
Creating A Checklist Template And Generating An Individual Checklist For Each User In Django
I am working on a project that incorporates a checklist for each new user. I had set it up so that the checklist is a model and used a foreignKey to associate the checklist with the correct user. I realize, however, that this would force me to re-create the checklist from scratch for each user. I would like, instead, to create a template with all of the ToDo items on it and then as users join the service a new instance of the checklist is created for them. I thought about doing a ManyToManyField for each checklist. This would probably mean, however, that if one user checks off one of their ToDos everyone's ToDo would then be checked. Any thoughts on this would be appreciated as I begin to figure this out. -
Does Python RQ or Django RQ use Multiple Processors?
I use Python RQ daily on an EC2 instance. One of the challenges my team is facing is that our team is relatively young in the Python space and unfamiliar with multithreading and multiprocessing. Currently we do everything on one core for a given request. Does Python RQ (and by extension Django RQ, the specific library we use), use multiprocessing? Does it use multiple cores? If not, is there a way we can achieve this? Should we set the number of workers to be the number of cores we have? -
'access_token' KeyError within django-slack-oauth
I am having difficulties while using the [django-slack-oauth][1] package. I am getting the error KeyError: 'access_token'. Apparently it is within the pipelines.py file of the package (see below). My goal is to enable my slack app to be installed by a wide public audience. File "venv/lib/python3.8/site-packages/django_slack_oauth/pipelines.py", line 38, in slack_user slacker.access_token = data.pop('access_token') KeyError: 'access_token' Is anyone able to help me debug this? -
It shows error 404 using python manage.py run server
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: ^admin/ The current path, new_topic/, didn’t match any of these. -
How to link to external wepage with form HTML?
The links contained in the form normally display correctly not in the form but in the form every time I click the button I get a forbidden access error. Is the HTML correct? Is there a way around this? {% for v in owner_obj %} <div class="container"> <form action="{{ v.Link }}" method="POST" type="submit"> <button style="border: none;"> {% csrf_token %} <input type="hidden" name="tshirt_id" value="{{ v.id }}" /> <a href="{{ v.Link }}" rel="noopener noreferrer"> <img src="{{ v.Images }}" width="150" height="150"> </a> </button> </form> <figcaption> {{ v.Titles }} </figcaption> <figcaption> <b>{{ v.Prices }}</b></figcaption> </div> {% endfor %} -
Swagger does not reflect correctly POST endpoint definition in Django Rest Framework
I have a small endpoint class SmallEndpointViewSet(APIView): def post(self, request, *args, **kwargs): //add the request.data data to the db def delete(self, request, pk, format=None): // remove the data[pk] from db in urls.py urlpatterns = [ url( r'^small-endpoint/(?P<pk>\d+)/$', mystuff_views.SmallEndpointViewSet.as_view(), name='small-endpoint' ), url( r'^small-endpoint/$', mystuff_views.SmallEndpointViewSet.as_view(), name='small-endpoint' ), ] Everything works correctly except that in swagger, the post appears as POST /small-endpoint/{id} instead of POST /small-endpoint/ A colleague told me that I need to send a paramater to as_view as this: url( r'^small-endpoint/$', mystuff_views.SmallEndpointViewSet.as_view({ 'post': 'create' }), name='small-endpoint' ), but then I receive the error TypeError: as_view() takes exactly 1 argument (2 given) I believe that APIView version of as_view doesn't receive parameters, and that is fine. What I really want is to swagger reflect correctly that the POST call does not need and id How can I do that? -
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