Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using django_tables2, tables.A() is only returning the passed string rather than an object
I'm creating a templateColumn in django_tables, and in order to populate a dropdown menu with Vendors related to a particular Job, I'm trying to use tables.A('job') to filter my queryset. However, tables.A('job') gives me the error ValueError: Field 'id' expected a number but got 'job'. No matter what I set as the argument, it just returns that string. I've tried "cost__job", "job__id", other field names etc., but it only ever returns the string I pass in. Code below: tables.py import django_tables2 as tables from .models import Job, Cost, Vendor class CostTable(tables.Table): vendor = tables.TemplateColumn(template_name="main_app/tables_costsheet_vendor_column.html", extra_context={ 'vendors':[(vendor.unique_id, vendor.full_name) for vendor in Vendor.objects.filter(jobs_rel=tables.A("job"))] }) edit = tables.TemplateColumn(verbose_name='', template_name="main_app/tables_costsheet_edit_column.html") job = tables.Column(accessor='job.vendors.all') #just for debug, correctly shows the vendors for the job class Meta: model = Cost order_by = 'vendor_initials' template_name = "django_tables2/bootstrap5.html" fields = ("job", "vendor", "description", "amount", "invoice", "PO_number", "edit") Here's how my Cost and Job objects are related: class Cost(models.Model): ... vendor = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True, blank=True,) job = models.ForeignKey('Job', on_delete=models.CASCADE, related_name='cost_rel', null=True) ... class Job(models.Model): ... vendors = models.ManyToManyField(Vendor, verbose_name='vendors involved', blank=True, related_name = 'jobs_rel') ... Note the dropdown populates if I use 'vendors':[(vendor.unique_id, vendor.full_name) for vendor in Vendor.objects.all())] in the context, but I only want it to show … -
Why don't the options for my cascading dropdown form appear?
I am building a car repair estimator and need to create a dependent dropdown that will allow users to select from a variety of Models that depend on the Make that they've chosen. I'm able to see and select different Makes, but I am unable to see the different Models. I am using Django framework and have stored the Makes, and Models in a Postgresql database Here is what is happening with my app right now: Ford models are supposed to be here Here is a snapshot of my working director of my app, AutoBuddy: Working Directory Here is the code from my ABDjango/templates/models/home.html file: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Dependent Dropdown in Django</title> </head> <body> <h2>Car Form</h2> <form method="post" id="modelForm" data-models-url="{% url 'ajax_load_models' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_model").change(function () { const url = $("#modelForm").attr("data-models-url"); // get the url of the `load_cities` view const modelId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= /persons/ajax/load-cities/ ) data: { 'model_id': … -
Writeable Nested Serializer, overriding .create() - Django
I have AttendanceSlot model which has a foreign key to Course model, I want my endpoint to return the actual course code, not just the primary key.but I'm getting the below error when I try to override the .create() please, I don't know where i'm getting it wrong. TypeError at /attendance/attendance-slot/ Field 'id' expected a number but got OrderedDict([('course_code', 'COM411')]). models.py class Course(models.Model): course_code = models.CharField(_("Course Code"), max_length=50) course_title = models.CharField(_("Course Title"), max_length=100) def __str__(self): return '{0}'.format(self.course_code) class AttendanceSlot(models.Model): department_id = models.ForeignKey("students.Department", verbose_name=_("department id"), on_delete=models.CASCADE) course_id = models.ForeignKey("students.Course", verbose_name=_("course id"), related_name= 'course', on_delete=models.CASCADE) lecturer_id = models.ForeignKey("lecturers.Lecturer", on_delete=models.CASCADE) date = models.DateField(_("attendance date"), auto_now=False, auto_now_add=True) start_time = models.TimeField(_("start time"), auto_now=False, auto_now_add=False) end_time = models.TimeField(auto_now=False, auto_now_add=False) def __str__(self): return '{0}'.format(self.course_id.course_code) below is my serializers.py class CourseMini(serializers.ModelSerializer): class Meta: model = Course fields = ['id','course_code'] class AttendanceSlotSerializer(serializers.ModelSerializer): course_id = CourseMini() class Meta: model = AttendanceSlot fields = '__all__' def create(self, validated_data): course = Course.objects.get(pk = validated_data.pop('course_id')) instance = AttendanceSlot.objects.create(**validated_data) instance.course_id = course instance.save() return instance def to_representation(self, instance): representation = super(AttendanceSlotSerializer, self).to_representation(instance) return representation views.py class AttendanceSlotView(ListCreateAPIView): queryset = AttendanceSlot.objects.all() serializer_class = AttendanceSlotSerializer def perform_create(self, serializer): serializer.save(lecturer_id=self.request.user.lecturer) return super().perform_create(serializer) what am i missing? -
Python / Django - Safest way to normalize relative paths cross-platform?
Please note this question is about relative paths and must account for cross-platform functionality. When a user uploads a file, I want to generate a timestamped path to it: def get_filepath(instance, filename) -> str: """ Returns a timestamped directory path to deposit files into. i.e. "evidence/2023/02/23/96672aa5-94d9-4289-8531-d7a8dc8f060d/data.jpg" """ dt = timezone.now() YYYY = dt.year MM = str(dt.month).zfill(2) DD = str(dt.day).zfill(2) UID = str(uuid.uuid4()) # settings.MEDIA_URL = 'media/', I just checked path = (str(x) for x in ( settings.MEDIA_URL, 'evidence', YYYY, MM, DD, UID, filename )) path = os.path.join(*path) # dubious return path This is raising SuspiciousFileOperation, which is not at all surprising: raise SuspiciousFileOperation( django.core.exceptions.SuspiciousFileOperation: Detected path traversal attempt in '/media/evidence\2023\02\23\1cfa40b9-b522-4c70-b59b-fd270d722ab2\templeos.txt' I'm at a loss as to how to normalize this though. pathlib.PurePath -- didn't work, Django FileField doesn't like the Path object, which want to treat the string as an absolute path by sticking C:\ in front. os.path.normpath -- didn't work either (SuspiciousFileOperation: The joined path (C:\media\evidence\2023\02\23\cc32be4a-76d8-47c5-a274-9783707844b3\templeos.txt) is located outside of the base path component (C:\Users\...) This does appear to work if I do str(x).strip('/\\') when defining the path, but this is hacky and the sort of thing I'd expect a proper library to handle... What am I "supposed" to … -
Django 4.1 Google Social Auth does not authenticate
I am not sure what happened as this was working fine before. Now, when I use google authentication with social-auth, and when I check request.user.is_authenticated, it is always False. I will provide my setup, I checked it hundreds of times, I just can't seem to see the error: Here are the variable to my key files. I verified the keys, I can confirm I am using the correct ones, I changed the URI and got an error. Here are all my settings. I use the login_view to create a userProfile and to send out emails. All this was working fine, and I have no idea why it would just stop. This is all happening on a local Dev server I have on an Ubuntu VM. Please, if you have any suggestions at all, I would be so very happy. # social auth configs for google SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get( 'SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ] #installed apps: 'social_django', #middleware: 'social_django.middleware.SocialAuthExceptionMiddleware', #templates: 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', LOGIN_REDIRECT_URL = "login_view" SOCIAL_AUTH_LOGIN_REDIRECT_URL = "login_view" SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'Quiz.pipeline.redirect_to_login_view', # custom pipeline function 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) pipeline.py: from django.shortcuts import redirect … -
Turn 'Like' to 'Unlike' if button is already liked by user
I have the 'Like' button working which adds the currently logged in user to database once button is pressed, but the button doesn't turn to 'Unlike'. If the button is pressed a second time the 'Like' is removed from the database. So the key issue is getting the button to change. I'm thinking I would need a variable for liked_status some where possibly? But wouldn't know how to implement this. Views def BlogLike (request, slug): post_id = request.POST.get('blog-id') post = BlogPost.objects.get(slug=post_id) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('viewblog', args=[post_id])) html <form action="{% url 'likepost' blog.slug %}" method="POST"> {% csrf_token %} {% if blog.liked is True %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="blog-id" value="{{ blog.slug }}">Unlike<i class="fa-solid fa-heart-crack"></i></button> - {{ blog.total_likes }} Likes {% else %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="blog-id" value="{{ blog.slug }}">Like<i class="fa-solid fa-heart"></i></button> - {{ blog.total_likes }} Likes {% endif %} </form> -
How can I render my Django variable and tags from my custom html code that is coming from sql database
I am using GrapesJS and Django together when I save GrapesJS html it doesn't save my dynamic variable for instance "Copyright {% now "Y" %}" it wants to save "Copyright 2023" instead. So before I save to database I do a re.sub and change "2023" back to {% now "Y" %} and save to database. Problem now is that when I get the html back from the database and put it into django template as "{{ page.html }}" it doesn't read the Django Tag because it has already did its magic and read "{{ page.html }}" so what it shows on webpage instead of seeing "Copyright 2023" I see "Copyright {% now "Y" %}". How can I get Django to read the variables and tags from the databases when rendering into template. I have tried to use engines['django'].from_string and couldn't get it to work. -
DJANGO: How to turn re_path into path
I am trying to understand how can I modify urlpatterns written with re_path to use path instead here's an example: re_path( r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail') How can I write the same thing using path instead? here's the html that when clicked takes you to the detail page of a school {% for school in school_list %} <h2><li><a href="{{school.id}}">{{school.name}}</a></li></h2> {% endfor %} here's what I tried: path('<int:school_id>/', views.SchoolDetailView.as_view(), name='detail') what I got is the following error: Generic detail view must be called with either an object pk or a slug in the URLconf. -
DRF web interface doesn't work as Postman
I'am creating a blog app where only authenticate users can add blogs. I'm using JWT token and on Postman it work's well and I can add blog's after I logged in. I want to do it on DRF web interface also but it always tell me that I'm not logged in - I think. Exception Value: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x0000021035CA1C50>": "Blog.author" must be a "User" instance. My views.py class BlogList(generics.ListCreateAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer authentication_classes = [JWTAuthentication] #permission_classes = [IsAuthenticated] permission_classes = [IsOwnerOrReadOnly] filter_backends = [SearchFilter] search_fields = ["title", "content", "author__username", "author__first_name", "author__last_name"] def perform_create(self, serializer): serializer.save(author=self.request.user) Serializer.py class BlogSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source="author.username") author_first_name = serializers.ReadOnlyField(source="author.first_name") author_last_name = serializers.ReadOnlyField(source="author.last_name") slug = serializers.ReadOnlyField() comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) read_only_fields = ["author", "first_name", "last_name"] class Meta: model = Blog fields = ["id", "title", "content", "status", "author", "comments", "image", "created_on", "updated_on", "author_first_name", "author_last_name", "slug"] def to_representation(self, instance): data = super().to_representation(instance) user = self.context["request"].user if not user.is_authenticated: data.pop("slug") return data def save_author(self, **kwargs): if "author" not in self.validated_data: self.validated_data["author"] = self.context["request"].user return super().save(**kwargs) def save(self,**kwargs): self.validated_data["slug"] = slugify(self.validated_data.get("title")) return super().save(**kwargs) I don't know what else I should post here. I tried somehow to DRF web interface add some button like "Authenticate" … -
Deploying a Django application to Elastic Beanstalk: Advantages and disadvantages of adding the VENV (Virtual Environment) folder
I've seen that some people have a virtual environment/venv folder in a project, or app folder. They are zipping that and deploying with Elastic Beanstalk. Is it a good or bad idea to do so? Official docs don't mention that directly, but in the example, there is no venv folder in the set for zipping. Quote: I don't have such an approach - I prefer to stick to the documentation. But I wonder if this approach that some use results from the case or is intentional. -
Like button not recording likes in the back end
Button successfully links back to current blog page but the likes are recording in the back end, what am I doing wrong here? views def BlogLike (request, slug): post = get_object_or_404(BlogPost, id=request.POST.get(slug)) post.likes.add(request.user) return render(request, 'viewblog', {'post': post}) urls path('view-blog/<slug:slug>/', views.ViewBlog, name='viewblog'), path('like/<slug:slug>', views.BlogLike, name='likepost'), html <form action="{% url 'viewblog' blog.slug %}" method="POST"> {% csrf_token %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="blog_id" value="{{ blog.slug }}">Like</button> </form> EDIT class BlogPost(models.Model): title = models.CharField(max_length=100, null=False, blank=False, default="",) text = RichTextUploadingField(null=True, blank=True, default="text") featured_text = models.TextField(max_length=550, null=True, blank=True, default="text") image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") date = models.DateField(auto_now_add=True) published = models.BooleanField(default=False) featured = models.BooleanField(default=False) slug = models.SlugField() likes = models.ManyToManyField(User, related_name='likes') def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title -
Django: How to use post data in DetailView
I would like to use detailview instead of the current view and process post data in it. However, I don't know how to download them to the view, is it even possible? If not then please give me some advice if leaving it as it is also looks good? views.py class ProductDetailView(View): def get(self, request, pk): product = Product.objects.get(id=pk) context = {'object': product} return render(request, "products/detailview.html", context) def post(self, request, pk): if not request.user.is_authenticated: messages.success(request, "You must be logged in") return redirect('Login') cart, created = Cart.objects.get_or_create( user=request.user, ) cart.save() added_item = Product.objects.get(id=pk) item_in_cart = CartItem.objects.filter(cart=cart) for item in item_in_cart: if item.product.title == added_item.title: messages.success(request, "It's already in the basket") return redirect('ProductDetail', pk=pk) new_item_in_cart = CartItem.objects.create( product=added_item, cart=cart, ) new_item_in_cart.save() added_item.quantity -= 1 if added_item.quantity == 0: added_item.is_available = False added_item.save() messages.success(request, "Add to cart") return redirect('home') pk captures from url detail.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container"> {% if messages %} {% for message in messages %} <div class="alert alert-success text-center" role="alert">{{ message }}</div> {% endfor %} {% endif %} <div class="col-md-3 mx-auto"> <div class="card card-product-grid"> <img src="{{ object.image.url }}"> {% if object.model_name == 'book' %} <div class="text-center">{{ object.author }}: {{ object.title … -
Django Database Router allow_migrate method
I'm trying to setup a database router to route my models to postgresql and redshift. I have an app within my project with multiple models. The database router should route the 1 model to redshift and all others to postgresql, however, I get the below errors when I run migrations. "python manage.py migrate --database redshift" SyntaxError: multiple default values specified for column "id" of table "django_migrations" ProgrammingError: multiple default values specified for column "id" of table "django_migrations" MigrationSchemaMissing: Unable to create the django_migrations table (multiple default values specified for column "id" of table "django_migrations" ) =============================================================== I'm confused by this as I do not have a django_migrations table in redshfit yet, which leads me to believe that my router is not working correctly and my logic for allow_migrate method is not correct. I'm new to django and this has me at my wits end. If anyone can provide any clarifying information or point me in the right direction, I would greatly appreciate it. NOTE: I've looked at the django documentation and built my router based off the examples they provided. Thanks! Below is my router, model Meta class example and database config. routers.py class DbRouter: def db_for_read(self, model, **hints): if … -
Django, rest api post ForeignKey
I am writing REST API in Django, I create model Member where is ForeignKey from User table (auth_user)... method GET work perfectly but with post I have problem... every time I saw error message that fk_id cannot be null. models.py class Member(models.Model): valid_from = models.DateTimeField(null=True, blank=True) valid_to = models.DateTimeField(null=True, blank=True) online = models.IntegerField() vpn_ip = models.CharField(max_length=20, unique=True) created = models.DateTimeField(auto_now_add=True) fk = models.ForeignKey(User, on_delete=models.CASCADE) @property def username(self): return self.fk.username @property def password(self): return self.fk.password @property def email(self): return self.fk.email @property def status(self): return self.fk.is_active @property def admin(self): return self.fk.is_staff @property def fk_id(self): return self.fk.id def __str__(self): return self.username views.py class MemberData(APIView): serializer_class = MemberDataSerializer permission_classes = [IsAuthenticated] def get(self, request, format=None): ''' Retrieves all Member from database ''' data = Member.objects.all() serializer = MemberDataSerializer(data, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): ''' Put new member to database ''' data = { "fk_id": request.data.get('fk_id'), "valid_from": request.data.get('valid_from'), "valid_to": request.data.get('valid_to'), "online": request.data.get('online'), "vpn_ip": request.data.get('vpn_ip'), } serializer = MemberDataSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class MemberDataSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ["id", "fk_id", "username", "password", "email", "status", "admin", "valid_from", "valid_to", "online", "vpn_ip", "created"] and If I try post data as application/json then I saw this error... … -
Django .exclude everyone except object owner
I've got two models: Animal and Pet. Pet has fields 'owner' and 'public'. owner connects object to user who creates it, public is BooleanField type sending information whether object should be visible to others or not. I want my website to show all of current user pets whether their attribute is set to True or False, and to show public pets of other users. My models.py from django.db import models from django.contrib.auth.models import User class Animal(models.Model): spec = models.CharField(max_length=50,) type = models.CharField(max_length=50) cute = models.BooleanField(default=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.spec class Pet(models.Model): animal = models.ForeignKey(Animal, on_delete=models.CASCADE) name = models.CharField(max_length=50) color = models.CharField(max_length=50) age = models.DecimalField(max_digits=3, decimal_places=0) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) public = models.BooleanField(default=False) def __str__(self): return self.name and function in views.py @login_required def animal(request, animal_id): animal = Animal.objects.get(id=animal_id) pets = animal.pet_set.filter(owner=request.user).order_by('-date_added') # <----- context = { 'animal': animal, 'pets': pets, } return render(request, 'animals/animal.html', context) I've tried this: for pet in pets: if pet.owner != request.user and pet.public == False: pets = pets.exclude(pet) but it messed up my list. Could you help me figuring it out? -
Deploying Django Web API to AWS Elastic Beanstalk server issue
I am trying to create venv and application in Elastic Beanstalk, but getting some error, so it is not finishing to deploy. To fix the issue, I tried downgrading my Django version from 4.0 to 3.2. Also did same with Python. In order to understand and find the issue, I'll provide here: .ebextensions/django.config my_site/settings.py requirements.txt logs from server deployment platform settings I also collected all static files using python3 manage.py collectstatic and added all environment variables needed django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: my_site.wsgi:application settings.py Django settings for my_site project. Generated by 'django-admin startproject' using Django 4.1.5. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path from os import getenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = getenv("DJANGOPASS") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = getenv("IS_DEVELOPMENT", True) ALLOWED_HOSTS = [getenv('APP_HOST')] # Application definition INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
err too many redirects.this page isnt working now on django
i was trying to create a registration form html page for my django project.but i ended up in a "too many redirects error".can anyone help me with this? iam new to django. here's my code : from . import views from django.urls import path app_name = 'credentials' urlpatterns = [ path('register/', views.register, name='register'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout') ]``` ` def register(request): if request.method == 'POST': username = request.POST['username'] firstname = request.POST['first_name'] lastname = request.POST['last_name'] email = request.POST['email'] password = request.POST['password'] confirmpassword = request.POST['password2'] ``if password == confirmpassword: if User.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request, 'Email Taken') return redirect('register')` ` user = User.objects.create_user(username=username, first_name=firstname, last_name=lastname, email=email, password=password) user.save() messages.info(request, 'USER REGISTERED') print('USER REGISTERED') else: messages.info(request, 'password did not match!!') return redirect('credentials:register') return redirect('/') return render(request, 'register.html') -
When should I use Django media files instead of static files for a very large number of images that are not user-uploaded files?
My Django web app serves up millions of images (not including the regular images such as site logos that are normally served up as static assets and are version controlled). These images will only ever be placed on the server by an admin, and they will never be stored in version control. Using Django's MEDIA_URL/MEDIA_ROOT seems the obvious way to store and serve these images, however the Django docs (https://docs.djangoproject.com/en/4.1/topics/files/) say that these file access methods are for 'those [files] uploaded by a user', which is not the case for my large collection of images. Please can someone advise me what the best practice is to handle these type of images: MEDIA_URL/MEDIA_ROOT or STATIC_URL/STATIC_ROOT. Many thanks. I have tried and tested both methods (MEDIA_URL/MEDIA_ROOT or STATIC_URL/STATIC_ROOT) of serving these images and both work, however I'm sure one method is preferable to the other. One point of concern going down the STATIC_URL route would be how long it takes collectstatic to find and move millions of images. There is an expectation that new batches of images (up to 100k per batch) will be added to the collection of images over time; I'm unsure how well collectstatic will scale up to this … -
Django fields help_text argument position in template
I have this code: class CreateListing(forms.Form): image = forms.CharField(label="Image URL", required=False, max_length=16384, help_text="Optional") Result is But is not nice UI arrangement. I want be same the↓: In Form Fields Documentation: The help_textarguments is wrapped in <span> element which is placed after <br> one. How setting Help_text final UI be same I want above? With grace arrangement. -
chat application using channels and django
I was following the tutorial on channels page https://channels.readthedocs.io/en/stable/tutorial/part_1.html but at the end of the second part the websocket should be working but in my case it says : WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/g/' failed: and on the backend i get: [23/Feb/2023 17:01:28] "GET /chat/lobby/ HTTP/1.1" 200 1660 Not Found: /ws/chat/lobby/ [23/Feb/2023 17:01:28] "GET /ws/chat/lobby/ HTTP/1.1" 404 2226 when typing 'Hello' i should have got : Type the message “hello” and press enter. You should now see “hello” echoed in the chat log. -
How can I get the products from a main category and sub category in one view?
I have this product model: class Product(models.Model): type = models.CharField(max_length=20, choices=TYPES, default=SI) title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None, related_name="products") body = models.TextField(max_length=5000, null=True, blank=True) image = models.FileField(upload_to=image_directory_path, default='products/default.png', null=True, blank=True) price = models.DecimalField(max_digits=20, decimal_places=2) length = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) width = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) height = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) volume = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) sku = models.CharField(max_length=20, null=True, blank=True) stock = models.DecimalField(max_digits=30, decimal_places=0) user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="products") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "product" verbose_name_plural = "products" db_table = "products" def __str__(self): return self.title and this category model: class Category(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=200, blank=True, null=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True ,related_name='sub_categories') created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "category" verbose_name_plural = "categories" db_table = "product_categories" unique_together = ('name', 'parent',) def __str__(self): return self.name def get_absolute_url(self): return self.slug At the moment I can only see the products from the category last in the hierarchy. If I go up to a parent category I cannot see any products. How can I get products from the parent (main category) and also … -
How to use csrf_token in Django RESTful API and React-Native?
I am trying to enable CSRF protection for a django - React Native application, I am familiar with the its process with React, from the django documentation at https://docs.djangoproject.com/en/3.1/ref/csrf/#ajax I get an error from if (document.cookie && document.cookie !== ""), is there an alternate way to enable the csrf apart from what is in this documentation or there is a change i need to make this piece of code function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); I am getting an error, with document -
Get attribute list after a django query filter
I have a WathList model: class Watchlist(models.Model): item = models.ForeignKey(Auction, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.user}\t\tItem: {self.item}" and I want to obtain all the item after performing a query def view_watchlist(request): active_listings = Auction.objects.filter(status=True) # watchlist_items = Watchlist.objects.filter(user=request.user).values('items') # for watchlist_item in watchlist_items: # print(watchlist_item.item) # print(watchlist_items.values('items')) return render(request, "auctions/index.html", { "listings": active_listings, }) to pass all the watchlisted items. Is it possible to make it without using a for loop? I tried to use .values method, .values_list and .only but did not work out: To make it work I created a empty list and a for loop def view_watchlist(request): watchlist_items = Watchlist.objects.filter(user=request.user).only('item') watchlist = [] for watchlist_item in watchlist_items: watchlist.append(watchlist_item.item) return render(request, "auctions/index.html", { "listings": watchlist, }) But I suspect there is a more elegant way to do it. Maybe using related_name when defining the model? -
Django rest unauthorize error even though that function not have any type of authentication
First of all whatever happening with me is very weired i have a django rest framework api and a nextjs frontend from the frontend i can call,login,signup,getProducts api but when i trying to call the verify otp route it is giving me unauthorize error even though that view have no authentication there as you can see from the server logs I can call the verify-otp by postman but when i am trying to call through nextjs it is giving the error here is the function from where i am calling the verify-otp ` ` export const handleVerifyOtp = async(otp,mobile_number) =>{ try { let data = { "otp":`${otp}`, "mobile_number":`${mobile_number}` } const response = await axios.post(`${API_URL}users/verify-otp/`,data); // dispatch(loginSuccess(response.data.data)); console.log("the response is",response.data) return response.data; } catch (error) { console.log("the error is",error) return error; } }`` In way to find solution i have checked every way i can find mistake here is python view which i am using there @api_view(['POST']) def verify_otp(request): print("GOT s") now = timezone.now() data = request.data otp = data['otp'] mobile_number = data['mobile_number'] -
In Django, querysets with multiple models evaluate very slowly
I have a Django project which I'm using to learn about optimizing searches in Django. I'm running Django 3.2 with a Postgres backend in a Docker container. I have two models, Chant and Sequence, which have the same fields, one view per model to search for instances of that model, and a combined search view, which searches for instances of both models and displays the results in a combined list. When I populate the database with a bunch of objects and try searching for things, the combined search view runs significantly slower than when searching for instances of a single model. Here are the relevant parts of my models.py: from django.db import models class Chant(models.Model): std_full_text = models.TextField(blank=True, null=True) class Sequence(models.Model): std_full_text = models.TextField(blank=True, null=True) Here is views/chant.py (views/sequence.py is the same, but with "sequence" and "Sequence" substituted for "chant" and "Chant"): from django.core.paginator import Paginator from django.views.generic import ListView from main_app.models import Chant class ChantSearchView(ListView): model = Chant template_name = 'chant_search.html' context_object_name = 'chants' paginate_by = 100 def get_queryset(self): query = self.request.GET.get('q') if query: return Chant.objects.filter(std_full_text__icontains=query) else: return Chant.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) query = self.request.GET.get('q', '') page_number = self.request.GET.get('page', 1) paginator = Paginator(self.get_queryset(), self.paginate_by) page_obj = …