Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to properly set up React proxying on a Chromebook?
I am running a Django backend app on port 8000 and would like to configure a React app proxy calling that particular Django backend app. I have added "proxy": "http://localhost:8000", to package.json and used shorthand url notations (such as /api/products) in the axios calls. This setup works fine when running both the React app and the Django app on a Debian machine. However, the same setup fails on my Chromebook (Lenovo Chromebook Duet 2000) with error: > frontend@0.1.0 start > react-scripts start Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options.allowedHosts[0] should be a non-empty string. Attempted to replace the proxy setup with "proxy": "http://127.0.0.1:8000", to no avail. Please let me know what is the culprit and how to make proxying work in this particular case! -
Axios Error and errors with postrgresql on django deployment
simple django/react app just start learning how to deploy with railway. current error is "Unsupported protocol postgresql:" so tried adding "http://" and "https://" to the api url, which gave cors error and still wasn't working, so reverted back to code below. import axios from "axios"; import { ACCESS_TOKEN } from "./constants"; const apiUrl = //protocol missing? "postgresql://postgres:ttNgMy**@monorail.proxy.rlwy.net:50695/railway"; const api = axios.create({ //import anything stored in an enviroment variable baseURL: apiUrl ? apiUrl : import.meta.env.VITE_API_URL, //local http://127.0.0.01 = import.meta.env.VITE_API_URL }); errors: Uncaught (in promise) TypeError: y.response is undefined message: "Unsupported protocol postgresql:" name: "AxiosError" -
many to many serializers error in post api
i have many-to-many relationship between Movie and Person through Cast. I use CastSerializer to create post method to create new movie and new cast relationship, but when call post method, response return AttributeError. I want my post body like this: { ... "title": "string", "genres": [ 0 ], "cast": [ { "charactor": "string", "cast": 0, "order": 2147483647 } ] } AttributeError at /movie/ Got AttributeError when attempting to get a value for field `cast` on serializer `MoviesSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Movie` instance. Original exception text was: 'Movie' object has no attribute 'person'. this is models: class Movie(models.Model): ... cast = models.ManyToManyField(Person,related_name='cast_movies', through="Cast") def __str__(self): return self.title class Cast(models.Model): id = models.AutoField(primary_key=True,null=False,blank=False) movie = models.ForeignKey(Movie,on_delete=models.CASCADE,related_name='casts') cast = models.ForeignKey(Person,on_delete=models.CASCADE,related_name='person') charactor = models.CharField(max_length=200,null=True,blank=True,default='') order = models.IntegerField(null=True) def __str__(self): return self.cast.name + " ("+ self.movie.title + ")" serializers: class CastSerializer(serializers.ModelSerializer): class Meta: model = Cast fields = ['charactor','cast','order'] class MoviesSerializer(serializers.ModelSerializer): genres = serializers.SlugRelatedField( many=True, queryset=Genre.objects.all(),slug_field='id' ) cast = CastSerializer(many = True) class Meta: model = Movie fields = [ ...,'cast'] def create(self, validated_data): genres_data = validated_data.pop('genres', []) cast_data = validated_data.pop('cast', []) movie = Movie.objects.create(**validated_data) for cast in cast_data: Cast.objects.create(movie_id = movie.id,**cast) … -
Complex constraint in a Django model
I have a use case where I want to validate that a field ForeignKey value is in a particular set, so something like: class Role(models.Model): label = models.CharField(max_length=24) class Group(models.Model): roles = models.ManyToManyField(Role, null=False) class Member(models.Model): label = models.CharField(max_length=24) group = models.ForeignKey(Group) role = models.ForeignKey(Role) class Meta: constraints = [ models.CheckConstraint( name="%(app_label)s_%(class)s_role", check=( models.Q(role__in=... valid roles ...) ) ) In other words, only allow a member to have a role if the role is listed in the roles for the group. I can't figure out how to express this. -
403 forbidden error in Django admin even though superuser was already created
Recently, i cloned a project from github to get more familiar with projects written in Django. Previously, everything was running fine, but today when i tried to sign into the Django admin page it gave me this error: 403 Forbidden And returned this in my terminal: Forbidden (Permission denied): /admin/auth/group/add/ raise PermissionDenied django.core.exceptions.PermissionDenied Which confused me, since there was already a superuser created. Can anyone help me solve this? -
My form doesn't return any error in django
I am a Django developer and I am trying two put two forms in one html file(register and login forms), but when I write an invalid input into them, they didn't return any error. views.py def log(request): if request.method == 'POST': print(request.POST) if 'email' in request.POST: regisform = RegisterForms(request.POST) if regisform.is_valid(): print("is valid") clean_data = regisform.cleaned_data user =User.objects.create_user(username=clean_data['user_name'],password=clean_data['password_2'],email=clean_data['email']) login(request,user) messages.success(request, "شما با موفقیت ثبت نام شدید." ) Profile.objects.get(user_id = request.user.id).hearts_time = jdatetime.datetime.today() send_user_notification(user=user, payload={"head":"تبریک", "body":"به سایت ویکی ریاضی حوش آمدید."}, ttl=10) return redirect('home:homepage') else: print("is not valid.") else: form = LoginForms(request.POST) if form.is_valid(): data = form.data print(data) print("running") try: user = authenticate(request, username = data['username'],password=data['password']) print(user) except: user =authenticate(request, email = data['email'],password=data['password']) print(user) if user is not None: login(request, user) messages.success(request, "شما با موفقیت وارد شدید.","warning") else: print('NOT LOGIN') return redirect('home:homepage') else: print("Naderi") form = LoginForms() regisform = RegisterForms() try: content = { 'form':form, 'regist':regisform, } except: content = { 'regist':regisform, } return render(request, 'accounts/login.html',content) forms.py class RegisterForms(forms.Form): user_name = forms.CharField(max_length=30, widget=forms.TextInput(attrs={"placeholder":'username'})) password_1 = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'placeholder':'password'})) password_2 = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'placeholder':'Confirm password'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder':'Email'})) captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) def clean_password_2(self): print('func 1 is begining.') password1 = self.cleaned_data['password_1'] password2 = self.cleaned_data['password_2'] listletter = 'abcdefghijklmnopqrstuvwxyz' listletterc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' adad = '1234567890' print(password1,password2) if password1 != … -
How to inject something at the end of every render in Django?
I want to inject a specific HTML comment at the end of every render of HTML in Django. I don't want to write that at the end of base.html template, but want it to be injected by code. Is there a way for me to do it? -
Django & dependency injection
In the past, I've used dependency-injector, but it looks like it's unmaintained now. :-( Does anyone have any good suggestions for a DI package? I'd want to be able to inject dependencies into views, with the ability to inject mocks in view tests. -
Not able to add Images and videos using quill rich text editor from local machine
Not able to Add Images and videos using Quill.js rich text editor. I have added quill editor in my django blog site,everything works fine but when i try to click image icon to add the image's from local machine i get this box. see this image i'm not able to select images from my local machine to upload in my blog using quill, but when i try to paste url link of the image from the internet then it works perfectly but not from local machine. this is my code :- const ColorClass = Quill.import("attributors/class/color"); const SizeStyle = Quill.import("attributors/style/size"); Quill.register(ColorClass, true); Quill.register(SizeStyle, true); // #stop const toolbarOptions = [ ["bold", "italic", "underline", "strike"], // toggled buttons ["blockquote", "code-block"], ["link", "image", "video", "formula"], [{ header: 1 }, { header: 2 }], // custom button values [{ list: "ordered" }, { list: "bullet" }, { list: "check" }], [{ script: "sub" }, { script: "super" }], // superscript/subscript [{ indent: "-1" }, { indent: "+1" }], // outdent/indent [{ direction: "rtl" }], // text direction [{ size: ["small", false, "large", "huge"] }], // custom dropdown [{ header: [1, 2, 3, 4, 5, 6, false] }], [{ color: [] }, { background: [] … -
Crispy tag leads to Hidden Field TOTAL_FORMS is a required field. error on POST
I have the following form in my template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% crispy blog_form %} {% for form in formset %} {% crispy form %} {% endfor %} <button type="submit">Save</button> </form> However: when I post this I get the following error: Hidden Field TOTAL_FORMS is a required field. and Hidden field INITIAL_FORMS is a required field. This form works well when I don't use the crispy tags. I want to use crispy forms to make the form look good. What am I missing and how can I fix it? My form looks like this: class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ['name','teaser','hero_image','text','video','category_tag','brand_tag','bottle_tag'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Div( Row('name', css_class='form-row my-1'), Row('teaser', css_class='form-control, my-1'), Row('text', css_class='form-control, my-1'), Row('hero_image', css_class='form-control-file form-row my-1'), Row('video', css_class='form-control-file form-row my-1'), Row( Column('category_tag', css_class='form-group col-md-4 my-1'), Column('brand_tag', css_class='form-group col-md-4 my-1'), Column('bottle_tag', css_class='form-group col-md-4 my-1'), ), Submit('submit', 'Save', css_class='my-3 btn btn-secondary') )) class BlogImageForm(forms.ModelForm): class Meta: model = BlogImage fields = ['image'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.form_method = 'post' self.helper.layout = Layout( Div( Row('image', css_class='form-row my-1'), )) -
How to set manifest_storage for ManifestFilesMixin (Django)
I use django-storages to serve my static files from S3. I want to use the ManifestFilesMixin for cache busting my CSS and JS files. The following works fine: from django.contrib.staticfiles.storage import ManifestFilesMixin from storages.backends.s3boto3 import S3Boto3Storage class ManifestS3Storage(ManifestFilesMixin, S3Boto3Storage): pass Except that staticfiles.json is placed in my S3 bucket. I don't want this as explained here. The Django docs mention that it is possible to give a "manifest_storage" argument to the ManifestFilesMixin but I don't know how to do this. The docs mention how to do it for the ManifestStaticFilesStorage class but I don't understand how to do this for the ManifestFilesMixin.