Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Custom Join in Django
I am struggling to create the correct prefetch behavior in Django. Here is the outline of the problem: Each Account has DailyQuotes, updated daily at different times (think snapshot) Need to query all of those DailyQuotes, and only get the most recent quotes for each account Here are the models: class Account(models.Model): name = models.TextField(default="") ... class DailyQuotes(models.Model): account = models.ForeignKey(Account, related_name="quote", on_delete=models.CASCADE) date = models.DateField(default=None) ... Currently the query inside of my view for this looks like: acc_ids = [1,2,3] max_date = DailyQuotes.objects.aggregate(Max("date"))["date__max"] accounts = ( Account.objects.filter(id__in=acc_ids) .prefetch_related( Prefetch( "quote", queryset=DailyQuotes.objects.filter(date=date), ), ) ) # Feed into serializer, etc This works and generates 3 queries: 1 for the max date, 1 for accounts, and 1 for the quotes. The problem with this solution is that if one account has more up to date DailyQuotes, then the other accounts will return no quotes. So I need to get the latest DailyQuotes for each account based on the max date for that account, not all accounts. I have generated the SQL query that does what I want, but turning it into Django code has been giving me issues. I could execute the raw SQL but I would like to keep it … -
How to change HTMX behavior to replace the full web page if form is invalid
If this form submits as invalid, I want to override the htmx and do a HttpRedirectResponse that refreshes the full page instead of just changing the div, #superdiv, contents. <form id="create_form" action="." method="post" hx-post="." hx-target="#superdiv" hx swap="outerHTML"> {{ form }} <button id="button" type="submit">Create</button> </form> I have been attempting to do this in the def post of my views. if form.is_valid(): return self.form_valid(form) else: return HttpResponseRedirect(reverse_lazy("logs:manager_form")) Would this be achieved better using JavaScript? I am trying my best to sticking to learning only vanilla JavaScript for now. Thanks for any help. -
query database to search post in django application
I'm trying to add search bar in my application but I don't know how to query a database to gives the things that user's search for. I want when user search for a user in a post or category in a post of model to shows the result that user search for, like YouTube search and facebook search, How can i do this in django to give me what i want ? this is my model: class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=30,null=True, blank=False) image = CloudinaryField(blank=False, null=False) description = models.TextField(null=True) date_added = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=12, null=False, blank=False) price = models.CharField(max_length=30,blank=False) location = models.CharField(max_length=20, blank=False) def __str__(self): return str(self.category) my dashboard: <div class="container"> <div class="row justify-content-center"> <form action="{% url 'search' %}" method="get"> <input class="form-control me-2" type="search" placeholder="Search" aria- label="Search"> <br> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> <div class="container"> <div class="row justify-content-center"> {% for photo in photos reversed %} <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbail" src="{{photo.image.url}}" alt="Card image cap"> <div class="card-body"> <h2 style="color: yellowgreen; font-family: Arial, Helvetica, sans-serif;"> {{photo.user.username.upper}} </h2> <br> <h3>{{photo.category}}</h3> <h4>{{photo.price}}</h4> </div> <a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn-sm m-1">Buy Now</a> </div> </div> {% empty %} <h3>No Files...</h3> {% endfor %} </div> … -
Design question: Is there a Django specific way to select users to receive notifications when a form is submitted?
I have a Django app, and need to send email notifications to certain users at certain points in my processes without adding any external libraries. For example, if any user submits a particular form, I need to send a notification to a specific set of users. I'm thinking to use custom model permissions for each model that relates to a particular form. Then hypothetically add users to unique Authentication Groups that have those particular permissions. Then I would create a Notifier class with a notify_users_by_email method that could accept an authorization group and a reason type. Have each reason type be 1-to-1 with the permissions defined at the model level. Then we can just filter the group to the users in the group and send the email. I would also add a Notifications model, which could be used to record who sent the notifications, who was the intended recipient, send time and the notification reason (again related to permission). In general, is that an appropriate way of going about this, or is there a cleaner way to do this in Django? class Notifier: @classmethod def notify_group_by_email(cls, group_id: int, reason: str): users_in_group = Group.objects.get(id=group_id).user_set.all() for user in users_in_group: cls.notify_user_by_email(user_id=user.id, reason=reason) user … -
Django (Wagtail) template not recognizing page type for if condition
On my wagtail blog, I have a simple model that will be the index page listing different articles, defined in my models.py as: class ArticleIndex(Page): description = models.CharField(max_length=255, blank=True,) content_panels = Page.content_panels + [FieldPanel("description", classname="full")] I have some template tags setup to show categories and tags in the sidebar, which should only activate on the index page, not actual article pages. I have this setup thusly: {% if article_index %} {% categories_list %} {% tags_list %} {% endif %} If I remove the if condition, everything displays as I want, so I know it is not an issue with the template tags. I don't understand why {% if article_index %} is failing, as that's what the page type is. How can I print out what the actual page type is to see where the discrepancy is, or to see why the if condition is failing? -
Django download links only working in new tab
This is driving me crazy, I'm developing a django app and need to provide a download link to a file located in the media folder. If I type the url in a blank tab it works fine, the file is downloaded, but if I click on the link from the website nothing happens. I realize this might be because the url to the file doesn't have the same origin that the website and from what I understood the browser won't allow the download, is this correct? Is there any way around? url of the website (in development): http://localhost:8000/django_app/view_name url of the file: http://localhost:8000/django_app/media/file.ext I've tried the following html href: href="../media/file.ext" download target="_blank" And the following view: def download_file(request): fl_path = settings.MEDIA_ROOT + "\\filename.ext" filename = "file_name" mime_type, _ = mimetypes.guess_type(fl_path) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response Nothing happens when I click on the link, no error generated. If I open the link in a new tab it downloads the file normally... Note that I need to be able to change the href link dynamically. Thanks! -
How to restrict access to a template to users based on their department_name
I have below model. Departments, users.. Users are assigned in a department. How can i restrict the access of template based on department_name of a user? For eg : User can view Application Template_1 if department_name == "Computer_Department". Here user belong to "computer" department. User can view Application Template_2 if department_name == "Electrical_Department". Here user belong to "electrical". ******My code are as below models.py class Departments(models.Model): id = models.AutoField(primary_key=True) department_name = models.CharField(max_length=255) # here department name can be computer, electrical etc created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Departments(models.Model): id = models.AutoField(primary_key=True) department_name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() UserViews.py def bi_powise(request): return render ( request, 'user_template/application_template/bi_powise.html', {}) urls.py path ( 'bi_powise_user', UserViews.bi_powise, name = 'bi_powise_user' ) sidebar_template.html {% url 'bi_powise_user' as bi_powise_user %} <a href="{{ bi_powise_user }}" class="nav-link {% if request.path == bi_powise_user %} active {% endif %}"> <i class="nav-icon fas fa-chalkboard"></i> <p> BI PO-Wise </p> </a> </li> -
Django: Horizontal scaling with a single database
I have a single django instance about to hit its limits in terms of throughput. Id like to make a second instance and start scaling horizontally. I understand when dealing with database read replicas there is some minimal django configuration necessary, but in the instance of only using a single database: is there anything I need to do, or anything I should be careful of when adding a second instance? For the record, I use render.com (it’s similar to heroku) and their scaling solution just gives us a slider and will automatically move an instance up or down. Is there any sort of configuration I need to do with django + gunicorn + uvicorn? It will automatically sit behind their load balancer as well. For reference my stack is: Django + DRF Postgres Redis for cache and broker Django-q for async Cloudflare -
Need to have the correct url path in Django
I am trying to get my django app to point to the correct url in my chatserver/urls.py file. I am getting this error when I start my django app: Using the URLconf defined in chatserver.urls, Django tried these URL patterns, in this order: admin/ join [name='join'] The empty path didn’t match any of these. This is my chatserver/urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('chat.urls')), path('admin/', admin.site.urls), ] And this is my chat/urls.py file: from django.urls import path from . import views urlpatterns = [ path('join', views.init, name='join'), ] And here is my app project directory: [1] Can someone help me correct my error? -
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