Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update a couple element by one request? HTMX
I have a few dropdowns. First one is parent and the second one is child. I mean when I choose value in first dropdowns, the values in second one are getting updated. Also I have one div for result. So when I pick element from the first dropdown second dropdown and values from result div should be updated somehow by HTMX. Here is a primitive schema of code: <div> <div class="grid-container"> <div id="dropdonw-1"> <select> <option value="1" hx-post="/url" hx-swap="innerHTML" hx-target="#dropdonw-2" <---- How to specify a couple of targets? > VALUE </option> </select> </div> <div id="dropdonw-2"> <select></select> </div> </div> <div id="result-div"></div> </div> -
Django 404 error-page not found, how can I solve this problem?
My project is named main, and when I runserver I get this error.Anybody have any clue how to fix this error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/detail//3 Using the URLconf defined in movieReview.urls, Django tried these URL patterns, in this order: admin/ [name='home'] detail/<str:slug>/<int:id> [name='detail'] category [name='category'] celebrity [name='celebrity'] category/<str:slug>/<int:id> [name='category-movies'] celebrity/<str:slug>/<int:id> [name='celebrity-movies'] recent-released [name='recent-released'] upcoming [name='upcoming'] accounts/register [name='register'] accounts/profile [name='profile'] accounts/changepassword [name='changepassword'] my-reviews [name='my-reviews'] delete-review/<int:id> [name='delete-review'] ^media/(?P<path>.*)$ accounts/ The current path, detail//3, didn’t match any of these. My settings.py file looks like this... """ Django settings for movieReview project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # 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/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Django: Is there a way to apply an aggregate function on a window function?
I have already made a raw SQL of this query as a last resort. I have a gaps-and-islands problem, where I get the respective groups with two ROW_NUMBER -s. Later on I use a COUNT and a MAX like so: SELECT ..., MAX(count) FROM ( SELECT ..., COUNT(group) FROM ( SELECT ... (ROW_NUMBER(ORDER BY ...) - ROW_NUMBER(PARTITION BY ... ORDER BY ...)) AS group .... ) AS x GROUP BY ... ) AS y GROUP BY ... So far, I have finished the innermost query and its possible representation with Django ORM, but when I try to annotate over group , it throws an error: django.db.utils.ProgrammingError: aggregate function calls cannot contain window function calls I haven't yet wrapped my head around using Subquery, but I'm also not sure if that would work at all. I do not need to filter over the window function, only use aggregates on it. Is there a way to solve this with plain Django, or do I have to resort to hybrid raw-ORM queries, perhaps to django-cte ? -
Django - Joining after filtering
Imagine there are a model and a view: class Task(models.Model): title = models.CharField(...) message = models.TextField(...) performer = models.ForeignKey(User, on_delete=models.CASCADE, ...) orgunit = models.ForeignKey(OrgUnit, on_delete=models.CASCADE ...) deviation = models.ForeignKey(Deviation, on_delete=models.CASCADE, related_name='tasks', ...) creator = models.ForeignKey(User, on_delete=models.SET_NULL, ...) for_control = models.ManyToManyField('self', ...) # другие поля class TasksViewSet(viewsets.ModelViewSet): serializer_class = TaskSerializer pagination_class = TasksPaginator filterset_class = TasksFilterSet def get_queryset(self): qs = Task.objects\ .select_related( 'performer__position__orgunit__conformation', 'deviation', 'creator__position__orgunit__conformation', 'orgunit__conformation', ).prefetch_related('for_control') return qs Fields in select_related and prefetch_related are for future serializing. As far as I know first joining happens and then filtering (where clause from TasksFilterSet) happens, right? If so obviously this can affect performance. So I thought would it be better first filter and then join? Of course some joins need to be done for filtering but this is not the case. I mean something like this: class TasksViewSet(viewsets.ModelViewSet): serializer_class = TaskSerializer pagination_class = TasksPaginator filterset_class = TasksFilterSet def get_queryset(self): return Task.objects.only('pk') def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: page = Task.objects.filter(pk__in=[task.pk for task in page]).select_related( 'performer__position__orgunit__conformation', 'deviation', 'creator__position__orgunit__conformation', 'orgunit__conformation', ) serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) What do you think about this? -
Django easypost buy returns malformed syntax when using test api key but insufficient funds with production
Using the easypost python library I call the buy function passing in the rate like the documentation says but it returns an error. Can you use your test api key with buy for easypost or not? I didn't see anything in the documentation with it. It might seem to work with production but I am not able to test that yet so I was wondering if I could test it with the test api key? The code is: import easypost def get_shipment(shipment_id): return easypost.Shipment.retrieve(shipment_id) ...... shipment = get_shipment(shipment_id) try: shipment.buy(rate=shipment.lowest_rate()) except Exception as e: raise ValidationError({'detail': e.message}) The error message I get with test key Traceback (most recent call last): File "/app/returns/serializers.py", line 237, in handle_shipment_purchase shipment.buy(rate=shipment.lowest_rate()) File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 725, in buy response, api_key = requestor.request('post', url, params) File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 260, in request response = self.interpret_response(http_body, http_status) File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 321, in interpret_response self.handle_api_error(http_status, http_body, response) File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 383, in handle_api_error raise Error(error.get('message', ''), http_status, http_body) easypost.Error: The request could not be understood by the server due to malformed syntax. -
Django Redirect does not work at all within view
I am trying to get my view to redirect to another page after clicking a button that triggers the POST request. I cannot seem to figure out why the redirect doesn't work or why it doesn't even seem to try to redirect. Here is my view: def cart1(request): if request.user.is_authenticated: #POST if request.method == "POST": #JSON Data data = request.body new_data = ast.literal_eval(data.decode('utf-8')) customer = request.user user_order = Order(user=customer) user_order.save() x = 0 while x < len(new_data.keys()): obj_title = new_data[x]["title"] obj_price = new_data[x]["price"] obj_quantity = new_data[x]["quantity"] obj_extra = new_data[x]["extra"] total = round(float(obj_price.replace("$", ""))) m = OrderItem(order=user_order, title=obj_title, price=total, quantity=obj_quantity, extra=obj_extra) m.save() x += 1 redirect('checkout-page') return render(request, 'cart.html') Any help would be appreciated, thank you -
Registration of application in Django
I need a custom section of application on admin site. It must not consider any model (proxy, unmanaged, etc), without template overriding, just a "phantom" application in programmatic way. I expect it looking like a bunch of URLs, registered in admin and located in separated section on index page. Hours of search and other answers without result. I tried this way in existing application, but links didn't appear. I did class MyModel(models.Model): class Meta: managed = False registered as ModelAdmin, and it's work, and for my luck URL fully matches with my view, so I don't need make real migrations, but I find this approach too rough. I really hope, there is more elegant way, but, perhaps, I must know Django deeply. -
img src returning 404 when path is correct
html template: {% load static %} <img src="{% static image_url %}"> <p>{{ quote }}</p> view: def makeImage(request): image = request.FILES['image'] quote = request.POST['quote'] fs = FileSystemStorage(location="static/") filename = fs.save(image.name, image) image_url = fs.url(filename) return render(request, 'app/makeImage.html', {'image_url': image_url, 'quote': quote}) error [05/May/2022 15:56:13] "POST /app/makeImage/ HTTP/1.1" 200 49 [05/May/2022 15:56:13] "GET /static/Space_Yzkaqwp.jpg HTTP/1.1" 404 1810 ........................................................................................................................................................................................................................................................................................................................... -
Django: how to filter posts based on view in django
i want to filter posts based on views e.g view>100 that is to filter course if only the view is greater is 100 views but it keeps showing this error SyntaxError: positional argument follows keyword argument. the way i am filtering the posts is the issue but i don't know the right way to do this. I have a field views = models.In... in my models.py, so that is why i am trying to filter course like course = Course.objects.filter(views>100) then it shows the error models.py class Course(models.Model): course_title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(unique=True) views = models.IntegerField(default=0) views.py def index(request): pop_courses = Course.objects.filter(course_publish_status="published", views>100).order_by('?') -
Django forms - Pandas displaying integer as columns names instead of actual names
I'm building a form to select columns from a CSV/XLSX file and then convert the selection to a dataframe. The parsing is working and I can get a dataframe. But in the dataframe, columns names are integers and not the actual names. I can't figure out why. My forms in forms.py which enables me to select columns: class CompareFormTransporteur(forms.ModelForm): file = forms.FileField(label="Fichier (CSV, XLSX, XML) ", required=True) header_row = forms.IntegerField(label="Header row", required=True) class Meta: model = CheckFile fields = ['file',] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request self.request.session['header_row'] = self['header_row'].value() super().__init__(*args, **kwargs) def clean(self): super().clean() extension = os.path.splitext(self.request.FILES['file'].name)[1] integer = self.request.session['header_row'] print(integer) if extension in ['.xlsx', '.xls']: uploaded = parse_excel(self.request.FILES['file'], rowheader=2) elif extension == ".csv": uploaded = parse_csv(self.request.FILES['file']) elif extension == ".xml": uploaded = parse_xml(self.request.FILES['file']) self.request.session['uploaded'] = uploaded self.request.session['profile'] = self.cleaned_data.get('profile') class CompareFormPartTwo(forms.Form): columns = forms.MultipleChoiceField(label="Colonnes", widget=forms.CheckboxSelectMultiple()) def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request self.uploaded = request.session['uploaded'] columns_choices = [] for key in enumerate(self.uploaded): columns_choices.append(key) self.fields['columns'].choices = columns_choices def clean_columns(self): """Valide les données sur les columns et transforme les choix en int.""" columns = self.cleaned_data['columns'] return [int(column) for column in columns] def clean(self): super().clean() self.request.session['selection'] = self.cleaned_data.get('columns') print(self.request.session['selection']) My code in views.py: class FormCompareTransporteur(RequestFormMixin, … -
How to add custom claim in django rest_framework_simple_jwt?
Their official doc only shows implementation for class based views. How to get this done for a function, ie. Refreshtoken.for_user()? from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } Snippet from here. This only shows how to create token manually. I know using pyjwt would make life simpler but there will be another workaround for blacklisting. -
I can not render a new user registration form from a model ViewSet in Django Rest frame work
class RegisterViewSet(viewsets.ModelViewSet): http_method_names = ["post"] permission_classes = (AllowAny,) serializer_class = RegisterSerializer renderer_classes = [TemplateHTMLRenderer] template_name = "api/authentication/template/authentication/register.html" def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response( { "success": True, "userID": user.id, "msg": "The new user is successfully registered", "serializer":serializer, "form": UserRegisterForm }, status=status.HTTP_201_CREATED, ) i just want to render a form to display to HTML . basically , how to render form from a model viewset from django rest framewor k. -
Django dumpdata serializing an int as string
I've been trying to make a custom class/type, defined in a separate db.py file, to be properly serialized as an int when doing a manage.py dumpdata command, but this BitFlagField always ends up exported as a string, the value accompanied by double quotes, while other integer fields are properly exported without the quotes in the JSON file. The person that made it left the place almost a year ago, so I can't get any help from him. This is the class' code - note that I've fixed the __str__ function and also changed the __repr__ to return repr(self.value) This is how it looks after the dumpdata: (...), "blocked": "8"}} ; For comparison, two other integer fields don't come with the value enclosed by quotes: "pk": 1, "bit":8,. Because of this, manage.py loaddata fails: django.core.serializers.base.DeserializationError: Problem installing fixture '/home/abcd/djangoapp/data.json': '>=' not supported between instances of 'str' and 'int': (core.userextra:pk=1) field_value was '8' If I manually remove the quotes from the "blocked" field's value, the loaddata command works. If I delete both __str__ and __repr__ functions, the object type is what ends up as the data: (...), "blocked": "<core.db.BitFlag object at 0x7f9f2eb0bf40>"}}. If I make either of them return self.value, it complains … -
I am trying to pop up error message in Django using messages, but it's not working
I am trying to pop up error message but it's not working. Do you see any problem in this coding? Thank you. -
Using double underscore to directly update foreign key's field in Django?
I am using double underscore to filter a model or get values from it in Django like this: # filtering model furthers = myModel.objects.filter(foreignKeyField__furtherField=value) # getting values furtherField = myModel.objects.get(id=10).values("foreignKeyField__furtherField") But when I try to use update() method with double underscore like this: myModel.objects.filter(id=10).update("foreignKeyField__furtherField") I get an error: django.core.exceptions.FieldDoesNotExist: myModel has no field named 'foreignKeyField__furtherField' I looked up documentations about this but there is neither usage example of double underscore for update() method nor a word I cant use it like this way. So could we say update() method cannot be used like this? -
what should i write in the settings.py to import my Template
I have deployed my project on pythonanywhere and there i am getting an error that template does not exist It's working properly on local host File directory settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Can someone tell what should i add my template DIRS -
Forbidden (403) CSRF verification failed. Request aborted. django error
I want to post a form with HTML <form method="POST" enctype="multipart/form-data"> {% csrf_token %} // some inputs </form> My middlewares are these MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] When I try to post a form, it is showing the following error Forbidden (403) CSRF verification failed. Request aborted. -
Installation of Spatialite with Django on windows 10
I am struggling to find out how to install spatialite for geodjango on windows but I don't know what I am doing wrong. I follow the instructions as per the django page https://docs.djangoproject.com/en/4.0/ref/contrib/gis/install/spatialite/ but the tutorial doesn't say what to do after getting the binarys of spatialite I have tried to put them everywhere but every time I get the same error: Exception Value: Unable to load the SpatiaLite library extension as specified in your SPATIALITE_LIBRARY_PATH setting I tried to put the mod_spatialite.dll file everywhere and try to set to SPATIALITE_LIBRARY_PATH but it seems I can't get the solution Any suggestions would be appriciated Thanks -
Django multiple upload drag and drop not working
I want to do an update on a current web app I developed with Django. The current version has multiple uploading fields: And I changed it to this: Now I don't know how to update the code to do exactly the same thing, I made some changes, but I can't seem to get the files from the dropzone using request.FILES.getlist('files') Here is my old code: HTML: <h5>Documents de base</h5> {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} View: ................... if request.method == "POST": dossierForm = DossierForm(request.POST) formset = DocumentFormSet( request.POST, request.FILES, queryset=DocumentdeBase.objects.none() ) formset2 = PhotoAvantFormSet( request.POST, request.FILES, queryset=PhotoAvant.objects.none() ) if dossierForm.is_valid() and formset.is_valid() and formset2.is_valid(): ................... for form in formset.cleaned_data: # this helps to not crash if the user # do not upload all the photos if form: image = form["documentdebase_image"] photo = DocumentdeBase( dossier=dossier_form, documentdebase_image=image ) photo.save() for form2 in formset2.cleaned_data: # this helps to not crash if the user # do not upload all the photos if form2: image2 = form2["photoavant_image"] photo2 = PhotoAvant(dossier=dossier_form, photoavant_image=image2) photo2.save() .................... else: dossierForm = DossierForm() formset = DocumentFormSet(queryset=DocumentdeBase.objects.none()) formset2 = PhotoAvantFormSet(queryset=PhotoAvant.objects.none()) Form: class DocumentdebaseForm(forms.ModelForm): documentdebase_image = forms.ImageField(label="") class Meta: model = DocumentdeBase fields = … -
Django Admin disable a html field by a another field value
I have a django model and I want to disable the other field according to the selection of one field in my admin panel. Look at the picture if the "User Auth Filter" field is "Only Unauthenticated Users", I want the "Linkedin Filter" field to be disabled from html. like this: How can I do the "disabled html" operation before saving from the admin panel. -
Django & React integration without using an API
Is there anyway to use django and react while keeping the business logic, routing, etc on the django side ? I want to use react for the ui features and the state management but on the other hand i don't like to do the business logic on the front end and just use drf as an api for the data. The way i would imagine it is to render mini react apps instead of django templates but i have no clear way to implement this and i don't even know if it's technically possible. I would like to get some guidance from more experienced developers. Thanks -
Django throws "connection to database already close" error on Scrapy + Celery task
Context I have a Django application running inside a Docker container. This application uses Celery and Celery-beat for async and scheduled tasks. One of those tasks scrapes texts from different webs using Scrapy. This task runs every minute looking for new texts on the pages. If there is new information, it creates a new object in MyModel. This logic (querying the database to check if data exists, and create the object or update the info) is performed by a custom Scrapy item pipeline. Issue When using Development environment (using locally Docker Compose to turn on one container for the app, one container for PostgreSQL plus other services containers) everything runs smoothly. However, when using Stage environment (one Docker container for the app on a DigitalOcean droplet and a PostgreSQL self-managed cluster) the tasks throws this error: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 236, in create_cursor cursor = self.connection.cursor() psycopg2.InterfaceError: connection already closed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/twisted/internet/defer.py", line 857, in _runCallbacks current.result = callback( # type: ignore[misc] File … -
Django: Create a superuser in a data migration
Goal: automatically creating a superuser I'm trying to create a default user, specifically a superuser, in an early data migration, so whenever my Django application is run in my Docker container, it already has a superuser with which I can access the admin site. I had already tried different options for creating said superuser, and although I have some functioning ones (based on the command parameter of my docker-compose file), I've seen when adding initial data to a Django project, the best practice is to do it through a Data Migration. My custom user In my Django project I've extended the AbstactBaseUser so I can change the default username field requirement for the email field. My User is as such: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): # Implementation... def create_superuser(self, email, password, **extra_fields): # Implementation... class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name="email address", max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email Failed attempts By following the Django documentation here I tried making my superuser in a data migration with the following code, located in a file called 0002_data_superuser in the migrations folder of my app: … -
Deploying FrontEnd and BackEnd as two separate applications with Google Cloud App Engine
I have two application that I want to deploy with Google Cloud App Engine. One of them is react front end, and I want to serve this through www.videoo.io Second one is back-end, which will be served via api.videoo.io Frontend yaml file react.yaml : runtime: nodejs16 env: standard handlers: - url: /static static_dir: static secure: always - url: www.videoo.io/* service: frontend script: auto secure: always% API yaml file, api.yaml : runtime: python37 entrypoint: gunicorn -b :$PORT videoo.wsgi service: "videoo-api" env: standard handlers: - url: api.videoo.io/* service: backend script: auto secure: always% Is this the correct way to achieve this ? What is the best strategy to serve these two separate applications that will interactively communicate (Frontend will make calls to API to get object information that is stored Django app) ? Here is also my domain name information in Google App Engine settings : -
Django kwargs doesn't retrieve value after page reload
I got this code in my view. @login_required(login_url='login_user') def user_profile(request, **kwargs): user = request.user post_form = PostForm(instance=user) post_func = post(request) user_n = kwargs.get('username') READ THIS PLEASE! user_n it returns the username of the current user, but for some reason, after I create posts with the post function it doesn't get the username, but it gets str:username instead when I print it to console. Does anyone know why and how I can fix this? print("This is the user logged in: ", user.username, user_n) EXAMPLE for the print above("This is the user logged in: ", user.username = current username, user_n = str:username (this is happening only when I use the post function to post some content. Any other time user_n = current username)) user_data = {} try: current_user_username = NewUser.objects.get(username=user_n) current_user_profile = Profile.objects.get(relation_id=current_user_username.id) except: return redirect("profiles") is_self = True if current_user_username: current_profile_posts = Posts.objects.filter(post_relation_id=current_user_username.id) user_data['current_profile_id'] = current_user_username.id user_data['current_profile_username'] = current_user_username.username user_data['current_profile_email'] = current_user_username.email user_data['current_profile_title'] = current_user_profile.title user_data['current_profile_avatar'] = current_user_profile.avatar user_data['is_self'] = is_self else: pass if post_func is not None: print("If post_func is not none: ", post_func) return post_func elif post_func is None: print("If post_func is none: ", post_func) pass else: print("This state of post_func should never activate: ", post_func) return http.HttpResponseRedirect('/UserProfile/<str:username>/') context …