Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to lock same time slot multiple times in django?
We building a Django application where we want to manage time slots such that where multiple user can use same time slot to order their product. On the contrary a delivery truck can ship product up to 9 times per day (9:30 AM, 10:30AM, 12:30 PM, 02:30PM, 04:00PM, 06:00PM, 08:00PM, 09:00PM, 12:00AM) . If we have 2 trucks then we can deliver our product in 9:30 AM twice in a day. Time Slots for per day delivery. We manage to lock/reserve/order the date only one time. We want to Reserve our current time with current date also all of the date of month dynamically. We can’t manage to order same time slot multiple times. How we can implement multiple order in same time slot? class OrderDashboard(models.Model): time = models.TimeField() reserved = models.BooleanField(default=False) class Reserved(models.Model): time = models.TimeField() date = models.DateField() # @login_required() def order_fuel(request): from django.db.models import Q date_time = OrderDashboard.objects.all() reservation = False if request.method == "POST": time = request.POST.get('time') date = request.POST.get('date') reserved = Reserved.objects.filter(Q(time=time) & Q(date=date)) if reserved: reservation = True print(reservation) return HttpResponse('Time already reserved!') else: reserved_ins = Reserved( time=time, date=date ) reserved_ins.save() return HttpResponse('Order confirmed') dict = {'date_time': date_time, 'reservation': reservation} return render(request, 'Uftl_App/orderfuel.html', context=dict) -
Django ajax pagination (without using JQuery), to update a portion of a page
I am using Django 3.2 I have a ListView derived CBV that returns a paginated list of objects. The list of objects is shown in a small portion of the main (heavy) page, and I want to update only the portion of the page that shows the list. For reasons I won't go into here, I can't seem to use jQuery (basically, I am using onclick() and if I define the onclick callback function within $().ready({}); then the function is not defined by the time it is called) - so I have to define the function using POJS (Plain Old JS). Here is a snippet of what I have so far: Javascript func in base template: function doIt(url, token, pagenum) { fetch(`${url}?page=${pagenum}`, { method: 'post', headers: { 'Accept': 'application/json, text/html, */*', 'Content-Type': 'text/html', 'X-CSRFToken': token }, //body: JSON.stringify({a: 7, str: 'Some string: &=&'}) }).then(res => res.text()) .then(res => console.log(res)); } /path/to/pagination-template # Test line <li class="page-item"><a class="ajax-pager page-link" onclick="doIt('{{ request.build_absolute_uri }}{{ object.get_absolute_url }}', '{{csrf_token}}', {{ i }});" href="#"</a></li> When I click on the anchor tag, a POST request is issued, and the server (i.e. Django) responds with a 200 OK status. However, nothing is logged on my console. Note: I … -
Upload file to Django backend by reading the file path from local machine
I am new to django and trying to get below scenario working. Can someone please guide me? Upload a master file which has absolute path of multiple files from my local machine or client machine which I want to process. In Django template, within Javascript, I am trying to read each of the file location from my local system and upload it to Django backend server. Is there any simple way to upload the file in Django by using the absolute path of a file from client machine? -
Django admin static files magically served
I just setup a simple Django website, and commented out path('admin/', admin.site.urls), with STATIC_URL = '/static/' in the settings.py, When I goto http://localhost:8100/static/admin/css/nav_sidebar.css, I see this static file is magically severed. What's really going on? I have not setup the static url serving in my urls.py yet? -
How to load a Jupyter Notebook for a Django project on a remote server?
I would like to run a Jupyter Notebook on a remote server where my Django project is hosted, but after I start the Notebook I'm unable to load the web page in a browser. When Jupyter Notebook is started localy I can easily load the page http://127.0.0.1:8888/?token=*** , but when started remotely with SSH the page http://IP_ADDRESS:8888/?token=*** doesn't load. What is the reason for this ? From my understanding it is supposed to start a webserver on port 8888 on the remote server. My Django project use Uvicorn server on port 8000. (env) zzz@ubuntu-2cpu-4gb-de-fra1:/var/www/capital$ python manage.py shell_plus --notebook [I 21:43:44.221 NotebookApp] Serving notebooks from local directory: /var/www/capital [I 21:43:44.222 NotebookApp] The Jupyter Notebook is running at: [I 21:43:44.222 NotebookApp] http://localhost:8888/?token=3cce26532860d8f8db0e6e27d945168a90b0f48cec912152 [I 21:43:44.222 NotebookApp] or http://127.0.0.1:8888/?token=3cce26532860d8f8db0e6e27d945168a90b0f48cec912152 [I 21:43:44.222 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [W 21:43:44.225 NotebookApp] No web browser found: could not locate runnable browser. [C 21:43:44.225 NotebookApp] To access the notebook, open this file in a browser: file:///home/zzz/.local/share/jupyter/runtime/nbserver-19178-open.html Or copy and paste one of these URLs: http://localhost:8888/?token=3cce26532860d8f8db0e6e27d945168a90b0f48cec912152 or http://127.0.0.1:8888/?token=3cce26532860d8f8db0e6e27d945168a90b0f48cec912152 -
Represent data consumed from 3rd party api in django with chart.js
I am working on a website that shows you the vitamins in the food I am using a 3rd party api that provides the data I need the problem is I can't find a way to represent this data in chart.js, what I am basically trying to do is get the data from the api then extract the labels and the amount that I need from the data but i don't know how to pass it to the template and be able to actually use it in my javascript file. this is the code I am currently trying to make work with it currently f**ed up cuz I keep adding and deleting to it but I hope you get what I am trying to do views.py def food_info(food_id, amount): info = requests.get( f'{base_url}/food/ingredients/{food_id}/information?amount={amount}&unit=grams&apiKey=') food = info.json() nutrients_data = food['nutrition']['nutrients'] labels = [nutrient['title'] for nutrient in nutrients_data if nutrient['amount'] > 0] return JsonResponse(data={'labels':labels}) def search_food(request): if request.method == 'POST': name = request.POST.get('name') amount = request.POST.get('amount') result = requests.get( f'{base_url}/food/ingredients/search?query={name}&addChildren=false&number=1&apiKey=') result = result.json() food_id = result['results'][0]['id'] food_info(food_id,amount) return render(request, 'food/test.html') class FoodChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = ['Cholesterol', 'Saturated Fat', 'Phosphorus', 'Poly Unsaturated Fat', 'Fiber'] … -
Django Custom Login Form Submission Does Not Go to LOGIN_REDIRECT_URL or Display Errors
I am trying to create a custom login form in Django 3.2. When I use a standard boilerplate login form using {{ form.as_p }}, a successful login takes me to the LOGIN_REDIRECT_URL defined in settings.py. An unsuccessful login shows the errors above the form. But when I use a custom login form, a successful login takes me right back to the login page. I looked at the generated HTML for the working form but cannot tell what I am doing wrong. An unsuccessful login acts the same way and doesn't show any errors. What am I missing here? registration/login.html (works as expected) <html> <body> <h1>Log In<h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> </form> </body> </html> registration/login.html (does not work) <html> <body> <h1>Log In<h1> <form method="post"> {% csrf_token %} <div class="mb-3"> <label for="id_username">Email</label> <input id="id_username" class="form-control form-control-lg" type="email" name="email" placeholder="Enter your email" /> </div> <div class="mb-3"> <label for="id_password">Password</label> <input id="id_password" class="form-control form-control-lg" type="password" name="password" placeholder="Enter your password" /> </div> <small> <a href="{% url 'password_reset' %}">Forgot password?</a> </small> <button type="submit">Log In</button> </form> </body> </html> urls.py (at project level) urlpatterns = [ path('auth/', include('django.contrib.auth.urls')), path('', include('app.urls')) ] -
How to make application in django work? Runnig a python script like class in django
I'm bit new with django and I'm lost, I don't know what to do. I'll explain what I want, maybe you can help me. I want to create a web page on my site where you input your data and based on your data you get created a excel template which you download. Most basic, you input name of rows and columns and you download an excel document. Here is what I have tried so far... I have a my_django folder and my_app folder, in my_app I'm trying to create an app to create templates. This is my_app/views.py from django.shortcuts import render from django.http import HttpResponse from .forms import TemplateForm import xlsxwriter from xlsxwriter import workbook def home(request): return render(request, 'my_app/home.html') def create_template(request): return render(request, 'my_app/create_template.html') class CreateMyWebTemplate(): def create_template(doc_name, name_sheet, years, name_columns): file = xlsxwriter.Workbook(doc_name + '_template.xlsx') worksheet_data = file.add_worksheet() worksheet_data.write_row(0, 1, years) worksheet_data.write_column(1, 0, name_columns) file.close() return file This is my_app/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='my-home'), path('create-template/', views.create_template, name='my-create-template'), ] This is my_app/template/my_app/create_template.html {% extends "my_app/base.html" %} {% block content %} <div class="create-template-box"> <form action="/"> <h1>Create your template</h1> <div class="item"> <p>Document name</p> <div class="name-item"> <input type="text" name="doc_name" placeholder="Input document … -
Overriding get_queryset, but get empty result set
So I have a database of books, and I want to search it based on filters and keywords so I've overridden the get_queryset method in my BookSearch view: class BookSearch(generics.ListAPIView): serializer_class = ProductDetailViewSerializer model = ProductDetailView def get_queryset(self): queryset = None categories = self.kwargs['categories'].rstrip() keywords = self.kwargs['keywords'].rstrip() if isinstance(categories, str) and isinstance(keywords, str): book_filter = BookFilter(categories) sql = self.get_sql(categories, keywords, book_filter) queryset = ProductDetailView.objects.filter( id__in=RawSQL(sql, book_filter.params) ) message = f"{queryset.query}" log_to_file('BookSearch.log', 'BookSearch.get_queryset', message) return queryset That log_to_file call logs the query that django uses, which I've abbreviated here but is as follows: SELECT `jester_productdetailview`.`id`, `jester_productdetailview`.`isbn`, `jester_productdetailview`.`title` FROM `jester_productdetailview` WHERE `jester_productdetailview`.`id` IN ( select id from jester_productdetailview where ( authors like '%Beatrix%' or illustrators like '%Beatrix%' or title like '%Beatrix%' ) ) ORDER BY `jester_productdetailview`.`title` ASC If I run that query in my database manually, I get 186 rows: '119371','9780723259572','A Beatrix Potter Treasury' '130754','9780241293348','A Christmas Wish' '117336','9780241358740','A Pumpkin for Peter' ... To get the query above, I call the view through the API, yet by the time the queryset is returned, there are no results ??? http://127.0.0.1:8000/api/book-search/{"filter": "all"}/Beatrix/ returns [] -
Connect remote mysql to django
i have a MySQL database in cpanel and i want to connect my django project to this database when i try to connect it it show a message that i can't connect to localhost but i don't want to connect to localhost i want to connect to my remote database in cpanel. i have tried to connect to (MySQL workbench) and it connected without a problem. This is a picture of my settings and error -
django - ajax - call python function from jquery/ajax
I'm working with Django to create a small website. in this project, I have some DateTime fields. I would use ajax (via another button) to set up the UTC date keeping in mind the solar time and daylight saving time. I created a python function which computes the hour shift. I would recall that function in the ajax code. How can I do it? -
Trying to run code in Google Cloud, getting Server 502 when accessing Django
I'm building a simple login page. You can log in using a Django account, or using Google Sign-In. I am trying to verify that you can log in using a Django account first. It deploys correctly, and I can access the site properly. But when I access Django /admin and key in the login credentials, aside from the fact that loading takes forever, I keep getting Server 502 Bad Gateway The documentations only vaguely mentions all the way at the bottom that app.yaml might be configured incorrectly but I'm not experienced enough to tell which part isnt. # [START runtime] runtime: python env: flex entrypoint: gunicorn -b :$PORT [myproject.wsgi] beta_settings: cloud_sql_instances: [instance]:asia-east2:[project] automatic_scaling: min_num_instances: 1 max_num_instances: 1 max_concurrent_requests: 80 resources: cpu: 1 memory_gb: 0.5 disk_size_gb: 10 runtime_config: python_version: 3 # [END runtime] -
After I pull a dockerized django project from the hub, how should I run it? I used docker compose
I am working on docker for the first time. I created a docker container of a Django application using docker-compose. Furthermore, I pushed the image to hub. Now, how should I run the image after pulling it back? What commands should I use? Where will the "docker-compose up" command go? -
Bad gateway when deploying Django app with awsebcli
I was using this AWS guidelines to deploy Django application to AWS EB using awsebcli. Deploying a Django application to Elastic Beanstalk But after I finished all the steps i got "502 Bad Gateway" error and I don't see any environment created in AWS console, but when I run eb status it looks like environment was created. eb status Environment details for: django-test-env Application name: django-test Region: us-west-2 Deployed Version: app-210819_194308 Environment ID: e-2h9nu62f8t Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 3.8 running on 64bit Amazon Linux 2/3.3.4 Tier: WebServer-Standard-1.0 CNAME: django-test-env.eba-3i3hqgjc.us-west-2.elasticbeanstalk.com Updated: 2021-08-19 18:43:34.097000+00:00 Status: Ready Health: Red The only thing I did different was that I used Python 3.8 at Deploy your site with the EB CLI Step 1. Also I had to create access key ID and secret access key, to be able to login to awsebcli. -
Heroku: user status banned from creating email addons on apps
I deployed a Django application on Heroku, which uses email verification during signup. I wanted to use Sendgrid addons, unfortunately I am getting this error: Item could not be created.... **User- user status banned** -
DJANGO - Display currently logged in users count
I need help with returning number of currently logged in users to my template in django. def get_context_data(self, **kwargs): ago5m = timezone.now() - timezone.timedelta(minutes=10) active_users = Profile.objects.filter(login_time__gte=ago5m).count() context = super().get_context_data(**kwargs) context.update({ 'active_users': active_users, }) return context I have tried using the attached code as a method within my class-based view in my project but it counts each authenticated user and decrements the count after 10 minutes (Note also: when I remove the timedelta value of 10, the code doesn't even count the authenticated users at all). how can I fix this problem? Note: "login_time" is declared in my models.py file as follows: -login_time = models.DateTimeField(auto_now=True, null=True) -
How to convert pandas datetime64 into something that can be recognized as DateField by Django?
When I load an Excel using pandas, the column containing dates was correctly identified as datetime64 excel_table = pd.read_excel(path, sheet_name=ws_name, header=2) print(excel_table['Start Date']) # output: 0 2001-01-31 1 2001-03-02 2 2001-07-23 3 2001-07-25 4 2002-03-11 ... Name: Start Date, Length: 11056, dtype: datetime64[ns] Then, I wrote excel_table to a sqlite3 database: excel_table.to_sql(table_name, cols_to_use, index=False) When I inspect the columns using PRAGMA table_info(TABLENAME), I got this: ... 11|Start Date|NUM|0||0 ... Shouldn't it be TIMESTAMP rather than NUM? Then, I generate a model class using Django's inspectdb method that gave me this: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models class TableName(models.Model): start_date = models.TextField(db_column='Start Date', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. This … -
Amount of queries to database in Views using Django
My question is regarding best practices for querying a database in a View using Django. I want a daily count of reservations for the past 7 days. Is it okay to have something like this? (below) count_day_1 = len(Reservations.objects.filter(date=TODAY_DATE).filter(is_reserved=True)) count_day_2 = len(Reservations.objects.filter(date=DATE_TODAY_MINUS_1).filter(is_reserved=True)) count_day_3 = len(Reservations.objects.filter(date=DATE_TODAY_MINUS_2).filter(is_reserved=True)) count_day_4 = len(Reservations.objects.filter(date=DATE_TODAY_MINUS_3).filter(is_reserved=True)) count_day_5 = len(Reservations.objects.filter(date=DATE_TODAY_MINUS_4).filter(is_reserved=True)) count_day_6 = len(Reservations.objects.filter(date=DATE_TODAY_MINUS_5).filter(is_reserved=True)) count_day_7 = len(Reservations.objects.filter(date=DATE_TODAY_MINUS_6).filter(is_reserved=True)) Or does having that Reservations.objects.filter() in there 7 times ping the database 7 times? If the above way isn't recommended, should I set it up something like this instead? (below) data = Reservations.objects.filter(is_reserved=True) for item in data: if item.date == TODAY_DATE: print(item.date) if item.date == DATE_TODAY_MINUS_1: print(item.date) (...so on and so forth) Any advice would be great. Thanks! -
How to filter an object witch has one of the two foreign key relation in Django one to many relationship
I have city and routes models class City(LocationAbstractModel): name = models.CharField(max_length=255) def __str__(self): return self.name class Route(BusAbstractModel): leaving_from = models.ForeignKey(location_models.City, on_delete=models.CASCADE, related_name='leaving_from') destination = models.ForeignKey(location_models.City, on_delete=models.CASCADE, related_name='destination') distance = models.IntegerField(null=True, blank=True) prices = models.ManyToManyField(carrier_models.Carrier, through="RoutePrice") crossing_cities = models.ManyToManyField(location_models.City, blank=True) def price(self, carrier_id): return self.routeprice_set.filter(carrier_id=carrier_id).order_by('created_at').first().price def __str__(self): return self.leaving_from.name + " -> " + self.destination.name How can I query only cities which has one of the relation in routes model. I want to filter cities which has either leaving_from or destination relation ship. I have tried models.City.objects.filter(Q(route__leaving_from__isnull=False) |Q(route__destination__isnull=False)).distinct() but it is only returning cities which has relation on both leaving_from and destination. How can I Filter Cities which has one of the relationships -
django fails to install psycopg2
I'm running Django 3.2 (Python 3.8.2) in a virtual environment on my Windows 10 PC and I'm trying to install psycopg2. I've successfully used postgresql and psycopg2 on this PC before, in a different virtual environment. However, this time I'm getting errors. I've tried: pipenv install psycopg2-binary==2.9.1 pipenv install psycopg2==2.9.1 pipenv install psycopg2 Each attempt ends with the error: raise InstallationError( pipenv.patched.notpip._internal.exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in C:\Users\...\psycopg2... -
Choosing a Main Image in a Foreign Key
I have the following two models: class Event(models.Model): title = models.CharField(max_length=250) description = RichTextField() start_date = models.DateField() start_time = models.TimeField() end_date = models.DateField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) location = models.CharField(max_length=100) volunteers = models.PositiveIntegerField(default=0) sdgs = models.ManyToManyField(SDG) def __str__(self): return f'{self.title}' class EventPhoto(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) photo = models.ImageField(upload_to='events/photos') A single Event object can contain multiple photos, maybe 1, maybe 10 or maybe 100. I am using the following code inside of my admin.py file. class EventPhotosInline(admin.StackedInline): model = EventPhotos @admin.register(Event) class EventAdmin(admin.ModelAdmin): inlines = [EventPhotosInline,] The above code allows me to add EventPhoto objects while I am adding a new event in the admin dashboard. My question is, how would I go about choosing on of the many photos to be the main photo of the event? I could of easily created an image field inside the Event model with the name main_photo, but in the future if I have to change the main photo I have to upload a new one, all I need is to just use one of the many uploaded images as my main photo. How would I go about creating something similar to what I want?! I also tried adding a boolean field … -
Django: How to solve several Foreign key relationship problem?
I'm currently learning Django and making electronic grade book. I am completely stuck after trying everything, but still cannot solve the problem. I will explain in detail and post all the relevant code below. I need to have two url pages "class_students" and "teacher_current". The first page is for the teacher to see the list of students of a certain class. The table on this page has "action" column. In every cell of this column there is View button, so that the teacher could be redirected to "teacher_current" page and see the list of current tasks, given to a certain student. On this page there is a "Mark" column, its cells may contain EITHER mark given to this student with link to another page to update or delete this mark OR "Add mark" link to add mark on another page. Here comes the problem: everything works correctly, except the thing that each mark is related to a Task class via Foreign key and NOT to a Student class. So every student of the same class has the same marks for the same tasks. But it certainly won't do. Here is all my relevant code: 1) views.py models.py urls.py: https://www.codepile.net/pile/qkLKxx6g 2) … -
show list in django without html file?
i have 2 models but i want to show name of artist in my output class Musician(models.Model): name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): name = models.CharField(max_length=100) artist = models.ForeignKey(Musician, on_delete=models.CASCADE) num_stars = models.IntegerField() i want to show musician name by HttpResponce funcction class Musician_list(Musician ,Album ): def get(self, request): qury= Musician.objects.all().values_list("name").order_by("name") return HttpResponse(qury) but this code dont show any things please help me. -
CORS Issues after adding headers field to axios when making a GET request
I am using Django REST for my API/Back end. Here is my python code: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', #'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000" ] CORS_ORIGIN_WHITELIST = [ "http://localhost:3000", "http://127.0.0.1:3000" ] On my React JS front end: listItems = async () =>{ let fetchedItems = await axios.get("http://localhost:8000/api/shipments/list/", {headers: {accessToken: this.props.token, "Access-Control-Allow-Headers" : '*'}}); } I did not get any CORS errors when I had listItems without the headers part: listItems = async () =>{ let fetchedItems = await axios.get("http://localhost:8000/api/items/list/"}); } However, I need to pass the accessToken in the request's header. Here is the error that I am getting: Access to XMLHttpRequest at 'http://localhost:8000/api/items/list/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field accesstoken is not allowed by Access-Control-Allow-Headers in preflight response. What is the reason behind having such CORS issues, what's the best way to fix it ? -
Remove templates from Django
We are using Django solely as backend and not utilizing its template system while we are developing our code. Current set up that we have points templates to the folder where our front end is located in dist/ui. Maybe in production mode when we could build actual combined binaries and want to serve them from the server it could be useful but in the development mode it often causes issues when there are some inconsistencies in the dist/ui folder with the folder structure of the development folder. Is it possible to avoid that behavior? How could we prevent Django from loading any templates at all using it solely as a backend data layer that interacts with a database? We tried just deleting paths and/or template set ups in settings.py but it didn't help: STATIC_ROOT = os.path.join(BASE_DIR, 'ui/dist') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ os.path.join(BASE_DIR, 'ui/dist'), os.path.join(BASE_DIR, '/data'), ], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]