Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Query If An Instance Exists Within A Many-To-Many Field On Django Queryset
Here are simplified model definitions class Resource(models.Model): name = models.CharField(max_length=100, unique=True) class Location(models.Model): name = models.CharField(max_length=100, unique=True) resources = models.ManyToManyField(Resource) And I want to know for one type of Resource, the existence on each Location. So the json data I want is like [ { "id": 1, "name": "loaction_A", "resource": true }, { "id": 2 "name": "location_B", "resource": false }, ... ] I tried following view function but obviously got wrong results. def resource_view(request, res_id): res = get_object_or_404(Resource, pk=res_id) locations = Location.objects.values('id', 'name')\ .annotate(resource=Q(resources=res)) return JsonResponce({'locations': list(locations)}) I know I need something like below (in SQL) select app_location.*, 1 in ( select resource_id from app_location_resources where location_id = app_location.id ) as resource from app_location How should I construct the queryset? -
Is the Use of Django Templates Common in Backend Python Jobs, or is it Typically Used Primarily for API and Business Logic Development?"
In the job market, I see many Python backend positions, and many of them require knowledge of the Django framework. However, as I started studying Django, I noticed that it uses templates as part of its architecture. In practice, are templates heavily used, or do companies typically have a frontend person using some JavaScript framework and a backend person using Django more for building APIs and implementing business logic? me as a Backend developer should focus in learn templates or learn build api in django with django rest? I'm new to Django and exploring backend Python job opportunities. I've noticed that Django uses templates in its architecture, but I'm curious about the practical use of templates in the industry. Have you encountered a situation where Django templates are widely used in backend development roles, or is it more common for companies to have a frontend specialist using JavaScript frameworks while Django is primarily utilized for API development and business logic implementation? -
Update an ImageField that is uploaded to S3 - REST API - FormData
I have created the following Django model: def upload_image(user, filename): ext = filename.split('.')[-1] return '%s/user_image.%s' % (user.image_path, ext) class CustomUser(AbstractUser): ... profile_picture = models.ImageField(default='default.png', upload_to=upload_image) @property def image_path(self): return f"{self.role}/{self.username}" And I have installed the storage package with which I upload the photos to a S3 bucket with the following configurations: if AWS_STORAGE_BUCKET_NAME' in os.environ: AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME'] AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False STORAGES = { # Media file (image) management "default": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", }, # CSS and JS file management "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", }, } When I create a new custom user, the photo is uploaded correctly. if 'profile_picture' in self.validated_data: account.profile_picture = self.validated_data['profile_picture'] account.save() However, when I try to update the photo in the same way (with save), it does not work. How upload_image is only called the first time when initiating the model ? -
Django APIView returns “IndexError: list index out of range” in unit test but works in Postman
I have written an APIView in Django that returns a random line from a database table. When I test it using Postman, I get the response I want. However, when I call the URL of the endpoint in a unit test, I get an “IndexError: list index out of range” error. Here’s my code: Endpoint - def get(self, request, **kwargs): all_the_pickup_id = PickupData.objects.values_list('id', flat=True) # if not all_the_pickup_id: # return Response("No pickup lines found.") random_id = random.choice(all_the_pickup_id) random_pickup = PickupData.objects.get(id=random_id) random_line = random_pickup.text return Response(random_line) Unit Test Code - def test_text_response(self): client = APIClient() response = client.get('/getPickup/getUnitTest/') self.assertEqual(response['Content-Type'], 'application/json') print('Get Pickup',response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) How can I fix this error and make my unit test work? -
Access to related model field in django_filters
I'm constructing Django-based 4-language website for a real estate agency. I'm using django-filter package to filter my objects (real estate properties) by certain parameters, such as type (house, apartment, etc.), city and some others. My 'type' field is a foreign key for the model 'Type'. On the html page this field is tendered as a field with options, which is good. But for some reason the options are rendered as slug names of my types ('house', 'apartment', etc., see the picture). It is the 'slug' field of my foreign key model Type. Instead of this, I want to print 'name' field in the options. This field is translated (django-modeltranslation package), so that in English version one should see options 'House', 'Apartment'..., and in Spanish version - 'Casa', 'Apartamento', etc. I tried modify this field in my PropertyFilter as using '__' symbol (type__name instead of type), but it doesn't seem to work. Please, help me, I'm stuck! -
which programming language should I choose? [closed]
I am a B.tech Information technology student , I am interested in both python and java but i have a doubt. which is best for software development python or java . which has the high scope for freshers? if any these language is best for software development the which frame work is suitable and which is trend today? -
How to manage serializers in Django Rest Framework?
I use the following serializer in my ViewSet to create some Instance: class InstanceCreateSerializer(ModelSerializer): class Meta: model = Instance fields = [ "id", "name", "description", "company", "err_msg", "is_valid", ] The fields author, company, is_valid and err_msg must be set by the service, not by the user. But if i use read_only_fields, as in the code below, then these fields cannot be changed by the service either. class InstanceCreateSerializer(ModelSerializer): class Meta: model = Instance fields = [ "id", "name", "description", "author", "company", "err_msg", "is_valid", ] read_only_fields = [ "author", "company", "err_msg", "is_valid", ] How can I manage serializers or prevent the user from submitting values for these fields? Additionally, these fields are available for input in the DRF Browsable API and Swagger, which is something I also want to fix. -
CKeditor not working on PythonAnywhere, working on localhost (Django)
I have simple blog project that I want to show on pythonanywhere. Unfortunatelly I cant seem to fix issue with CKeditor. It works on localhost, but on pythonanywhere it shows errors and only standard text editor window. Errors in console](https://i.stack.imgur.com/SCTnH.png) I did try solutions here on Stackoverflow. I did try to run collectstatics etc. Nothing helped so far. I found that someone said That Pythonanywhere wont ever be able to run CKeditor but I didnt find more about it. If CKeditor is not gonna work, do you know about any other rich text editor that will work? I need one with picture editing. Also here is the webppage on Pythonanywhere.com. Thank you for any advice. I will provide code if needed I just didnt know which part exactly would make this issue. -
Djoser UserViewSet, getting 401 Unauthorized `as_view("get": "list")`
When I test the endpoint using POSTMAN I am getting 401 Unauthorized. { "detail": "Authentication credentials were not provided." } enlighten me accounts.views.py from django.shortcuts import render from djoser.views import UserViewSet from .serializers import UserCreateSerializer, ResidentRegistrationSerializer from rest_framework import status from rest_framework.response import Response # Create your views here. class ResidentRegistrationView(UserViewSet): serializer_class = ResidentRegistrationSerializer # custom serializer # override the create method to enforce the required fields def create(self, request, *args, **kwargs): # check if address_info data is provided in the request if "address_info" not in request.data: return Response({"Error": "Address information is required."}, status=status.HTTP_400_BAD_REQUEST) # call the parent class's create method return super().create(request, *args, **kwargs) accounts.urls.py from django.urls import path from .views import ResidentRegistrationView urlpatterns = [ path("register/resident/", ResidentRegistrationView.as_view({"get": "list"}), name="resident-registration") ] accounts.serializers.py from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model from .models import ResidentProfile, AddressInformation User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ("id", "email", "password") class ResidentRegistrationSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = ResidentProfile fields = ( "first_name", "middle_name", "last_name", "date_of_birth", "gender", "relationship_status", "phone_number", "address_info", ) -
Django ORM get record with latest date
This is the data I have: class RdpUserPasswordHash(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='password_hash') when = models.DateTimeField(auto_now_add=True, db_index=True) select id, "when", user_id from registry_rdpuserpasswordhash where user_id =3; 1 2023-07-29 10:55:41.193 +0200 3 2 2022-08-09 10:55:41.236 +0200 3 I need to filter getting for each user_id the latest record wrt "when" and I do not find a reliable way to do it with the ORM. (1) for r in RdpUserPasswordHash.objects.order_by('user_id', '-when').distinct('user_id'): if r.user_id==3: print(r) <RdpUserPasswordHash: RdpUserPasswordHash object (1)> RdpUserPasswordHash object (1) is the one with the latest date (2) RdpUserPasswordHash.objects.order_by('user_id', '-when').distinct('user_id').filter(when__lt=timezone.now() - td_expire_days) <QuerySet [<RdpUserPasswordHash: RdpUserPasswordHash object (2)>]> But I need to now, among the ones with the latest date which one is expired but with the above query I get the unexpected result. Unexpected because it is not in RdpUserPasswordHash.objects.order_by('user_id', '-when').distinct('user_id') So adding a filter actually changes the result of the initial queryset. QUERIES generated by the ORM: (1) SELECT DISTINCT ON ("registry_rdpuserpasswordhash"."user_id") "registry_rdpuserpasswordhash"."id", "registry_rdpuserpasswordhash"."user_id", "registry_rdpuserpasswordhash"."password_hash", "registry_rdpuserpasswordhash"."when" FROM "registry_rdpuserpasswordhash" INNER JOIN "registry_rdpuser" ON ("registry_rdpuserpasswordhash"."user_id" = "registry_rdpuser"."id") WHERE ("registry_rdpuser"."is_active" AND "registry_rdpuserpasswordhash"."when" < '2023-07-28T08:23:32.599017+00:00'::timestamptz) ORDER BY "registry_rdpuserpasswordhash"."user_id" ASC, "registry_rdpuserpasswordhash"."when" DESC LIMIT 21 (2) SELECT DISTINCT ON ("registry_rdpuserpasswordhash"."user_id") "registry_rdpuserpasswordhash"."id", "registry_rdpuserpasswordhash"."user_id", "registry_rdpuserpasswordhash"."password_hash", "registry_rdpuserpasswordhash"."when" FROM "registry_rdpuserpasswordhash" INNER JOIN "registry_rdpuser" ON ("registry_rdpuserpasswordhash"."user_id" = "registry_rdpuser"."id") WHERE ("registry_rdpuser"."is_active" AND … -
Trying to install Helios requirements
Building wheel for python-ldap (pyproject.toml) ...Error ERROR: Failed building wheel for python-ldap Failed to build python-ldap ERROR: Could not build wheels for python-ldap, which is required to install pyproject.toml-based projects -
Problem with user uploading images in django
I want to use the Django framework to design a user personal picture uploading system. The completed content includes a Django project name named SGV. The project inclue a name call Success app to handle various requests from users. After the user logs in, It will jump to a webpage named userhome.html. I want to upload pictures of the current webpage in this userhome without jumping to other pages. After the pictures are uploaded, they will be saved to the user_file/image folder in the root directory of the project. , the problem is that after I finished writing part of the code, I found that I could select the file, but nothing happened after clicking the upload image button, not even any error. Is there any kind person who can help me, a newbie in Django? The following is some code within the project, which may not be fully displayed. If you want to know more, please tell me. Userhome.html <!DOCTYPE html> <html> <head> {% load static %} <title>SGV UserHome</title> <base href="/"> <link rel="stylesheet" type="text/css" href="{% static 'css/system.css' %}"> </head> <body> <div class="nav"> <h1>Welcome to User Home</h1> <form method="post" enctype="multipart/form-data" id="upload-form"> {% csrf_token %} <input type="file" name="image" accept="image/*" id="image-input"> <button … -
Django Session, Login and Signup
This is my view module def home(request): return render(request, 'rescues_site/home_page.html') # @login_required def user_home(request): if request.method == 'POST': username = request.session.get('username') context = { 'username': username } return render(request, 'rescues_site/home_page.html', context) def login(request): if request.method == 'GET': return render(request, 'registration/login.html') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username = username, password = password) if user is not None and user.is_active and user.is_authenticated: login(request, user) request.session['username'] = user.username return redirect('user_home') else: return render(request, 'registration/login.html') @transaction.atomic def sign_up(request): if request.method == 'GET': return render(request, 'registration/sign_up.html') if request.method == 'POST': error = [] first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') address = request.POST.get('address') suburb = request.POST.get('suburb') postcode = request.POST.get('postcode') email = request.POST.get('email') phone_number = request.POST.get('phone_number', None) password = make_password(request.POST.get('password')) try: user = CustomUser.objects.create(username = email, first_name = first_name, last_name = last_name, address = address, suburb = suburb, postcode = postcode, phone_number = phone_number, password = password) request.session['username'] = user.username return redirect('user_home') I tried to login the user and redirect the user to the home page with their cresidentials but what I have is a POST request in the terminal and it take me nowhere. I'm still new to Django and Python. Thank you for your time! -
CSRF Error event after adding CORS_TRUSTED_ORIGINS Django
I am trying to implement feature for changing password but when I make a put request from react frontend to django backend I am getting CSRF error. I am not getting such an error for other put/post requests. Following are the code details: settings.py REST_FRAMEWORK = { # 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAuthenticated', # ], # 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework_simplejwt.authentication.JWTAuthentication', # ], 'DEFAULT_PAGINATION_CLASS': 'main.paginations.CustomPagination', 'PAGE_SIZE': 12 } CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000", "http://127.0.0.1:3000", "http://localhost:3000", ] CORS_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] views.py class ChangePasswordView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = serializers.ChangePasswordSerializer serializers.py class ChangePasswordSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True) password2 = serializers.CharField(write_only=True, required=True) old_password = serializers.CharField(write_only=True, required=True) class Meta: model = models.User fields = [ 'old_password', 'password', 'password2' ] def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({'password': 'Password fields did not match!'}) return attrs def validate_old_password(self, value): user = self.context['request'].user if not user.check_password(value): raise serializers.ValidationError({'old_password': 'Old password provided is incorrect!'}) return value def update(self, instance, validated_data): user = self.context['request'].user print(user) if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission to change password!",}) instance.set_password(validated_data['password']) instance.save() return instance urls.py ... path('change_password/<int:pk>/', views.ChangePasswordView.as_view(), name='auth_change_password'), ... Frontend: const link = `${BASE_URL}${CHANGE_PASSWORD_URL}${customer_id}`; const formData = new FormData(); formData.append('old_password', oldPwdRef.current.value); formData.append('password', newPwdRef.current.value); formData.append('password2', confirmNewPwdRef.current.value); axios.put(link, formData, … -
Calling a variable from python function in HTML page. Coding done in Python, HTML, and Django [duplicate]
I created a basic website in Django, with Python and HTML. Now when I click a button, I want to see a python variable contents on the website. I have a HTML file, and a python views file(I have more files but I think those are the main ones I need to change). I want to print the contents of a python variable onto a HTML website. -
Django Meta.constraints are not working in my models
I'm trying to define a unique constraint for two primary keys in my model, because they are referenced by other models. And ent_ruc cant be unique. Must be unique together with ent_id. class Enterprise(models.Model): ent_id = models.CharField( db_column='ENT_ID', primary_key=True, max_length=16, default=timestamp_id_16) ent_ruc = models.CharField( db_column='ENT_RUC', max_length=16) ent_name = models.CharField(db_column='ENT_NAME', max_length=256) ent_address = models.CharField(db_column='ENT_ADDRESS', max_length=512) ent_type = models.CharField(db_column='ENT_TYPE', max_length=2) class Meta: db_table = 'ENTERPRISE' constraints = [ models.UniqueConstraint( fields=['ent_ruc', 'ent_id'], name='unique_enterprise') ] But when I run the server I get the error: 'Enterprise.ent_ruc' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or add a UniqueConstraint (without condition) in the model Meta.constraints. Why Meta.constraints are not working ? -
How to Make This Django's ImageField Work?
models.py `class SpecialOffer(models.Model): productImage = models.ImageField(upload_to="", null=True, blank=True) productName = models.CharField('Product Name', max_length=20) def __str__(self): return self.productName` views.py `def homepage(request): specialoffers = SpecialOffer.objects.all() context = { 'specialoffers' : specialoffers, } return render(request, "index.html", context)` index.html {% for product_name in specialoffers %} <img src="{{ product_name.productImage.url }}" alt="" /> {% endfor %} and the error is that the image i'm uploading through admin sections, is not rendering through my HTML templates. what's wrong with my code? I tried changing this {{ product_name.productImage.url }} to {{ product_name.productImage }} but is still not working. I also tried setting up the MEDIA_URL, and MEDIA_ROOT. -
getting model object using .get(slug=slug) return an error: Invitation matching query does not exist
I am creating a notification system using django, I'm using django signal to create Notification model when the Invitation model is created, but when I created the Invitation model, and click on the link that are in notification template it says: Invitation matching query does not exist. This is a booking application, we want to send that link to the person who created the Invitation model via his email, so that he can see his information, but the link does not gives the person information when I click it in the notification template it says: DoesNotExist at /invitation_information/OlaRooms-123297186425/ Invitation matching query does not exist. views.py def invitation_information(request, slug): invitation = Invitation.objects.get(slug=slug) return render(request, 'invitations.html', {'invitation':invitation}) urls.py path('invitation_information/<slug:slug>/', views.invitation_information, name='invitation_information'), notification template <div class="container"> <div class="row"> {% for notification in notifications %} {% if not notification.is_read %} <div class="col-md-3"> <div class="card"> <div class="card-body"> <a href="{{ notification.link }}"> {{ notification.message }} </a> </div> </div> </div> {% endif %} {% endfor %} </div> </div> signals: @receiver(post_save, sender=Invitation) def notification_signals(sender, instance, created, **kwargs): message = f"{instance.first_name} {instance.last_name} booked our {instance.room_type.room_type} room for {instance.number_of_day} day" link = reverse('Invitation_Information', args=[str(instance.room_type.slug)]) room_id_number = generate_random_number() notification = Notification.objects.create( user=instance.room_type.user, message=message, link=link, room_id_number=room_id_number ) notification.save() My Models: class Room(models.Model): … -
Optimizing Django Admin Search by 'external_id' for Large Datasetsop
I'm facing performance issues when searching for records by the 'external_id' field in the Django Admin on a large dataset. The 'external_id' is a unique identifier for each record in my model. I've already added a HashIndex for this field, but it's still slow. What can I do to optimize the search performance in this specific scenario? Are there any other indexing techniques or Django-specific optimizations that can help speed up the search operation? I appreciate any insights or suggestions to improve the performance of searching by 'external_id' in the Django Admin, especially on large datasets. Thank you! from django.contrib.postgres.indexes import HashIndex from django.db import models class SocialIds(models.Model): """Model for social network identifiers of a user.""" profile = models.ForeignKey( 'accounts.Profile', related_name='socials', on_delete=models.deletion.CASCADE, verbose_name='User Profile', ) service_name = models.CharField( max_length=30, verbose_name='Social Network Name', ) external_id = models.CharField( max_length=100, verbose_name='External Identifier', ) class Meta: verbose_name = 'Social Network Identifier' verbose_name_plural = 'Social Network Identifiers' constraints = [ models.UniqueConstraint( fields=[ 'service_name', 'external_id', ], name='unique_social_service_name_external_id_ids', ), ] indexes = [ HashIndex( fields=['external_id'], name='social_ids_external_idx', ), ] def __str__(self): return str(self.profile) @admin.register(SocialIds) class SocialIDsAdmin(admin.ModelAdmin): list_display = ('profile', 'service_name') list_filter = ('service_name',) raw_id_fields = ('profile',) search_fields = ['profile__nickname', 'external_id'] fields = ('profile', 'service_name') I'd like to obtain … -
Django Error: 'cannot pickle '_io.BufferedReader' object' when Using Cache with Context Data
I'm encountering a challenging issue in my Django project related to caching and context data. When trying to cache the context data in a view, I'm receiving the error message: "cannot pickle '_io.BufferedReader' object." The error seems to occur in my view that displays detailed information about a book, and I'm attempting to cache certain parts of the context, such as average ratings, recommended books, and the last books. There is my detail book view and model: #views.py class DetailBookView(DetailView): template_name = "books/book-detail.html" queryset = Book.objects.all().select_related("genre") cache_timeout = 60 def get_context_data(self, **kwargs): obj = self.get_object() context = super().get_context_data(**kwargs) cache_key = f"book_detail_{obj.id}" cached_data = cache.get(cache_key) if cached_data is not None: context.update(cached_data) # average rating book context["avg"] = BookRelations.objects.get_rating(book=obj) # generate 3 random book context["recommended"] = Book.objects.get_recommended(obj.genre) # last 3 books context["last_books"] = self.get_queryset().values("title") else: cache.set(cache_key, context, self.cache_timeout) return context #models.py (Books) class BookManager(models.Manager): def get_recommended(self, genre): recommend_books = list(Book.objects.filter(genre=genre).select_related("owner")) if len(recommend_books) < 3: recommend_books += list(self.get_queryset())[:4] return random.sample(recommend_books, 3) class Book(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(default="") description = models.TextField(blank=True, null=True) rating = models.DecimalField( validators=[MaxValueValidator(5)], max_digits=3, decimal_places=2 ) created_at = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) image = models.ImageField( upload_to="book_img/", validators=[FileExtensionValidator(["jpg", "JPEG"])], null=True, blank=True, ) genre = models.ForeignKey(Genre, on_delete=models.PROTECT, null=True) author = models.ForeignKey(Author, … -
How to display multiple related objects in Django
I have two models that look like this: class EventDrink(models.Model): name = models.CharField(max_length=255) drink_active = models.BooleanField() def __str__(self): return self.name class EventIngredient(models.Model): drink = models.ManyToManyField(EventDrink) name = models.CharField(max_length=255) url = models.URLField() def __str__(self): return self.name I now want to display all drinks with drink_active set to True to display in my view. I also want to display the ingredients related to that drink. I know I can filter on the drinks in my view like this: drinks = EventDrink.objects.filter(drink_active=1) But how do I now display the ingredients related to each drink? -
The contents in my cards are not the same size eventhough they have the same code
So I made this booking page with bootstrap, and I have made the Upcoming Bookings section first, after that I just copied and past it to the Past Booking section, and just change the variable inside the templating language curly brackets. In theory, since its 99.99% the same code, it should be the same right? But for some reason the details in the Past Booking card is slightly smaller than the Upcoming booking, and this makes it looks unsymmetrical and its driving my OCD crazy. I cannot figure it out! If anyone could that would be very helpful! Screenshot my_bookings.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="jumbotron"> <div class="welcome-my-bookings mt-5 text-center"> <h1>My Bookings</h1> </div> </div> <div class="row mt-4 booking-title"> <h3>Upcoming Bookings</h3> <hr> </div> <div class="col-12 card mb-4 left top"> <div class="card-body"> {% if future_bookings %} {% for booking in future_bookings %} <div class="booking-details booking-card my-4"> <div class="row justify-content-center align-items-center flex-lg-row"> <div class="col-auto booking-img-container"> <a href="{% url 'lesson_detail' booking.lesson.slug %}" class="lesson-link"> <div class="col-auto"> {% if "placeholder" in booking.lesson.featured_image.url %} <img class="booking-img d-none d-md-inline-block" src="https://res.cloudinary.com/dukqu7lia/image/upload/v1696354385/placeholder.jpg"> {% else %} <img src="{{ booking.lesson.lesson.featured_image.url }}" class="booking-img d-none d-md-block"> {% endif %} </div> </a> </div> <div class="col-auto … -
Centering div and its elements in Django project
I'm diving into Django for my first project, and I'm stuck with centering stuff on my site. What I'm trying to do is create a div that holds all the content on the site except for the navigation bar. I want this div to sit right in the middle of the screen and take up 50% of the width. And, of course, all the stuff inside that div should be centered too. I've tried a few things, but it's not quite working. Take a look at what I've got: Here is the template: <html> <style> body { margin: 0; padding: 0; } img[src="/media/images/crate_bar.png"] { margin: 0; padding: 0; display: block; width: 100%; height: auto; box-sizing: border-box; } img[src="/media/images/logo.png"] { position: absolute; display: block; width: auto; height: auto; left: 50%; transform: translateX(-50%); top: 0; } #logo { display: flex; justify-content: center; align-items: center; text-align: center; } #main_container { display: flex; justify-content: center; align-items: center; } #second_container { display: flex; justify-content: center; align-items: center; width: 50%; } </style> <div id="logo"> <img src="/media/images/crate_bar.png"> <a href="{% url 'mainapp:home_view' %}"><img src="/media/images/logo.png" alt="logo"></a> </div> <h1> {% if user.is_superuser %} <a href="{% url 'mainapp:new_article' %}"><button type=" button">New article</button></a> {% endif %} {% block content %} <div id="main_container"> … -
Create dynamic URL using primary key in django
I'm developing a website, it creates url for every article using slug (entered manually by the admin who is posting the article) However I'm trying to change it to be dynamically generated using pk. Note that there is no content uploaded in the website so it won't affected by this change. Here is the current code and my main problem is that I don't know how to change it to pk. and when I try the available solutions I don't know where it should be passed through HTML pages. #view.py def DetailView(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) return render(request, template_name, {'post': post}) #models.py class Post(models.Model): title = models.CharField(max_length=500) image = models.ImageField(null=True, blank=True, upload_to='media/') content = RichTextField(blank = True, null = True) post_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=200, allow_unicode=True, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') status = models.IntegerField(choices=STATUS, default=0) category = models.CharField(max_length=500, choices= categories_list, default='0') #To order posts based on created dates decsend class Meta: ordering = ['-created_on'] def __str__(self): return self.title #urls.py path('<slug:slug>/', views.DetailView, name='post_detail'), and here is how it's being passed to the html <p><a href="{% url 'post_detail' post.slug %}">{{post.content|safe |slice:":10" }}</a></p> Thanks in advance -
Django Query input results of one queryset to find an object that doesn't appear in another model
Good afternoon, I am trying to write an DRF endpoint that returns the next unused hint. I have two models: class GameActivity(models.Model): activity_datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='activity_user') activity_type = models.ForeignKey(GameActivityType, on_delete=models.CASCADE, null=True, blank=True,related_name='game_activity_type') activity_hint = models.ForeignKey(Hint, on_delete=models.CASCADE, null=True, blank=True) And class Hint(models.Model): hint_title = models.CharField(max_length=50) hint_detail = models.CharField(max_length=300) hint_level = models.IntegerField() chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, null=True, blank=True, related_name="chapter_hint") pts_cost = models.IntegerField() What I am trying to do is return the next hint for the passed in Chapter ID that is NOT in the GameActivity model. pseudo-code return Hint where (Count (GameActivity where activity_hint=Hint AND Hint.Chapter == Chapter.ID) = 0) order by hint_level ASC LIMIT 1 I cannot figure out how to chain two queries together, the first being input to the second. Queryset = SELECT * from Hint WHERE chapter.id = CHAPTER_ID Pass in the queryset into GameActivity and return the one Hint with the lowest hint_level that doesn't have a GameActivity entry. Thanks for any help, I feel like I am not thinking about the problem correctly. BCBB