Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Method "PATCH" not allowed error in django
I have django rest framework and with generics views. Whenever I try to make a PATCH request, I get an error that method not allowed. Below is my views.py code class VisitorsLogBooktbViewSet(generics.ListCreateAPIView): queryset = VisitorsLogBooktb.objects.all() serializer_class = VisitorsLogBooktbSerializer class Visitor_data(generics.RetrieveUpdateDestroyAPIView): queryset = models.VisitorsLogBooktb.objects.all() serializer_class = VisitorsLogBooktbSerializer and below is my urls.py code in the app root urlpatterns = [ path('', VisitorsLogBooktbViewSet.as_view(),), path('api/All-visitors/', Visitor_data.as_view(),), ] I have tried changing the generics views by creating views only for updates using just generics.UpdateAPIView......But it still doesn't work. -
django project on macbook pro M1 pro crashed with illegal hardware instruction
environment: 16-inch,2021 cpu: Apple M1 Pro mermory: 16 GB os version: 14.4.1 (23E224) python version: 2.7.15 i try to run "python manage.py runserver 0.0.0.0:8080", but i got illegal hardware instruction.(history project on my company is using python2.7&Django==1.11.29) below is the traceback on osx system report; ------------------------------------- Translated Report (Full Report Below) ------------------------------------- Process: python2.7 [20108] Path: /Users/USER/*/python2.7 Identifier: python2.7 Version: ??? Code Type: X86-64 (Translated) Parent Process: zsh [19681] Responsible: pycharm [750] User ID: 505 Date/Time: 2024-05-04 23:55:26.3734 +0800 OS Version: macOS 14.4.1 (23E224) Report Version: 12 Anonymous UUID: 5CBB7AC0-C198-33B7-4503-8B049D36B4D6 Sleep/Wake UUID: AC988E56-79A2-4466-AAD1-47F1578D8084 Time Awake Since Boot: 22000 seconds Time Since Wake: 3855 seconds System Integrity Protection: enabled Notes: PC register does not match crashing frame (0x0 vs 0x10CD53688) Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4 Terminating Process: exc handler [20108] Error Formulating Crash Report: PC register does not match crashing frame (0x0 vs 0x10CD53688) Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 corecext.so 0x10cd53688 initcorecext + 9048 1 libpython2.7.dylib 0x10cfe9df6 _PyImport_LoadDynamicModule + 150 2 libpython2.7.dylib 0x10cfe848f import_submodule + 319 3 libpython2.7.dylib 0x10cfe7ebe load_next + 270 4 libpython2.7.dylib 0x10cfe6c9b PyImport_ImportModuleLevel + 939 5 libpython2.7.dylib 0x10cfbd0d7 … -
how to load the sale price based on the selecter with django
hi I am a beginner on django and I would like to display the sale price depending on the product selected, see my source codes below. I'm stuck and I can't unblock, please I need your help. Thanks for your help the sales model: class Sale(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) product = models.ForeignKey('Product', on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) sale_price = models.PositiveIntegerField(default=0) montant_total = models.CharField(max_length=15, default=0) def __str__(self): return self.montant_total the views : def addSale(request=None): current_sale = Sale() list_user = User.objects.all().order_by('-username') list_product = Product.objects.all().order_by('-name') if request.POST: if request.POST.get('user') != "": current_sale.user = User.objects.get(id=request.POST.get('user')) if request.POST.get('product') != "": current_sale.product = Product.objects.get(id=request.POST.get('product')) if request.POST.get('quantity') != "": current_sale.quantity = request.POST.get('quantity') if request.POST.get('sale_price') != "": current_sale.sale_price = request.GET.get('price') if request.POST.get('montant_total') != "": current_sale.montant_total = request.POST.get('montant_total') current_sale.save() return redirect('products-list') context = {'sale': current_sale, 'list_user': list_user, 'list_product': list_product} return render(request, 'daara/add_sale.html', context) the add_sale.html template: <div class="card-body"> <form method="POST"> {% csrf_token %} <div class="form-group col-md-6"> <label for="utilisateur">Utilisateur</label> <select class="form-control" name="user"> <option value="1" selected="selected">Selectionez un utilisateur</option> {% for user in list_user %} {% if user.id == sale.user.id %} <option value="{{sale.user.id}}" selected="selected">{{sale.user.username}}</option> {% else %} <option value="{{user.id}}">{{user.username}}</option> {% endif %} {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="produit">Produit</label> <select class="form-control" name="product" id="product"> <option value="0" selected="selected">Selectionez un produit</option> … -
Whenever I try running the server for django in my virtual enviroment it doesn't work
Whenever I try running the server for django in my virtual enviroment it doesn't work. Example: python manage.py runserver Replies: NameError: name 'include' is not defined I know it's referencing my urls.py where I say path('hello/', include("hello.urls")) but I need that for me to do what I'm doing I tried looking on stack overflow, youtube, fixing it, trying something my ide said would work. All I wanted it to do was run a server that I could copy and paste the url for and would be able to access it but no. -
Choosing Between Django and Headless CMS for Website Development: Seeking Advice
I've been delving into the decision-making process for a website project I'm working on for a hotel owner. They're keen on having a robust admin interface to manage various aspects of the site, including a gallery, blog, events, emails, and payments. While I've done my fair share of research, I'm still grappling with the decision between using Django for its powerful admin capabilities or exploring the possibility of using an open-source headless CMS like Strapi or Payload to streamline content management and integration with a Next.js frontend. Despite my efforts, I find myself in a bit of a quandary. Here's where I could use your expertise: Development Complexity: In your experience, how does the development complexity compare between building everything within Django versus integrating a headless CMS with a Next.js frontend? Admin Interface: How user-friendly and customizable are the admin interfaces provided by open-source headless CMS platforms like Strapi or Payload compared to Django Admin? Performance and Scalability: Are there any performance or scalability considerations I should keep in mind when choosing between Django and a headless CMS for this project? Cost and Deployment: Which open-source headless CMS options allow self-hosting without additional costs for deployment? How do the deployment … -
Custom admin inline for manytomany field
I have a manytomany field called following where all the other users a user is following is stored. I want to be able to view, add, delete the users in this per user in the field. This is my attempt with creating a custom inline in admin can someone help with getting this to work as desired. models.py (following field in class user(abstractuser): following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Following', blank=True, symmetrical=False) Admin.py: from django.contrib import admin from .models import User class FollowingInline(admin.TabularInline): model = User.following.through fk_name = 'from_user' extra = 1 # Allow adding one extra form for adding followers class UserAdmin(admin.ModelAdmin): list_display = ('username', 'full_name', 'email') inlines = [FollowingInline] def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: if instance.to_user_id: # Check if a user is selected instance.save() elif instance.id: # Check if an existing instance is being deleted instance.delete() formset.save_m2m() admin.site.register(User, UserAdmin) -
QuerySet class does not inherit from TranslatableQuerySet
I'm working on my Django project, and currently I'm working on localization and translating a website. I have a problem with translating my post for blog part. I already have integrated models and everything and I used PublishedManager in order to filter. But now since I used django-parler (from parler.models import TranslatableModel, TranslatedFields), now I got this error which is probably because of TranslatableModel. I have this error: ImproperlyConfigured at /en/admin/main_app/post/ QuerySet class does not inherit from TranslatableQuerySet models.py class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Status.PUBLISHED) class Post(TranslatableModel): # Your existing fields and methods... # My custom manager published = PublishedManager() # Other methods... How do I solve this? Thanks in advance! -
Django: unexpected keyword arguements when trying to create new object
i'm trying to create a new object but i keep getting an error message "player_team() got unexpected keyword arguments: 'player', 'team'" I'm just starting out in Django and working on a personal project. I've tried my best to problem solve but I'm still getting this unexplained error. Here is my Model class player_team(models.Model): Player = models.ForeignKey(player, on_delete = models.CASCADE) Team = models.ForeignKey(team, on_delete = models.CASCADE, null=True) here is my view def assign_team(request): if request.method == "POST": PlayersID = request.POST.get("Players") TeamsId = request.POST.get("Teams") player_team.objects.create( player = PlayersID, team = TeamsId ) return redirect(request.META['HTTP_REFERER']) -
how do i make a form submission permanent in my django project?
in my django project models.py = from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone class User(AbstractUser): profile_pic = models.ImageField(upload_to='profile_pic/') bio = models.TextField(max_length=160, blank=True, null=True) cover = models.ImageField(upload_to='covers/', blank=True) whatsapp = models.CharField(max_length=25, blank=True, null=True) def __str__(self): return self.username def serialize(self): return { 'id': self.id, "username": self.username, "profile_pic": self.profile_pic.url, "first_name": self.first_name, "last_name": self.last_name } class Post(models.Model): creater = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') date_created = models.DateTimeField(default=timezone.now) content_text = models.TextField(max_length=140, blank=True) content_image = models.ImageField(upload_to='posts/', blank=True) likers = models.ManyToManyField(User,blank=True , related_name='likes') savers = models.ManyToManyField(User,blank=True , related_name='saved') comment_count = models.IntegerField(default=0) def __str__(self): return f"Post ID: {self.id} (creater: {self.creater})" def img_url(self): return self.content_image.url def append(self, name, value): self.name = value class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') commenter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='commenters') comment_content = models.TextField(max_length=90) comment_time = models.DateTimeField(default=timezone.now) def __str__(self): return f"Post: {self.post} | Commenter: {self.commenter}" def serialize(self): return { "id": self.id, "commenter": self.commenter.serialize(), "body": self.comment_content, "timestamp": self.comment_time.strftime("%b %d %Y, %I:%M %p") } class Follower(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers') followers = models.ManyToManyField(User, blank=True, related_name='following') def __str__(self): return f"User: {self.user}" views.py = from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt … -
Django prefetch_related nested filter
Got classes of Student, StudentGroup, Pair(double lesson), Mark and a queryset: class Student(models.Model): student_group = models.ForeignKey("StudentGroup", ...) ... class StudentGroup(models.Model): ... class Pair(models.Model): pair_time = models.TimeField(...) pair_date = models.DateField(...) student_group = models.ForeignKey("StudentGroup", ...) ... class Mark(models.Model): student = models.ForeignKey("Student", ...) pair = models.ForeignKey("Pair", ...) queryset = ( Student.objects .select_related("student_group") .prefetch_related( Prefetch( "student_group__pairs", queryset=( Pair.objects .order_by("-pair_date", "pair_time") .select_related("subject") .prefetch_related( Prefetch( "marks", # This is what I need to filter. queryset=Mark.objects.filter(student_id=**???**), to_attr="student_marks" ) ) .all() ), to_attr="student_pairs" ) ) .all() ) I need to filter marks by student_id. How can I do it? Tried F, Q, Subquery, but I can't get how to use'em. -
Django Rest Framework Query issue with filter()
this is my model: class PmPrice(models.Model): created_at = models.DateTimeField() price = models.DecimalField(max_digits=6, decimal_places=2) listing = models.ForeignKey("PmListing", models.DO_NOTHING) seller = models.ForeignKey("PmSeller", models.DO_NOTHING) class Meta: managed = False db_table = "pm_price" this is my serializer: class PmPriceListSerializer(serializers.ModelSerializer): url = serializers.ReadOnlyField(source="listing.url") shop = serializers.ReadOnlyField(source="listing.shop.name") name = serializers.ReadOnlyField(source="listing.product.name") ean = serializers.ReadOnlyField(source="listing.product.ean") uvp = serializers.ReadOnlyField(source="listing.product.uvp") sku = serializers.ReadOnlyField(source="listing.product.sku") seller = serializers.ReadOnlyField(source="seller.name") class Meta: model = PmPrice fields = ( "url", "shop", "name", "ean", "sku", "uvp", "price", "created_at", "seller", ) def to_representation(self, instance): data = super().to_representation(instance) return data and this is a method inside my filters.py class that I'm using on my view, and this is causing me headache: def get_by_last_two_cheapest(self, queryset, name, value): latest_date_subquery = ( queryset.annotate(datum=TruncDate("created_at")) .values("datum") .order_by("-datum") .annotate(latest_date=Max("datum")) .values("latest_date")[:1] ) # Second subquery to get the second latest date second_latest_subquery = ( queryset.filter( created_at__date__lt=Subquery(latest_date_subquery), ) .annotate(datum=TruncDate("created_at")) .values("datum") .order_by("-datum") .annotate(latest_date=Max("datum")) .values("latest_date")[:1] ) # Concatenate the results of the subqueries to get the dates dates = list() dates.append(str(latest_date_subquery[0]["latest_date"])) dates.append(str(second_latest_subquery[0]["latest_date"])) print(dates) # Perform the necessary filtering and annotation qs = ( queryset.filter(created_at__date__in=dates) .values("listing_id", "created_at__date") .annotate(cheapest_price=Min("price")) ) print(qs) print(len(qs)) # Retrieve the corresponding rows with the cheapest prices result_queryset = queryset.filter( created_at__date__in=dates, listing_id__in=qs.values_list("listing_id", flat=True), price__in=qs.values_list("cheapest_price", flat=True), ).order_by("-created_at", "listing_id") print(len(result_queryset)) return result_queryset Now I want to retrieve the … -
While mutating shares of a Post, I get "Variable '$postId' got invalid value {'isTrusted': True, '_vts': 1714830156331} ID cannot represent value
Using Vue 3 and Django backend using Graphql, I want to count button click shares.The problem is referring to PostId of Post model in django and graphene-django gives me error: "Variable '$postId' got invalid value {'isTrusted': True, '_vts': 1714830156331} ID cannot represent value. How can I refer to PostId from the Django database? In SocialMediaButtons.vue: const toggleShares = (postId) => { navigator.clipboard.writeText(window.open (shareUrl, '_blank')); copied.value = true; console.log('Post Shared!'); store.toggleShares(postId); }; And using Pinia state management I have userInteraction: toggleShares(postId) { const postStore = usePostStore(); const post = postStore.getPostBySlug(postId); if (post) { const url = window.location.origin + '/post/' + post.slug; window.open(url, '_blank'); } this.shares += 1; // Increment shares count console.log('Share button clicked. Shares:', this.shares); this.updateBackend(postId, 'shares', this.shares); }, async updateBackend(postId, field, value) { // Send GraphQL mutation to update backend const response = await apolloClient.mutate({ mutation: gql` mutation UpdatePostInteractions($postId: ID!, $likes: Int!, $dislikes: Int!, $shares:Int!) { updatePostInteractions(postId: $postId, likes: $likes, dislikes: $dislikes, shares:$shares) { post{ postId likes dislikes shares} } } `, variables: { postId, likes: field === 'likes' ? value : this.likes, dislikes: field === 'dislikes' ? value : this.dislikes, shares: field === 'shares' ? value : this.shares, }, }); -
LoginRequiredMixin not work Properly with login URL
I'm working on a Django project where I have implemented a ListView to display a list of checkout items (ListCheckoutView). I want to require authentication for accessing this view, but currently, it's accessible even without logging in. I've tried using the LoginRequiredMixin, but it doesn't seem to be working as expected. In the checkout.html works properly from django.urls import path from .views import BooksListView, BooksDetailView, BookCheckoutView, OrderComplete, SearchResultsListView, ListCheckoutView urlpatterns = [ path('', BooksListView.as_view(), name='list'), path('books/', ListCheckoutView.as_view(), name='list2'), path('<int:pk>/', BooksDetailView.as_view(), name='detail'), path('<int:pk>/checkout/', BookCheckoutView.as_view(), name='checkout'), path('complete/', OrderComplete, name='complete'), path('search/', SearchResultsListView.as_view(), name='search_results'), ] from django.views.generic import ListView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Book, Order class ListCheckoutView(LoginRequiredMixin, ListView): model = Book template_name = 'base.html' login_url = 'login' class BookCheckoutView(LoginRequiredMixin, DetailView): model = Book template_name = 'checkout.html' login_url = 'login' -
Django Form - POST method not recognised as POST in views
In my django project, I am trying to create a form which the user will access through a specific url. By clicking on the url, the user will be automatically redirected to a pager_id. Inbetween the user click on said url and being redirected to page_id, a form will be passed in the background, without any template. Slight problem, the form does not pass the if request.method == "POST":. I know that because the print rendered in the console is this is not a post request. I think its the probably the first time Im not using a template to render theform. I would normally specify something like: <form "method="POST"> {% csrf_token %} </form> Question: Assuming this what is causing problem: Does Django require to use a template to render the form? Or is there a way to specify method="POST" in a different way? Or is there something else I am not seeing? views.py def function(request, page_id): form = myform(request.POST) if request.method == "POST": print('this is a post request') if form.is_valid(): data = form.save(commit=False) ... data.save() return redirect('page', page_id=page_id) else: form = myform() print('this is not a post request') #<-- this is what gets printed in the console else: print('Come … -
django gives me a bad request error 400 when I want to fill a table
when I want to fill in the MRZ table it gives me the bad request error knowing that all the attributes are retrieved from my flutter mobile app except for the ccp_account which gives me nothing when I want to print it I retrieve it from the backend and not from flutter. Here is the code for the Mrz models class MRZ(models.Model): id_mrz = models.AutoField(primary_key=True) FK_compte_ccp = models.OneToOneField(CompteCcp, on_delete=models.CASCADE) photo_passport = models.ImageField(upload_to='mrz_photos/') birthDate = models.DateField(null=True, blank=True) documentNumber = models.CharField(max_length=100, null=True, blank=True) expiryDate = models.DateField(null=True, blank=True) And here is the code of the views where i have the probleme def remplir_mrz(request): if request.method == 'POST': try: # Récupérer le token JWT depuis le corps de la requête token = request.headers.get('Authorization').split(' ')[1] print("Données reçues :", request.POST) print("Token JWT récupéré :", token) # Vérifier si le token n'est pas vide if token: # Décoder le token JWT pour obtenir l'identifiant de l'utilisateur decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) print("Token JWT decoder :", decoded_token) user_id = decoded_token['user_id'] print("user id :", user_id) # Rechercher le compte CCP associé à l'utilisateur compte_ccp = get_object_or_404(CompteCcp, FK_compte_app=user_id) # Vérifier si les données contiennent une clé 'photo_passport' if 'photo_passport' in request.FILES: # Extraire l'image image_file = request.FILES['photo_passport'] # Construire le … -
generate PDF with picture Django rest framework
import weasyprint def admin_order_pdf(request, sell_id): # working fine try: sell = Sell.objects.get(id=sell_id) except Sell.DoesNotExist: return HttpResponse('Sell object does not exist') html = render_to_string('sell_invoice.html', {'sell': sell}) response = HttpResponse(content_type='application/pdf') app_static_dir = os.path.join(settings.BASE_DIR, 'pdf', 'static') css_path = os.path.join(app_static_dir, 'css', 'css.css') response['Content-Disposition'] = f'filename=sell_{sell.id}.pdf' weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(css_path)]) return response With the code, I can easily generate a PDF. I can design with inline CSS and. CSS files on my PDF, but I can't pass any photos or pictures.Is it possible to add picture on a PDF ?if yes,? How can I pass a picture/logo on my PDF? -
Setting DateTimeRangeField programmatically via a ModelForm
I'm trying to set the DateTimeRangeField in a Django ModelForm form, but I'm getting a validation error "this field is required". It seems that Django is not recognizing nor psycopg2.extras.DateTimeTZRange instance, nor any date strings as a valid value. How can I set the value of DateTimeRangeField? Striped down example: # models.py from django.contrib.postgres.fields import DateTimeRangeField class Reservation(models.Model): range = DateTimeRangeField() # forms.py class ReservationForm(forms.ModelForm): class Meta: model = Reservation exclude = [] # test.py from psycopg2.extras import DateTimeTZRange form = ReservationForm(data={ 'range': DateTimeTZRange( lower='2024-04-21 10:00', upper='2024-04-21 11:00' ) }) if form.is_valid(): form.save() else: print(form.errors.as_data()) Output: {'range': [ValidationError(['This field is required.'])]} -
How to manage language redirection in Django middleware with user authentication?
I am developing a middleware in Django to manage language redirection based on the user's language preference, which can be stored in the database or specified in a cookie. The middleware needs to handle URLs that include a language prefix, ensuring they match the user's preferred language, especially after the user logs in. The middleware is designed to redirect users to the correct language version of a page. However, when a user logs in and a next parameter is used to specify a redirect URL, the language prefix in this URL sometimes does not match the user's preferred language. This results in users being redirected to the default language instead of their preferred language. Here is the middleware implementation: from django.http import HttpResponseRedirect from django.utils.http import urlencode from urllib.parse import urlparse, urlunparse, parse_qs from django.utils.translation import activate class UserLanguageMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) excepted_paths = ["/stripe/", "/api/", "/media/", "/static/", "/set-language/"] if any(request.path.startswith(path) for path in excepted_paths): return response preferred_language = None if request.user.is_authenticated: preferred_language = getattr(request.user, "language", None) if not preferred_language: preferred_language = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME, "en") activate(preferred_language) current_cookie_language = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if current_cookie_language != preferred_language: response.set_cookie( settings.LANGUAGE_COOKIE_NAME, preferred_language, max_age=365 * 24 * 60 * … -
Calling the create method of a ModelViewSet from another ModelViewSet
I need to create objects of model B from the views.py file of A. I was able to do it using the serialiser of B (see # OLD METHOD using serializer) but I would like to know how to use the create method of viewset B from viewset A In the function generate_drf_format, I tried to manually instantiate and invoke the create action in Viewset B but it's not working. I am getting the error message: AttributeError: 'ViewSetB' object has no attribute 'request' class BViewSet(viewsets.ModelViewSet): queryset = B.objects.all() serializer_class = BSerializer class ViewSetA(viewsets.ModelViewSet): queryset = A.objects.all() serializer_class = ASerializer def create(self, request, *args, **kwargs): form_data = request.data # map front-end request to DRF model mapped_data = generate_drf_format(form_data) serializer = self.get_serializer(data=mapped_data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def generate_drf_format(form_data): participants_ids = [] if 'participants' in form_data: participants_list = form_data['participants'] if len(participants_list) > 0: request = HttpRequest() for participant_data in participants_list: request.data = participant_data # Manually instantiate and invoke action in Viewset B viewset_b = UserViewSet() viewset_b.create(request=request) # OLD METHOD using serializer # b_serializer = BSerializer(data=participant_data) # if b_serializer.is_valid(): # b_serializer.save() # participants_ids.append(b_serializer.data['id']) # else: # return Response(b_serializer.errors) new_data = generate_some_obj(form_data, participants_ids) return new_data Any suggestion of how to … -
JSONDecodeError : Extra data: line 1 column 5 (char4) when using an API & JSON in Django
When i use the SVD Stability.api API there is an error shown to me which is like this in Django, the API i used is this https://platform.stability.ai/docs/api-reference#tag/Image-to-Video this is my view.py def img2vid(request): error = None video = None form = ImageForm() context = None if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() realImage = request.FILES['Image'] imageName = str(form.cleaned_data['Image']) # check the extension of the image and return an error if its happen ext = pathlib.Path(imageName).suffix.replace(".", "") if (ext != "png" and ext != "jpeg" and ext != "jpg"): error = "Invalid Extension . PNG & JPEG are allowed only" return render(request, "img2vid.html", {'form': form, 'error': error}) imgloc = rf'media\images\\{imageName}' imgloc2 = imgloc.strip().replace(" ", "_") image = Image.open(imgloc2) imgSize = image.size w, h = image.size new_w, new_h = w, h greater = h if h < w: greater = w if 300 <= abs(w - h) <= 2000: new_w, new_h = 1024, 576 elif h > w: if 300 <= abs(w - h) <= 2000: new_w, new_h = 576, 1024 if 0 <= abs(w - h) <= 299: new_w, new_h = 768, 768 new_image = image.resize((new_w, new_h)) new_image.save(imgloc2) response = requests.post( f"https://api.stability.ai/v2beta/image-to-video", headers={ "authorization": f"Bearer apitoken"}, files={"image": … -
Django 4.2.11 is not supported with SQL Server
I am using Django 4.2.11 and connected to django-pyodbc-azure Version: 2.1.0.0. The code was running fine but now I start getting an error and can't run it. Did anyone knows how to solve this problem? Error: /Users/zinabadnan/Library/Python/3.9/lib/python/site-packages (from asgiref<4,>=3.6.0->django) (4.9.0) (env) zinabadnan@Zinabs-MacBook-Air system % python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/zinabadnan/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/zinabadnan/Library/Python/3.9/lib/python/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/zinabadnan/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/zinabadnan/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/zinabadnan/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/zinabadnan/Library/Python/3.9/lib/python/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/zinabadnan/Library/Python/3.9/lib/python/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/zinabadnan/Library/Python/3.9/lib/python/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/zinabadnan/Library/Python/3.9/lib/python/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, … -
Ways to providing data to your frontend
As I progress with the backend development of this website ( with django and DRF but i don't think it matters in this question), I've come across a question regarding the organization of API endpoints, particularly with regards to providing data for the frontend. My goal is to ensure that the backend implementation is both standard-compliant and optimized for performance. For example, let's consider the structure of the homepage of the website. The frontend will display various components such as banners, most popular services, newest products, and potentially other unrelated data * unrelated in terms of they are separate entities in database). While I have separate endpoints for products and services and .., I'm uncertain whether this approach is suitable for the homepage. My main concern is whether it's preferable to maintain separate endpoints for products and services, potentially requiring the frontend to make multiple requests to gather all the necessary data for the homepage. Alternatively, should I consider consolidating the data needed for the homepage into a single endpoint to streamline frontend data retrieval? I'm seeking advice on best practices for structuring API endpoints in this scenario. Are there established conventions or guidelines for organizing endpoints in a way … -
My images uploaded from ckeditor5 in django to cloudflare r2 stop working
So the images initially upload and are appear in my posts but eventually the link stops working after an hour or so. Has anyone had this issue before? It looks like they are going into the rootfolder in my mediabucket. Is anyone else using R2, Django, and CKeditor5 I've been messing with custom media storage but can't really find an example of what I'm trying to do -
Trying to utilize Supabase S3 Storage with Django
`if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv("SUPA_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("SUPA_SECRET_KEY") AWS_STORAGE_BUCKET_NAME = "images" AWS_S3_REGION_NAME = os.getenv("SUPA_S3_REGION_NAME") AWS_ENDPOINT_URL = os.getenv("SUPA_S3_DOMAIN") # s3 static settings STATIC_LOCATION = "static" STATICFILES_STORAGE = "storages.backends.s3boto.S3BotoStorage" # s3 public media settings DEFAULT_FILE_STORAGE = "storages.backends.s3boto.S3BotoStorage" else: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles_build", "static") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media/") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)` WARNINGS: ?: (staticfiles.W004) The directory '/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/static' in the STATICFILES_DIRS setting does not exist. Traceback (most recent call last): File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/manage.py", line 22, in <module> main() File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect handler(path, prefixed_path, storage) File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 368, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 278, in delete_file if self.storage.exists(prefixed_path): File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/storages/backends/s3.py", line 514, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/botocore/client.py", line 565, in _api_call return self._make_api_call(operation_name, kwargs) File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/botocore/client.py", line 958, in _make_api_call api_params = self._emit_api_params( File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/botocore/client.py", line 1084, in _emit_api_params self.meta.events.emit( File "/Users/admin/Desktop/code/Zions_AutoERP/Zions_AutoERP/.venv/lib/python3.9/site-packages/botocore/hooks.py", line 412, in emit return self._emitter.emit(aliased_event_name, … -
Field Validator not getting called in Model Serializer
I am quite new to Django. I am working on a django app which needs to store films, and when I try to load film instances with the following program: import os import json import requests # Assuming the JSON content is stored in a variable named 'films_json' json_file_path: str = os.path.join(os.getcwd(), "films.json") # Load the JSON content from the file with open(json_file_path, "r") as file: films_json: dict = json.load(file) # URL of the endpoint endpoint_url = "http://127.0.0.1:8000/site-admin/add-film/" for film_data in films_json["films"]: print() print(json.dumps(film_data, indent=4)) response: requests.Response = requests.post(endpoint_url, json=film_data) if response.status_code == 201: print(f"Film '{film_data['name']}' added successfully") else: print(f"Failed to add film '{film_data['name']}':") print(json.dumps(dict(response.headers),indent=4)) print(f"{json.dumps(response.json(), indent=4)}") I get the following response (for each film): { "name": "Pulp Fiction", "genre": "Crime", "duration": 154, "director": "Quentin Tarantino", "cast": [ "John Travolta", "Uma Thurman", "Samuel L. Jackson", "Bruce Willis" ], "description": "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", "image_url": "https://m.media-amazon.com/images/M/MV5BNGNhMDIzZTUtNTBlZi00MTRlLWFjM2ItYzViMjE3YzI5MjljXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_.jpg", "release": "1994-00-00" } Failed to add film 'Pulp Fiction': Bad Request { "Date": "Fri, 03 May 2024 22:35:32 GMT", "Server": "WSGIServer/0.2 CPython/3.10.10", "Content-Type": "application/json", "Vary": "Accept, Cookie", "Allow": "POST, OPTIONS", "djdt-store-id": "bf9dc157db354419a70d69f3be5e8dd7", "Server-Timing": "TimerPanel_utime;dur=0;desc=\"User …