Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django throttling problem when use ManualAPIKey
I am using Django rest API, in one of the views I use manual key authentication when I activate throttling for that view, the request from a same IP address with different API_key count as from same user and reject after several times. For example: I set the rate 12/minute. user1 from a IP 20.40.5.6 send 10 request in a minute, and user2 from a IP 20.40.5.6 send 10 request in a minute. They both get 429 error until next minute. If these user send request from different IPs, there are no problems. class HasManualAPIKey(BasePermission): def has_permission(self, request, view): key = request.META["HTTP_AUTHORIZATION"].split()[1] keys = MyUser.objects.values_list('key', flat=True) if key in keys: return True else: return False class MyUserRateThrottle(UserRateThrottle): rate= '12/minute' class MyUserView(APIView): permission_classes = [HasManualAPIKey] throttle_classes = [DeviceRateThrottle] -
Django Rest Framework : how to specify a serializer to use different fields to create, update and get
I have a doubt with the serializers and so far I have not been able to solve it. I explain the doubt with the following example: I have a User model and this model has the following attributes: username, password, first_name, last_name, age, gender. I also have a serializer, which is called UserSerializer. The UserSerializer should do the following: When inserting information into the database, UserSerializer should only take into account the fields: username, password, first_name, last_name. When retrieving information from the database, UserSerializer should only take into account the fields: age, gender. When updating the database information, UserSerializer should only take into account the fields: password. My solution: class UserSerializer: class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'first_name', 'last_name'] class UserGetSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['age', 'gender'] class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['password'] Question: The question: is there any way to synthesize the three serializers into one, or what is the best solution for this problem? Thank you very much. -
CORS error appears when I Upload multiple files at once to S3 Bucket with boto3
I have a question about S3 upload, I use boto3 library in python to connect to S3. def get_client(): return boto3.client('s3', aws_access_key_id = 'AWS_ACCESS_KEY', aws_secret_access_key = 'AWS_SECRET_KEY') My Multiple upload file in below for item in img_files: file_type = '' uuid_key = uuid.uuid4() fs = FileSystemStorage() filename = fs.save(f'{S3_TEMP_FOLDER}{uuid_key}-{item.name}', item) file_o_name, file_o_ext = os.path.splitext(filename) if file_o_ext.lower() in ['.jpg', '.png', '.jpeg']: file_type = 'image' else: file_type = 'video' uploaded_file_path = fs.path(filename) try: s3_client.upload_file(uploaded_file_path, bucket_name, f'{folder_key}/{uuid_key}-{item.name}', ExtraArgs={'ACL': 'public-read'}) uploaded_data = { "file_name": item.name, "file_key": f'{folder_key}/{uuid_key}-{item.name}', "bucket_name": bucket_name, "folder_id": get_folder_id.id, "created_by": request.user.username, "updated_by": request.user.username, "bucket_id": bucket.id, "file_type": file_type } S3FileManagement.objects.create(**uploaded_data) except Exception as e: logger.error({'message': str(e)}) logger.error({'message': S3_FOLDER_MESSAGE['S3_FILE_UPLOAD_FAILED']}) return Response({'message': S3_FOLDER_MESSAGE['S3_FILE_UPLOAD_FAILED']}, status=status.HTTP_400_BAD_REQUEST) When I upload about 5-10 files at a time, the upload process is no problem, but when I upload > 30 files, there will be some files with 502 - CORS errors. In settings python, I was allows CORS CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOWED_ORIGINS = [ '..{url}..vercel.app', ] CSRF_TRUSTED_ORIGINS = [ '..{url}..vercel.app', ] Additionaly, the python backend I'm using aapanel. Any more additional settings needed? Thanks. -
Django FormView and ListView multiple inheritance error
Problem I have a AccesCheck Mixin, and view named ListFormView that inherits AccessCheck, FormView and ListView to show list and create/update Worker objects. But when I try to add new data by POST method, django keeps returning Attribute Error : Worker object has no attribute 'object_list' error. What is more confusing to me is that whole ListFormView is duplication of another class based view that is used in another app, and the original one is running without any problems. I've doublechecked all my codes and still have no clue to fix this problem. [AccessCheck] class AccessCheck(LoginRequiredMixin, UserPassesTestMixin, View): def test_func(self, *args, **kwargs): access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])] return self.request.user.is_superuser or selr.request.user.id in access def handle_no_permission(self): return redirect('index') get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['shop'] = Shop.objects.get(shop_id = self.kwars['shop_id']) return context [ListFormView] class Worker(AccessCheck, FormView, ListView): template_name = 'my_template_name.html' context_object_name = 'workers' form_class = WorkerForm success_url = './my_url' def form_valid(self, form): data = form.save() return super().form_valid(form) def get_queryset(self, *args, **kwargs): return Worker.objects.filter(shop_id = self.kwargs['shop_id']) -
django migration error on changing FK field to regular field
Part of my model looked like this, initially. class RealTimeLocation(models.Model): name = models.CharField(max_length=80) latlng = models.PointField(default=None) class CabLog(models.Model): location = models.ForeignKey(RealTimeLocation, on_delete=models.CASCADE, related_name='cablog_locations') Then i thought, no need for an FK field, so i changed the fk field to a Point field. class RealTimeLocation(models.Model): name = models.CharField(max_length=80) latlng = models.PointField(default=None) class CabLog(models.Model): location = models.PointField()// 'python manage.py makemigrations ' no issues, but on migrate i'm getting error. .django.db.utils.ProgrammingError: column "location_id" of relation "myapp_cablog" does not exist. I tried adding a null=True option to pointfield, deleting the migrate-scripts and redo it many times, no avail. SO before i completely fake-migrate the entire project and startover, do anybody have any solutions for this. I already got some data in DB, so i really don't want to do that. Thanks. -
Is it possible to create an empty csv file in Django database?
I am wondering if it is possible to create an empty csv file in Django database. Basically what I am trying to do is to allow the user to upload a text file as TextUpload model object, then run the code in the backend to process the text file and to save it as ProcessedTextToCsv model object. My views.py code looks something like this: def upload_view(request): form = TextUploadsModelform(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = TextUploadsModelform() ProcessedTextToCsv().save() I am wondering if here I can create an empty csv so I can use file_name.path as argument in the function below processTextToCsv(TextUploads.objects.latest('uploaded').file_name.path,ProcessedTextToCsv.objects.latest('uploaded').file_name.path) return render(request, 'main_app/example.html',{'form': form}) -
Dockerized Django app not running in Azure
I'm trying to deploy a Django app dockerized to Azure App Service, the app seems to run well on my local environment http://localhost:8000/, for this I use docker run -p 8000:8000 myapp.azurecr.io/myapp:latest. But when I try deploying the app to Azure it doesn't work. This is my dockerfile: FROM python:3.8.3-slim ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN apk update \&& apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev freetype-dev libxml2-dev libxslt-dev build-base \&& pip install --upgrade pip psycopg2-binary COPY ./requirements.txt ./ RUN pip install -r requirements.txt COPY ./ ./ EXPOSE 3000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] And these are the logs I receive from Azure 2022-11-25T00:33:44.857803391Z Performing system checks... 2022-11-25T00:33:44.857871092Z 2022-11-25T00:33:48.431821909Z System check identified no issues (0 silenced). 2022-11-25T00:33:48.890144064Z November 25, 2022 - 00:33:48 2022-11-25T00:33:48.896514773Z Django version 4.0.3, using settings 'certificados.settings' 2022-11-25T00:33:48.896531175Z Starting development server at http://0.0.0.0:8000/ 2022-11-25T00:33:48.896535775Z Quit the server with CONTROL-C. ... Container myapp_0_aaaaa didn't respond to HTTP pings on port: 3000, failing site start. I'm new to Docker so I don't know if I'm missing something important here. -
How to solve CORS error caused from API Calls made by Chrome extension DOM element inserted to a webpage
Im trying to make an API request to my backend server (Django) from the chrome extension. The API request goes through from the Popup.html and Popup.js but I'm facing the CORS issue when I am trying to make the request via a custom DOM element which I had inserted into Webpage. For example: I want to fetch the list of users. The Api request works fine when I open the chrome extension and make the API request. When I make the same API request after insert a new DOM element from chrome extension into any Webpage. The API is throwing CORS error. As the origin inside request headers get set to the current webpage which is not inside my allowed origin. Is there any way in which we can resolve the CORS issue without adding the LinkedIn website Url to allowed origins. I have tried multiple implementations all of which failed miserably. -
How to filter foreign key choices in admin form based on another field while changing (before saving)
I have a model with two foreign key fields class LabTesting(models.Model): fk_farm = models.ForeignKey("Farm", verbose_name=_("Farm"), on_delete=models.SET_NULL, null=True, blank=True) fk_house = models.ForeignKey("House", verbose_name=_("House"), on_delete=models.SET_NULL, null=True, blank=True) fk_house has a fk_farm foreign key field I want to limit the fk_house choices in admin page to the selected farm but while changing before clicking save I tried to edit the form but I couldn't get it to work dynamically in the change list page without saving the object -
How to render sphinx static files in django view
I have a sphinx documentation and django projet in two separate folder. When I try to render the sphinx template in my django projet, I loose all the css style and js link. Is there a way load all dependencies? -
Django - How to track user progress across multiple days?
I have a django model that updates with the user's current time spent on the website: totallearningtime = models.DecimalField(default = 0, decimal_places=2, max_digits=100) # total time user spent on website And I have the following chart.js that I want to populate with the totallearningtime through the week, and reset at the begining of the next week: (right now it has placeholder values) Here is the code for the chart: <script> const ctx = document.getElementById("myChart"); // <block:setup:1> const DATA_COUNT = 12; const labels = [ "Mon", "Tue", "Wen", "Thur", "Fri", "Sat", "Sun", ]; const datapoints = [ 0, 20, 20, 60, 60, 120, 140, 180, 120, 125, 105, 110, 170, ]; const data = { labels: labels, datasets: [ { label: "Learning Time", data: datapoints, // borderColor: red, fill: false, cubicInterpolationMode: "monotone", tension: 0.4, }, ], }; new Chart(ctx, { type: "line", data: data, options: { responsive: true, maintainAspectRatio: true, plugins: { title: { display: false, text: "Total Time: 5h 45m", }, }, interaction: { intersect: false, }, scales: { x: { display: true, title: { display: true, }, }, y: { display: true, title: { display: true, text: "Hours", }, suggestedMin: 0, suggestedMax: 200, }, }, }, }); </script> However, … -
How to add field to every historical model in django simple history
Tracking which change to a model has been made is easy. But tracking which changes have been conducted together during a single "operation" or "action" is more difficult. I would like to add an additional field to all historical models that stores a key referencing the action during which an object has been changed. In order to add a field to a historical model that is generated by the django-simple-history package one has to add an abstract class for each model and install a model specific signal handler in the apps' config. When working with 50+ models this is quiet a lot of unDRY code. How would I add a field to all historical models? -
Pydantic raises ValidationError not allowing "None" using FastAPI and Django ORM
So I have the following model in my database (Django ORM): # Database Models handled by Django ORM import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "superpower.settings") import django django.setup() from django.db import models class Order(models.Model): """Test Table""" text = models.CharField(max_length=50) amount = models.IntegerField() the following Pydantic schema: from pydantic import BaseModel # Base Class for Model "Order" class OrderBase(BaseModel): text: str amount: int class Config: orm_mode = True this view: from . import models, schemas def create_order(order: schemas.OrderBase): models.Order.objects.get_or_create(text=order.text, amount=order.amount) and finally the following routes: from fastapi import APIRouter, Depends, HTTPException from .. import models, schemas, views router = APIRouter( prefix="/orders", tags=["orders"], responses={404: {"description": "Not found"}}, ) @router.post("/create/", response_model=schemas.OrderBase) def create_orders(order: schemas.OrderBase): return views.create_order(order=order) When I now call http://127.0.0.1:8000/api/orders/create with the body { "text": "test1", "amount": 40 } I get this error: File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 407, in run_asgi result = await app( # type: ignore[func-returns-value] File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__ return await self.app(scope, receive, send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/fastapi/applications.py", line 270, in __call__ await super().__call__(scope, receive, send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/applications.py", line 124, in __call__ await self.middleware_stack(scope, receive, send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__ raise exc File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__ await self.app(scope, receive, _send) File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 79, in __call__ raise exc File "/Users/jonas/Desktop/superpower/venv/lib/python3.10/site-packages/starlette/middleware/exceptions.py", … -
Django Can't See Where I Typed in User ID
So I'm creating a web app in Django, and I encountered this error: my urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:user_id>/', views.profile, name="profile"), #path('signup/', views.signup, name="signup"), path("signup/", views.signup, name="signup") ] my views.py: from django.shortcuts import render, get_object_or_404 from django.contrib.auth import forms from django.urls import reverse_lazy from django.http import HttpResponse, Http404 from django.template import loader from .models import User from .forms import SignUpForm from datetime import datetime def index(request): cool_people_list = User.objects.order_by("-username")[:5] _template = loader.get_template("front_page.html") context = { "cool_people_list" : cool_people_list, } return HttpResponse(_template.render(context, request)) def profile(request, user_id): try: user = get_object_or_404(User, pk=user_id) _template = loader.get_template("profile.html") context = { "user" : user } return HttpResponse(_template.render(context, request)) except: raise Http404("The user you are looking for doesn't exist.") def signup(request): if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): rn = str(datetime.today().strftime("%Y-%m-%D")) rn2 = str(datetime.today) """usr_list = User.objects.order_by('-join_date') latest_usr = usr_list.first()""" new_user = User(3, str(form.cleaned_data.get("username")), str(form.cleaned_data.get("password")), rn, rn2) new_user.save() return render(request, "signup.html") my models.py: from django.db import models from django.core.validators import MinLengthValidator import datetime class User(models.Model): user_id = models.IntegerField(unique=True) username = models.CharField(max_length=25, validators=[MinLengthValidator(3)]) password = models.CharField(max_length=25, validators=[MinLengthValidator(7)]) join_date = models.DateField() last_online = models.DateTimeField() def __str__(self): return self.username I kept trying different methods, like manually … -
Django how to register model users to admin panel
I am making a site, the idea is that users can post and comment, but i messed up the models(i think) and now i have 2 seperate groups of users. My goal is to combine these 2 groups that they would be able to post and comment. When i login with an admin user and try to post something i can only use the users that i have created from the model(i have a dropdown menu that assigns and existing user to a post) I have: Admin panel users that can't post or comment, but can register, login and log out And: Model created users that can create posts and comment, but i assign them manually to posts/comments Here is my models User code: class User(models.Model): username = models.CharField('Username', max_length=100) description = HTMLField() interests = models.ManyToManyField(Interest, related_name='user_interest') Here is my models Post code: class Post(models.Model): **post_name = models.CharField('Post name', max_length=100)** description = HTMLField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) interest_tag = models.ManyToManyField(Interest, related_name='interest_tag') post_host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) Here is my models Comment code: class Comment(models.Model): **user = models.ForeignKey(User, on_delete=models.CASCADE)** post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) I'm pretty green so not sure how … -
how to extract value from FK
I have this org object (org1) which is showing in my page. This is reference to a foreign key in the model. When I do just {{ orgid }} I get the above, I can't figure out how to actually get the value - that Foreign Key = 'org1' Can anyone help please? -
How to fix a bug in Django
When I was working on a Django project (blog), I had an error(s) while working on the site. Here are the errors I have appeared: 1: When I entered the python command manage.py makemigrations blog(via the console) in the directory C:\mysite\site\miniproject , then there is this: Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\mysite\site\miniproject\blog\models.py", line 5, in <module> class Post(models.Model): File "C:\mysite\site\miniproject\blog\models.py", line 12, in Post author = models.ForeignKey(User, related_name='blog_posts') TypeError: __init__() missing 1 required positional argument: 'on_delete' Although I did everything according to the instructions on the website https://pocoz .gitbooks.io/django-v-primerah/content/sozdanie-i-primenenie-migracij.html. I … -
Django: Heroku Postgres resets uploaded data every idle
My problem seems to be the same as addressed in this page. However, I believe I am using an add-on for my case, specifically the Heroku Postgres. In case it is needed, here is a part of my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = env.str("SECRET_KEY") DEBUG = env.bool("DEBUG", default=False) ALLOWED_HOSTS = \[".herokuapp.com", "localhost", "127.0.0.1"\] CSRF_TRUSTED_ORIGINS = \['https://8000-abcdarl-hivforecastingd-4p274ahpjtp.ws-us67.gitpod.io'\] # Database DATABASES = { 'default': env.dj_db_url("DATABASE_URL") } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIRS = \[BASE_DIR / 'static'\] STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Here is a screenshot of my config variables: Screenshot of my config variables In my Django admin, I could still see all my uploaded files, but I could only download the recent ones and it would say not found in the previous ones. This is my first time deploying an application and using Heroku, so I am still new with every process involved. Thank you in advance. I don't know what to try as I am still new with everything, but I kept on researching how to handle it and I couldn't find … -
Django: html input type=input and checkbox
I have a problem with send data from input type='number' to django view. I have a page with products, each of them has a checkbox and a quantity selection (input type='number') <form action="{% url 'create-order' %}" method="POST"> {% csrf_token %} <table class="table table-responsive table-borderless"> <thead> <th>&nbsp;</th> <th>Quantity</th> </thead> <tbody> {% for item in items %} <tr class="align-middle alert border-bottom"> <td> <input type="checkbox" id="check" name="item" value="{{ item.id }}"> </td> <td> <input class="input" min="1" value=1 type="number" name="quantity"> </td> </tr> {% endfor %} </tbody> </table> <div class="submitButton"> <button type="submit" class="lgbtn green">Go to order</button> </div> </form> Submit button go to view: def create_order(request): quantities = request.POST.getlist('quantity') items = request.POST.getlist('item') return JsonResponse({ 'quantities': quantities, 'items': items }) For example, I have 6 products with id = 1, 2, 3, 4, 5, 6. And if I choose 1, 2, 3 and set quantities: 3, 4, 5, then I get: items = [1, 2, 3] # it's OK quantities = [3, 4, 5, 1, 1, 1] # but I need [3, 4, 5] Ideally, I want items and quantities to be in the same object (For example [(1, 3), (2, 4), (3, 5)] or dict {1: 3, 2: 4, 3: 5}), but not necessarily, but in any … -
Modify one to many relationship in Django
I have two models in a one to one relationship: class GPSDevice(models.Model): device_name = models.CharField(max_length=50) class SessionGPS(models.Model): start= models.IntegerField() end= models.IntegerField() gps_device = models.OneToOneField(GPSDevice, on_delete=models.CASCADE, related_name="sesion_gps_device") I realized I have a mistake, a GPSDevice can have many SessionGPS. The problem is that to correct this I should delete the one to one relation in SessionGPS and add a ForeignKey field in GPSDevice: class GPSDevice(models.Model): device_name = models.CharField(max_length=50) session_gps = models.ForeignKey(SessionGPS, on_delete=models.CASCADE, related_name="sesion_gps") #added class SessionGPS(models.Model): foco = models.BooleanField(default=False) inicio_sesion = models.IntegerField() fin_sesion = models.IntegerField() #gps_device = models.OneToOneField(GPSDevice, on_delete=models.CASCADE, related_name="sesion_gps_device") deleted I have already data in the database and I fear that migrating this can produce a mess in the database as have happened before to me. Is there another way, like doing something in the SessionGPS model? -
Flutter Web Sign in with google WITHOUT firebase gives null access token
im trying to implement google sign in with my flutter application which sends the access token to my django back end. I have everything working except, I seem to keep getting null access token. I get the ID token but that I can't send to my back end. is there some problems with trying to get the access token for flutter web (WITHOUT firebase). GoogleSignInAccount? googleaccount = await _googleSignIn.signIn(); final googleauth = await googleaccount.authentication; everything normally works fine for my mobile apps but this is me not using firebase for web. any help would be appreciated. -
How to integrate FastAPI into Django project to use Django's ORM?
I am trying to integrate FastAPI into my Django project which shall serve as an extra app (reason is that I want to use Django's ORM). Now when I run uvicorn wsgi:app --reload it returns ModuleNotFoundError: No module named 'superpower' The only tutorial I found was this which is fairly outdated. Note that I included the FastAPI app electron into the INSTALLED_APPS in my django settings. Running the command uvicorn applications.electorn.wsgi:app --reload from the project root returns ModuleNotFoundError: No module named 'applications' -
A booking form in django that fills a dropdown menu with available times
I am able to display the available times in a dropdown menu, but when I submit the form it wont save to the database. I have two forms, the first the user selects a date and the second is where the available dates should show up in a dropdown menu. models.py Slots = ( ('9.00 - 10.00', '9.00 - 10.00'), ('10.00 - 11.00', '10.00 - 11.00'), ('11.00 - 12.00', '11.00 - 12.00'), ('12.00 - 13.00', '12.00 - 13.00'), ('13.00 - 14.00', '13.00 - 14.00'), ('14.00 - 15.00', '14.00 - 15.00'), ('15.00 - 16.00', '15.00 - 16.00'), ('16.00 - 17.00', '16.00 - 17.00'), ('17.00 - 18.00', '17.00 - 18.00'), ) class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slot = models.CharField(max_length=15, choices=Slots) booking_date = models.CharField(max_length=15, default='foo') def __str__(self): return f'{self.user} has booked a PT at {self.slot} on {self.booking_date}' views.py def DateView(request): form = DateForm(request.POST or None) if form.is_valid(): request.session["dateSelected"] = str( form.cleaned_data["booking_date"]) #sends user to next form return redirect('create') context = { 'form': form } return render(request, "bookingapp/date_form.html", context) def BookingView(request): instance = Booking(booking_date=request.session.get( 'dateSelected'), user=request.user) form = BookingForm(request.POST or None, instance=instance) # get all times from bookings on the provided date booked_slots = Booking.objects.filter(booking_date=request.session.get( 'dateSelected')).values_list('slot', flat=True) available_slots = [] for slot in … -
how to redirect to homepage in django-microsoft-auth if there is no next parameter?
I registered the app in Azure AD and configured my Django app so I can log in using a Microsoft account. The problem I am facing is changing the redirect from the admin page to my homepage. Mu redirect URI on Azure looks like this: https://localhost:8000/microsoft/auth-callback/ What do I need to do to change the redirect to https://localhost:8000/home -
Django ListView display items with for loop. Mirror every 2nd
I am working on a django product overview page. I display categories with a listview. I use a Bootstrap grid with two columns to display the categories as follows: picture | Info I now ant every 2nd column to be mirrored so the end resukt will be like this: Picture | Info Info | Picture Picture | Info How do I run a loop to make this work? My code looks like this: <div class='container'> {% for category in categories %} <!-- Check is subcategory exists. if not, filter on category. If it does exist filter on subcategory --> {% if category.sub_category is Null %} <a href="{% url 'academy:brandByCat_list' category.category_name %}"> <div class="row py-3 item-display"> <div class='col-md item-img'> <img src= {{category.category_picture.url}} class="img-fluid category-picture"> </div> <div class="col-md"> <h1 class='py-3'>{{category.category_name}}</h1> <p>{{category.category_info}} </div> </div> </a> {% else %} <a href="{% url 'academy:brandBySubCat_list' category.sub_category %}"> <div class="row py-3 item-display"> <div class='col-md item-img'> <img src= {{category.category_picture.url}} class="img-fluid category-picture"> </div> <div class="col-md"> <h1 class='py-3'>{{category.sub_category}}</h1> <p>{{category.category_info}}</p> </div> </div> </a> {% endif %} {% endfor %} Thanks for the help!