Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku timeout on Django 3 Python 3 hobby dyno
I upgraded a django web application on heroku to Python 3 and Django 3. Now the app tries to load a page that had been working on the lower django version, the lower python version, and now times out. The error you get from the Django Logs is as follows: [2020-07-23 08:04:46 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:11) Then it restarts and shows you that there is an error with the webserver on heroku. I have tried to change the procfile to web: gunicorn whaat.wsgi And removed the collectstatic command, shifting that off to the config vars in heroku. I have included gunicorn in the settings file. I also checked that java script was not slowing it down, but I feel like there is a slowness with the database as at least one page loads on my site (the one with no database requests). The app works locally, just not on heroku, so what can I do? -
Fastest way to get a unique record from query set
I'm new to django & I'm looking for best way to do following I have a list of user_ids to update & 1 user_id by which all of them where updated. What I'm looking for is a way to use one single DB query to get both. Here is what I'm doing right now #users_ids > list of user_ids for updated users #updated_by > int users_ids.append(created_by) queryset = User.objects.filter(id__in=users_ids) created_by = queryset.get(id=updated_by) person_list = queryset.exclude(id=updated_by) I'm wondering if django provides me a way to do get created_by & person_list in a single query, in a faster way to optimize performance. Any help is appreciated -
Exception occured processing wsgi script - Django Error
I am trying to port Django proj which was in python2.7 to python 3.5. I have made the necessary changes in to code to support python3.5.2. I have also install mod_wsgi for python3. I am getting the error mentioned in the Title. I am not able to understand where did i make the mistake. PS: I am working on django for the first time. I am adding the apache2 error log below: Target WSGI script '/home/kishor/ENVS/linksmart_full/smartDNA/smartdna.py' cannot be loaded as Python module. [Thu Jul 23 12:57:52.392881 2020] [wsgi:error] [pid 10132:tid 140050044196608] [remote 127.0.0.1:0] mod_wsgi (pid=10132): Exception occurred processing WSGI script '/home/kishor/ENVS/linksmart_full/smartDNA/smartdna.py'. [Thu Jul 23 12:57:52.395522 2020] [wsgi:error] [pid 10132:tid 140050044196608] [remote 127.0.0.1:0] Traceback (most recent call last): [Thu Jul 23 12:57:52.395733 2020] [wsgi:error] [pid 10132:tid 140050044196608] [remote 127.0.0.1:0] File "/home/kishor/ENVS/linksmart_full/smartDNA/smartdna.py", line 18, in <module> [Thu Jul 23 12:57:52.395778 2020] [wsgi:error] [pid 10132:tid 140050044196608] [remote 127.0.0.1:0] application = get_wsgi_application() [Thu Jul 23 12:57:52.395823 2020] [wsgi:error] [pid 10132:tid 140050044196608] [remote 127.0.0.1:0] File "/home/kishor/ENVS/myenv/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Thu Jul 23 12:57:52.395870 2020] [wsgi:error] [pid 10132:tid 140050044196608] [remote 127.0.0.1:0] django.setup(set_prefix=False) [Thu Jul 23 12:57:52.395914 2020] [wsgi:error] [pid 10132:tid 140050044196608] [remote 127.0.0.1:0] File "/home/kishor/ENVS/myenv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup [Thu Jul 23 12:57:52.395951 2020] [wsgi:error] … -
Likert-like scale in Django
I am trying to set up a questionnaire in Django and in the questionnaire, I want to include questions involving a Likert scale. I tried doing this with the Likert package of Django, but this is not ideal for several reasons: It is not possible to change the labelling of the scale (I want to give labels like 'do not agree' and 'totally agree') It seems impossible to store responses disaggregated. My question somewhat looks like the one asked here, but I could not make much of the answer. I hope somebody could give me some pointers to make progress. -
Django - Change label of foreign key
I want to change models.ForeignKey label into another language. For that reason I've used adding verbose_name attribute, Meta class, __str__ method, but nothing changes. In my case I want to display Insurance Type label as Example label in Blank model's form. Here are my codes: models.py: class Insurance(models.Model): insurance_type = models.CharField(_('Example label'), max_length=150, unique=True) class Meta: verbose_name_plural = 'Example text' def __str__(self): return self.insurance_type class Blank(models.Model): blank_series = models.CharField(_('Blankın seriyası'), max_length=3) blank_insurance_type = models.ForeignKey(Insurance, on_delete=models.CASCADE, verbose_name='Verbose label') def __str__(self): return self.blank_series class Meta: verbose_name_plural = 'Blanks' -
Django: Query gives zero results after first match in for loop
The following code works fine until the filter gets first match(es). After that on the following runs in the for loop, the query always returns 0. If in that result object would be a match for the next row also, it doesn't even see that, so I don't see this being a cache issue (which might have been far fetched anyhow). for row in self._ordr.OrderRows.SalesOrderRow: available = row.Row_amount - Slot.objects.filter(rows_ids=row.Row_id).count() if available > 0 or row.Row_id in self.instance.rows_ids: # some code Any ideas what am I doing wrong here? -
how to run a downloaded django project?
I have gotten a django project from a colleague. After looking up how one should run it on their on computer, it seems I need to find a text file called "requirements.txt". However, I don't have this one in the folder that I've downloaded. I tried running both commands python manage.py runserver but I get the following error: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' running migrate before running runserver also doesn't help. It results into the following error: ModuleNotFoundError: No module named 'django_extensions' Can a downloaded django project be run without the requirements.txt file? -
How to include css class to django forms
I'm using Django Password Reset view to reset user's password. It's working perfectly fine, I've included the predefined Password reset class in my urls.py. I want to design the fields of the form, since I don't have forms.py, I can't give css attribute to the form field. Can I get help? -
How to use 'router' in django and DRF
I want to use router in django. But when I tried to import the module and Migrate it to use the router, the following error appears. ModuleNotFoundError: No module named 'router' I definitely imported the module, but I can't understand the error that says there is no module. Can you give me a solution? Here is my code. urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers from api.views import arduinoViewSet router = routers.DefaultRouter() router.register('arduino', arduinoViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('', include('router.urls')), path('auth/', include('rest_auth.urls')), path('auth/registration/', include('rest_auth.registration.urls')), ] -
How to Connect Tkinter Application with Django User Model?
I got stuck in one Place. I have a Tkinter Application and Web Application on Django. I have a login system in both Application. Rather making two distinct User Model, I want to linked My Tkinter Desktop Application with Django user Model so that I can synchronized the User data in both Application but the problem is when I am checking the password in my tkinter Application it is checking it as a plain text but the password in django User Model cannot be decrypt. So, Is there any way that I can synchronized my Desktop Application (Tkinter) and Web Application (Django) with one User Model (Django)? -
Field Lookup in DRF serializer validation
I am setting up a Django REST application where peopple can review restaurants. So far I have those models: class RestaurantId(models.Model): maps_id = models.CharField(max_length=140, unique=True) adress = models.CharField(max_length=240) name = models.CharField(max_length=140) class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class StarterPics(models.Model): restaurant_review_id = models.OneToOneField(RestaurantReview, on_delete=models.CASCADE) pics_author = models.ForeignKey(User, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) name_1 = models.CharField(max_length=40) picture_1 = models.ImageField() My serializers: class RestaurantIdSerializer(serializers.ModelSerializer): class Meta: model = RestaurantId field = fields = '__all__' class RestaurantReviewSerializer(serializers.ModelSerializer): class Meta: model = RestaurantReview field = fields = '__all__' class StarterPicsSerializer(serializers.ModelSerializer): class Meta: model = StarterPics fields = '__all__' def validate_restaurant_review_id(self, value): if value.review_author != self.context['request'].user: raise serializers.ValidationError("User has not reviewed the restaurant") if RestaurantReview.objects.filter(id=value.id, restaurant_id=value.restaurant_id).exists(): return value raise serializers.ValidationError('Not the right restaurant') So what I need is that if the author is not the author of the review he can't POST any pictures in StarterPics. This part of my validation is working fine. But I also need to be sure that even if the User is the author of the review he can't change the restaurant_id and POST the picture with another restaurant_id. The second part of validate_restaurant_review_id doesn't work because the User can POST … -
How to display multiple tabular inlined items of multiple objects in single html page
I am working on a project and I created about page, and add staff details, then create another object for social media detail of staff, and make it tabular inline into django admin, and I want to display all staff members in single page and social media according to staff member. I added all code I've done. models.py from django.db import models from django.utils.safestring import mark_safe from ckeditor_uploader.fields import RichTextUploadingField class AboutStaff(models.Model): image = models.ImageField(upload_to='images/staff/',null=True) name = models.CharField(max_length=255) designation = models.CharField(max_length=255) about = RichTextUploadingField() def __str__(self): return self.name def image_tag(self): if self.image.url is not None: return mark_safe('<img src="{}" height="50"/>'.format(self.image.url)) else: return "" class StaffSocialMedia(models.Model): about_staff = models.ForeignKey(AboutLeader, on_delete=models.CASCADE) sm_name = models.CharField(max_length=255) sm_url = models.CharField(max_length=255) def __str__(self): return self.sm_name admin.py from django.contrib import admin from home import models from home.models import * class AboutStaffSocialMedia(admin.TabularInline): model = StaffSocialMedia extra = 3 class AboutStaffAdmin(admin.ModelAdmin): list_display = ['name', 'designation', ] readonly_fields = ('image_tag',) inlines = [AboutStaffSocialMedia] admin.site.register(AboutStaff, AboutStaffAdmin) admin.site.register(StaffSocialMedia) views.py from django.shortcuts import render from .models import * def about(request): about_staff = AboutStaff.objects.all() staff_social_media = StaffSocialMedia.objects.all() context = {"about_staff": about_staff, "staff_social_media": staff_social_media} return render(request, "about.html", context) about.html {% extends "base.html" %} {% load static %} {% block title %}About{% endblock %} {% block body … -
Serbian latin django translation
For some reason Serbian latin is not working properly on the server. I add the new language for translation. It is then created in /locale/ folder. python manage.py makemessages -l sr_Latn Locally everything looks fine I go to http://localhost:8000/translate/ .There I see the new add language in 2 rows sr_LATN and sr_latn Locally I translate what I want and it works. But the problem comes on the server. On the server it is not recognized, I don't see it visually so I can’t not translate it. I see .po and .mo file exists in folder but it is not not visible under www.myswebsite.com/translate/ . I looked at this post on stackoverflow but didn't help me Django 1.9 sr_Latn locale doesn't work and I looked the the ticket of Django official documentation. https://code.djangoproject.com/ticket/10663 I use Django = "==1.7.8" and django-cms = "==3.0.12" Did anyone have similar experience? -
Enable default help_text in PasswordChange django
after I created a customize authenticate form in django the help text for new password could not be use anymore I need to write a customize help text also inside the forms of passwordchange. is there a way to use the default one? here is my code of passwordchangeview: class ChangePassword(LoginRequiredMixin, PasswordChangeView): template_name = 'content/changepassword.html' form_class = ChangePasswordForm success_url = '/changepassword/' here is my form: class ChangePasswordForm(PasswordChangeForm): error_messages = { 'password_mismatch': 'Password mismatch.', 'password_incorrect': 'Password incorrect.' } old_password = forms.CharField(label = 'Old Password', widget = forms.PasswordInput( attrs = { 'class': 'form-control', 'placeholder': 'Old Password' }), max_length = 50) new_password1 = forms.CharField(label = 'New Password', widget = forms.PasswordInput( attrs = { 'class': 'form-control', 'placeholder': 'New Password' }), max_length = 50, help_text = ''' <ul> <li></li> </ul> ''') new_password2 = forms.CharField(label = 'Confirm New Password', widget = forms.PasswordInput( attrs = { 'class': 'form-control', 'placeholder': 'Confirm New Password' }), max_length = 50) so instead of writing a help_text, i will just use the django default help_text. -
Which is the best Shopping cart Module in Django?
I am developing an eCommerce website and i have done all work from my admin panel, all products, category, blog work has been finished. Now I want to add cart functionality in my website, please let me know if there are any premade Cart functionality (or module) in Django, I want to implement in my website. -
Django rest framework foreign key pointing to different tables
I am using django rest framework, Models and serializers. I have three different types of tables. chatrequest videorequest audiorequest I have another table notifications where I will be storing notification related to that table It has the following fields message request_id (Foreign key) request_type (chatrequest, videorequest, audiorequest) What I am trying to do is that based on request_type, request_id details get fetched from the database. Notification model id = models.AutoField(primary_key=True) message = models.TextField(blank=True, null=True) user = models.ForeignKey(User,related_name ='users_id', on_delete=models.CASCADE,blank=True, null=True ) request_type = models.SmallIntegerField(blank=True,null=True) request_id = models.IntegerField(blank=True, null=True) Notification serializer class NotificationSerializer(serializers.ModelSerializer): user = userSerializer() class Meta: model = Notification fields = ('id', 'user', 'message', 'request_id', 'request_type') -
I need to know how to structure my Django models to work for a Django Pool Reservation Website
Im in the process of creating a django pool reservation website for use at an apartment complex. I've already created the main templates and views which include the main page that shows the status of the pool time-slots the next day (as well as the logged on user's statistics for how they use the pool), the create reservation page (that shows how many current reservations there are for the time slot they are interested in), the reservation confirmation page, and the change reservation page. I've gotten to work on making the models for the project, but firstly, I wrote the logic in plain python so that it would make sense for me before putting it into a django format. What I Need Help Solving: I need to know what I need make my logic fit for how django operates - I also want to know if you can use data structures in django (like object classes etc.). Can you also tell me how I need to structure my app and models models to work with my logic and work with the views. A link to my code on github is attached below: Bloom Reservations Thanks for any help that comes … -
Django redirection after successful login
Is it possible that after successful login first redirect to a new page and not to that url witch is in the next parameter (ex. http://localhost:8000/ro/login/?next=/ro/exam/3/). So what I exactly want is after a successful login first redirect to that url what I provided in LOGIN_REDIRECT_URL, and also I want to keep somehow the next url ( http://localhost:8000/ro/login/?next=/ro/exam/3/), because after the user clicks somewhere I want to redirect him to the target. -
Django - How to get user file path?
I have to accept excel file from user and perform some operation on it using pandas dataframe. So to load the dataframe using pandas I need to pass the path of file: fd =pd.read_excel('C:\users\chan\desktop\abc.xlsx') In django I am trying to use HTML input type file to get the location of file, so that I can pass it in pandas but unable to get file location in python variable. I tried below code but it's printing data on html page instead of storing it's path in variable: HTML: <html> <head> <title>Coordinates to Bounding Box</title> </head> <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" /> <input type="submit" value="Upload" /> </form> {% block content %} <h3>File uploaded successfully</h3> {{file.name}} </br>content = {{contentOfFile}} {% endblock %} </body> </html> Django's views.py from django.shortcuts import render from django.conf.urls.static import static from django.http import HttpResponse # Create your views here. def index(request): if request.method == 'POST': file1 = request.FILES['file'] contentOfFile = file1.read() if file1: return render(request, 'index.html', {'file': file1, 'contentOfFile': contentOfFile}) return render(request,'index.html') Is there any way I can get the path of excel file or load the excel data in pandas dataframe? -
How to bypass current error in data tuple in send mass mail?
I am working on a bulk mailing platform using Django send_mass_mail function. Everything worked perfectly. But the problem I am facing is, I have nearly 500 recipients, and if one recipient fails to receive mail (recipient side errors like, improper mail address provision), the whole function stops immediately. How to send the next mail, if current data tuple has errors in data. I think the question is straight and need no code examples. Since i followed straight from the Django Docs -
Debbuger not working while running python program
When i am trying to debug my django code, the debbuger doesn't stop at any breakpoints. And after sometime all of a sudden it starts working. I am getting this problem in both pycharm and vs code. Are there any settings needed to be changed or is some other things going wrong -
How to add a logo to django admin page
I know that I can change any text on the Django admin page but I don't know how to add a logo to the admin page.Here -
save multiple values from a django template
I have a Django template that asks for # of players using a form. I pass this variable to the views.py which renders to another template (including the # of players). The next template shows the same # of input fields to get the name of the players. Here’s the for loop to iterate through the number of players -- <form action="name_players" method="POST" class="form-inline"> {% csrf_token %} {% for loop_time in numbers %} <input name="name_players[]" type="text" class="form-control mb-2 mr-sm-2" id="inlineFormInputName2" placeholder="name of player..."> {% endfor %} <button type="submit" class="btn btn-primary mb-2">Submit</button> </form> How should I go about saving these names in an array and returning to the views.py file and then save to a database OR is there a way to do that directly in the template file. thank you! -
Django date wont work on full calendar date
Hello I have this js script data is coming from django this code below works properly on hardcoded dates but when I tried to dynamic it via object.created but when I save this say on Monday and the date today is Friday the output on pdf is on the friday not in monday. <script> $(document).ready(function() { $(function() { $('#calendar').fullCalendar({ defaultView: "agendaWeek", defaultDate: "2019-04-19", slotDuration:"00:30:00", allDaySlot: false, columnFormat: "ddd", header: false, minTime: "7:00:00", maxTime: "20:00:00", editable: true, selectable: true, eventOverlap: false, header: { left: "", center: "", right: "", }, events: [ {% for subsched in schedules %} {% for sched in subsched.scheduling_set.all %} { title: '{{subsched.subject.code}} ({{sched.subject_schedule_type|title|slice:"3"}})', {% if sched.day|slugify == '0' %} start: ( '2019-04-14 {{sched.time_from|date:"H:i:s"}}' ), end: ( '2019-04-14 {{sched.time_to|date:"H:i:s"}}' ), {% elif sched.day|slugify == '1' %} start: ( '2019-04-15 {{sched.time_from|date:"H:i:s"}}' ), end: ( '2019-04-15 {{sched.time_to|date:"H:i:s"}}' ), {% elif sched.day|slugify == '2' %} start: ( '2019-04-16 {{sched.time_from|date:"H:i:s"}}' ), end: ( '2019-04-16 {{sched.time_to|date:"H:i:s"}}' ), {% elif sched.day|slugify == '3' %} start: ( '2019-04-17 {{sched.time_from|date:"H:i:s"}}' ), end: ( '2019-04-17 {{sched.time_to|date:"H:i:s"}}' ), {% elif sched.day|slugify == '4' %} start: ( '2019-04-18 {{sched.time_from|date:"H:i:s"}}' ), end: ( '2019-04-18 {{sched.time_to|date:"H:i:s"}}' ), {% elif sched.day|slugify == '5' %} start: ( '2019-04-19 {{sched.time_from|date:"H:i:s"}}' ), end: ( … -
django.db.utils.OperationalError: FATAL: database "library" does not exist
I'm trying to connect my project with postgres database using docker.It works fine when I use default postgres setup like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } but when i try to create a database using postgre admin and want to use it in my django project it shows the error. my Dockerfile: Dockerfile # Pull base image FROM python:3.7 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ the settings.py for databse DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'library', 'USER': 'postgres', 'PASSWORD': 'my_password', 'HOST': 'db', 'PORT': 5432 } } and the docker-compose.yml docker-compose.yml version: '3.7' services: db: hostname: db image: postgres:11 environment: - POSTGRES_DB=library - POSTGRES_USER=postgres - POSTGRES_PASSWORD=my_password volumes: - postgres_data:/var/lib/postgresql/data ports: - "5432:5432" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db volumes: postgres_data: