Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Using month from datetime in model filter
I have a model called Watch with a datefield called date and I want to only show the objects from that model that have the same month as the current month. I tried: Watch.objects.filter(date.month=now.month).order_by('-day') But this appeared not to be possible. How can I achieve this? -
Model infos not showing up on HTML page Django
I am trying to create an educational website using Django, so when I am trying to render {{ profile.institution }} or {{ profile.grade }} or {{ profile.user.username }} they are not being rendered.I don't know why they aren't. Can anyone help me solve this? My models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.CharField(max_length = 100) grade = models.CharField(max_length=100, choices= YEAR_IN_SCHOOL_CHOICES) bio = models.TextField(max_length=300) def __str__(self): return f'{self.user.username} Profile' My views.py: class User_Profile(LoginRequiredMixin, ListView): model = Profile template_name = 'class/profile.html' context_object_name = 'profile' def get_queryset(self): return Profile.objects.filter(user=self.request.user) My html: {% extends "class/base.html" %} {% load crispy_forms_tags %} {% block content %} <br> <div class="row d-flex justify-content-center"> <h1 style="color: #f5a425">Hello {{ user.username }}</h1> </div> <div class="container mt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-7"> <div class="card p-3 py-4"> <div class="text-center"> <i class='fas fa-user-alt' style='font-size:36px'></i> <!-- <img src="" width="100" class="rounded-circle"> --> </div> <div class="text-center mt-3"> <span class="bg-secondary p-1 px-4 rounded text-white">Pro</span> <h5 class="mt-2 mb-0">{{ profile.user.username }}</h5> <span>{{ profile.institution }}</span> <span>{{ profile.grade }} Grade</span> <div class="px-4 mt-1"> <p class="fonts">{{ profile.bio }}</p> </div> <div class="buttons"> <button class="btn btn-outline-primary px-4">Message</button> <button class="btn btn-primary px-4 ms-3">Contact</button> </div> </div> </div> </div> </div> </div> {% endblock content %} -
Как добавить элементы по кнопке вместо прокрутки?
у меня есть такой код для бесконечной прокрутки masonry с фото и пагинация на django. Я хочу чтобы по нажатии на кнопку добавлялись элементы в masonry вместо прокрутки до конца блока. В основном я находил вариант загружать все элементы masonry, а потом по кнопке делать их видимыми, но мне такой способ не нравится, ведь фото может быть бесконечно много. translation via google translator. I have this code for infinite scrolling masonry with photos and pagination on django. I want the button to add elements to masonry instead of scrolling to the end of the block. Basically, I found an option to load all the masonry elements, and then click on the button to make them visible, but I don't like this method, because there can be infinitely many photos. jQuery(window).on('load', function(){ var container = $('#gallery'); container.imagesLoaded(function () { container.masonry({ itemSelector: '.item-masonry', percentPosition: true, transitionDuration: '0', }); var infinity = new Waypoint.Infinite({ element: $('.infinite-container')[0], container: 'auto', items: '.infinite-item', more: '.infinite-more-link', offset: 'bottom-in-view', loadingClass: 'infinite-loading', onBeforePageLoad: function() { }, onAfterPageLoad: function() { container.masonry('reloadItems'); // $(container).masonry('layout') container.imagesLoaded().progress( function() { container.masonry('layout'); }); } }); }); }); class IndexImg(ListView): model = ImageFile template_name = 'images.html' context_object_name = 'images' paginate_by = 15 -
Django POST request is empty
Running Django 4.1.1. Having this code below in template. By clicking a button it sends a data to delete apropriate marker. <form method="POST"> {% csrf_token %} <ol> {% for marker in markers %} <li> {{ marker }} - <button class="button btn-primary" id="delete" value="{{ marker.pk }}" type="submit">Delete</button> </li> {% endfor %} </ol> </form> In views.py def user_markers(request): markers = Marker.objects.filter(owner_id=request.user.id).select_related() if request.method == "POST": print(request.POST.get("delete")) # gives me None marker = Marker.objects.get(pk=request.POST.get("delete")) marker.delete() context = { "markers": markers, } return render(request, "hub/markers.html", context) The problem is that request.POST.get("delete") is empty. POST data has only 'csrfmiddlewaretoken' Do I miss something? -
How to execute multiple sql queries in django.db with execute - SET PREPARE EXECUTE
How can I execute this statement in django.db SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when field_key = ''', field_key, ''' then field_value end) ', field_key ) ) INTO @sql FROM Meeting; SET @sql = CONCAT('SELECT Meeting_id, ', @sql, ' FROM Meeting GROUP BY Meeting_id'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; with connection.cursor() as cursor: cursor.execute(query) rows = cursor.fetchall() I try to execute the sql as a string but it returns no results, apparently django's .execute() can only execute one configuration at a time. -
Djoser logout from Vue Frontend
Currently using Vue as my frontend and Django as backend API. Trying to have user logged out when clicking on logout button. Not sure what is all needed in order to log user out. When I click on the logout button, nothing is happening and just pushing to /logout route where I have the router linked to the file. When I click the logout button, user is still logged in. Not worried about the routing, but more concerned about actually being able to log out. Login export default { name: 'Login', data () { return { username: '', password: '', errors: [] } }, methods: { submitForm(e) { axios.defaults.headers.common["Authorization"] = "" localStorage.removeItem("token") const formData = { username: this.username, password: this.password } axios .post("/api/v1/token/login/", formData) .then(response => { const token = response.data.auth_token this.$store.commit('setToken', token) axios.defaults.headers.common["Authorization"] = "Token " + token localStorage.setItem("token", token) this.$router.push('/project-dashboard') }) .catch(error => { if (error.response) { for (const property in error.response.data) { this.errors.push(`${property}: ${error.response.data[property]}`) } console.log(JSON.stringify(error.response.data)) } else if (error.message) { console.log(JSON.stringify(error.message)) } else { console.log(JSON.stringify(error)) } }) } } } Logout export default { name: 'Logout', data () { return { username: '', password: '', errors: [] } }, methods: { onclick(e) { axios.defaults.headers.common["Authorization"] = "" … -
Failed to load resource: the server responded with a status of 500 (Internal Server Error) server cannot be a server error
When I run it in visual, it works, but when I deploy it to the server, the part with the url is https://domain/finance/ error $.ajax({ url: 'http://127.0.0.1:8000/finance/', beforeSend : function(jqXHR, settings) { jqXHR.setRequestHeader("x-csrftoken", '{{ csrf_token }}'); }, data: data, processData: false, method: 'POST', contentType: false, enctype: 'multipart/form-data', success: function ( qayidanData ) { if( qayidanData == "True"){ $('.requiredS2, .requiredS1').each(function () { $(this).val(''); }); $('#step2').hide(); $('#step1').show(); Swal.fire('You have successfully registered'); } } }); jquery-3.6.0.min.js:2 XHR failed loading: POST "https://turbohub.ca/finance/". send @ jquery-3.6.0.min.js:2 ajax @ jquery-3.6.0.min.js:2 (anonymous) @ (index):433 dispatch @ jquery-3.6.0.min.js:2 v.handle @ jquery-3.6.0.min.js: -
Import "django.core.management" could not be resolved from source
Import "django.core.management" could not be resolved from source I am getting this error not able to clear it enter image description here -
How to search text inside a database in Django
I have to search using a collection of words in a database. The sequence of the words doesn't matter. For example: `"How to build a computer" is a string in the database. I should be able to get this result by just putting in the string "build computer". Currently, I am using a sqlite3 database with Django. I tried solving the problem by splitting the words in the query and then looping through the database to check if the word was in the records of the database. The more words of the query are in the record, the higher the ranking of that particular record in the database. But my approach involves splitting each record in the database, and then search all of the records using every word in my search query. Is there any way to optimise my algorithm? -
Django annotate with other model attributes based on a common field
I have a User model, class User(AbstractBaseUser): id = models.IntegerField(primary_key=True) email = models.EmailField(unique=True) I have another model named Company. The Company model has a reference to User model via an Integer field. class Company(models.Model): user_id = models.IntegerField(db_index=True) name = models.CharField(max_length=100) size = models.IntegerField(default=1) I wanted to extract the company information along with user information. basically I want a user object dictionary like this {'id':1, 'email':'abc@gmail.com','name':'foobar.co','size':400} I want to annotate the user objects with name and size. As of now, I tried in the serializer's to_representation method. However, for millions of users this is super slow. class UserSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) email = serializers.EmailField(read_only=True) def to_representation(self, instance): response = super(UserSerializer, self).to_representation(instance) company = Company.objects.filter(user_id=instance.id) if company.exists(): company = company.first() response['name'] = company.name response['size'] = company.size return response How can I achieve this annotation in the query itself. -
Consuming External API Using Django Generic CBVs
If I want to consume an external API within a generic class based view in Django, can I add a method to the generic view including a get request? I need to pass parameters from the data model in the request payload in order to illicit a response, and I fundamentally do not understand how to do this. I was hoping someone could point me in the direction of a tutorial or something to help me out, as I have done hours of searching and I cannot find anything that is within an existing CBV. Thanks! -
Django static files troubleshooting for production
BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') INSTALLED_APPS has 'django.contrib.staticfiles' This is how they're called in HTML <img src="{% static 'capabilities-2.jpg' %}" class="img-fluid"> Displayed in my console: [10/Sep/2022 17:39:50] "GET /css/index_styles.css HTTP/1.1" 404 179 [10/Sep/2022 17:39:50] "GET /js/scripts.js HTTP/1.1" 404 179 [10/Sep/2022 17:39:51] "GET /static/index/images/capabilities-2.jpg HTTP/1.1" 404 179 [10/Sep/2022 17:39:51] "GET /assets/favicon.ico HTTP/1.1" 404 179 Trying to transition from Dev to Production. I had the images working in development. If I inspect the images (or lack of images) within a browser, the path is as follows: Should be noted that I can't even see them when inspecting the source. I tried adjusting the paths /static/capabilities-2.jpg to /static/index/images/capabilities-2.jpg as it is in my project but that still didn't work. I'm running on Linode, Ubuntu 22.04. I like a lot about Django, but static files are being a huge PIMA. -
How do I make a user balance in django?
I want to make a user balance. And I want to make sure that the user, before buying something, first replenishes this balance through the payment system and only then makes purchases. And also, so that when making a purchase, part of the funds went to the seller, and part went to the service. How can this be implemented since I'm new to django? -
When trying to pass in a post it is not working
<html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> </body> </html> class Post(CreateView): fields = ("title","about","itempicture") template_name = "post.html" model = models.Listing I can't seem to figure out why is is not working my html and views connect perfectly put when try to send in a post request it does not work I would happy if someone could help me out -
What is the best way to search in multiple fields in django?
I have the following model in my models.py, and I want to search based on its three fields. class Profile(models.Model): username = models.CharField(max_length=128, null=False, blank=False, unique=True) password = models.CharField(max_length=128, null=False, blank=False) name = models.CharField(max_length=50, null=True, blank=True) lastname = models.CharField(max_length=50, null=True, blank=True) parent = models.ForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE) There are also three separate inputs for entering the text, one for name, one for last name, and one for username. The user should at least fill in one input, or if the input string was a part of main string, the main string should be returned. This is my API, but it does not return anything, and the result list is always empty. def search_users(request): if request.method == 'GET': try: to_be_searched_username = request.GET.get("username", None) to_be_searched_name = request.GET.get("name", None) to_be_searched_lastname = request.GET.get("lastname", None) supervisor_username = request.headers['Authorization'] supervisor = Profile.objects.get(username=supervisor_username) if not((to_be_searched_name or to_be_searched_lastname) or to_be_searched_username): return Response({"message": "Enter a search term"}, status=status.HTTP_204_NO_CONTENT) else: results = supervisor.children.filter( username__icontains=to_be_searched_username and to_be_searched_username is not None ).filter( name__icontains=to_be_searched_name and to_be_searched_name is not None ).filter( lastname__icontains=to_be_searched_lastname and to_be_searched_lastname is not None ) return Response({'results': results}, status=status.HTTP_200_OK) except: return Response({"message": "خطا در دریافت اطلاعات"}, status=status.HTTP_400_BAD_REQUEST) I will be grateful for any help or advice. -
what is a function inside a function in django/python
I wanna know, what is main idea function inside a function in djanggo?, something like this example. def partition_by_mod(base): def func(n): return n % base return staticmethod(func) when I call this function like this test = partition_by_mod(8), so I'm wondering where the "n" comes from. thank you ~ -
Is there a way of passing a model into a template without a class based view
My question is can I use a function view to pass in a model inside my template to be iterated through. This is how my model looks like class Listing(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE) itempicture = models.ImageField(upload_to="images",blank=False) title = models.CharField(max_length=50) about = models.CharField(max_length=500) published_date = models.DateTimeField(blank=True, null=True) how can I write a function based view to pass in my database just like a class based (list view) -
Bypassing DRF throttling
I have a Django application running on an Nginx + Gunicorn server where I use DRF throttling. Whenever I make API requests to my server and change the X-Forwarded-For header value in the client I'm then able to bypass the throttling for unauthenticated users and thereby have unlimited access to the API. This is of course not desired. I think a way to deal with this is to have Nginx append the real IP to the end of the X-Forwarded-For request header before it reaches the server by using proxy params. It just doesn't seem to change the header when I inspect Postman / RapidApi client. I assume that's what causes the error but ultimately I don't know. Nginx conf: location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } The proxy_params file from Nginx includes setting the X-Forwarded-For request header like so: proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; Can somebody tell me what I'm doing wrong and how to fix it so you can't make unlimited API requests? If you need more information or clarification please let me know. -
formset won't validate django admin custom actions interim form page
I don't know how to get the updated fields, from the forms in the formset, into individual messages, because the formset is never valid. in the admin action interim page the user has to be able to see and edit the forms intial values and when they submit the messages should be sent with the form updated or not values to the correct mail. But the formset is never valid. Is it because of how the admin actions functions or what is going on? ¨ forms.py class ReviewRequestTemplate(forms.Form): emailtemplate = forms.CharField(widget=forms.Textarea) employers_email = forms.EmailField() review_link = forms.CharField() subject = forms.CharField() admin.py class EmployerAdmin(TranslationAdmin): list_display = ('name', 'website', 'review_request_sent',) actions = ['request_review',] def request_review(self, request, queryset): RequestTemplateFormset = formset_factory(ReviewRequestTemplate, extra=0) formset = RequestTemplateFormset(initial=[{'emailtemplate': f"Hello {employer.name} Review our servie right NOW! Here is your link:",'employers_email':employer.email, 'review_link':get_current_site(request).domain +reverse('review', kwargs={'uidb64': urlsafe_base64_encode(force_bytes(employer.pk)), 'token':account_activation_token.make_token(employer)}), 'subject':'Please let us better our services'} for employer in queryset]) if request.POST.get('post'): formset = RequestTemplateFormset(request.POST) if formset.is_valid(): print('valid') message = f"email:{form.get('employers_email')}, subject:{form.get('subject')}, message: {form.get('emailtemplate') + form.get('review_link')}" queryset.update(review_request_sent=True) else: print('not valid') all_sent = request.POST.items() return HttpResponse(all_sent) else: context = { 'title': "Are you sure?", 'queryset': queryset, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME, 'formset': formset } return TemplateResponse(request, 'admin/requestreview.html', #TemplateResponse context) request_review.short_description = "Send review requests" html {% … -
Not able to run the command: python manage.py runserver, in pycharm
I have tried running the python manage.py runserver in pycharm terminal, earlier it was working fine but now it is not working as expected and gives the following error: Program 'python.exe' failed to run: The file cannot be accessed by the systemAt line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~. At line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed -
How to split API to paid and unpaid users?
I have database full of useful information, which I want to develop an API for using Django rest framework. This API will be used by mobile app so user and user authentication. I want the users of this App to pay a subscription fee for the services. What is the best way to go about this using django?? I just need a direction, I thought about dividing user to groups paid and unpaid Paid group have access to all, unpaid only have a portion of every service, using django permissions group. I do have a strong feeling that this not secure or the way to do it. I also thought about Token Authorisation, meaning people who have the token have access others have limited access. Is this good strategy? Please any help is immensely appreciated 🙏. -
I want to perform a search using these two fields by django-watson framework , Please help...thank you
I want to perform a search using these two fields by django-watson framework The first field searches by restaurant name and the second field searches by restaurant locations and the two fields in the same form -
Django request.POST does not contain the name of the button that submitted the form despite having name and value
I have Django form that have 2 different submit button, i need to know which button is clicked. But the button did not include in request.POST This is my form: <form hx-post="{% url 'recomposition:akb-edit' %}" hx-target="#target-{{this_month}}-{{data.pk}}" hx-swap="outerHTML" enctype="multipart/form-data"> ... <div class="form-group modal-footer p-0"> <div class="btn-group d-flex w-100" role="group" aria-label="..."> {% if this_month != 0 %} <button type="submit" value="delete" name="delete" class="btn btn-danger w-100" {%if not is_month %}disabled{% endif %}>Delete changes</button> {% endif %} <button type="button" class="btn btn-secondary w-100" onclick="closeModal()">Close</button> <button type="submit" value="save" name="save" class="btn btn-primary w-100" >Save changes</button> </div> </div> </form> I didnt know whats wrong the last time I encounter this if i forgot to included the name but now i have the name and value but id didnt show up in request.POST -
How to use patterns in the definition of a variable in Django
I am working in Django and I have the following class class Usuario(AbstractBaseUser): username =models.CharField(verbose_name='Nombre de usuario', max_length=45, unique=True) date_join =models.DateTimeField(verbose_name='Fecha de alta', auto_now_add=True) last_login =models.DateTimeField(verbose_name='Última conexión', auto_now=True) es_docente =models.BooleanField(default=False) es_estudiante =models.BooleanField(default=False) es_directivo =models.BooleanField(default=False) es_preceptor =models.BooleanField(default=False) es_tutor =models.BooleanField(default=False) es_superuser =models.BooleanField(default=False) estado =models.BooleanField(default=True) now, I would like to add a function to change the boolean states, if it is possible, by using some kind of pattern. I know that the following code is wrong but I didn't find the correct syntax: def changer(self,var): es_(%var) = not Usuario.es_(%var) where I am marking with %var some kind of usage of the input of the function. For example, I would like to input changer(preceptor) and receive as output that the changing of the boolean field es_preceptor. Thanks in advance! -
I'm making a django webapp and I keep getting pk errors
I keep getting this error even after migrating, making migrations, importing get_object functions, Page not found (404) No storage found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/change-info/1 Raised by: base.views.UpdateInfo Using the URLconf defined in mywallet.urls, Django tried these URL patterns, in this order: admin/ [name='list'] descript/<int:pk>/ [name='descript'] create-bank/ [name='create-bank'] change-info/<int:pk> [name='change-info'] The current path, change-info/1, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my views.py code from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView from django.urls import reverse_lazy from .models import Storage # Create your views here. class Listings(ListView): model = Storage context_object_name = 'banks' class Information(DetailView): model = Storage template_name = 'base/storage_detail.html' class NewBank(CreateView): model = Storage fields = '__all__' success_url = reverse_lazy('list') class UpdateInfo(UpdateView): model = Storage fields = '__all__' reverse_lazy('list') my urls.py from django.urls import path from .views import Listings, Information, NewBank, UpdateInfo urlpatterns = [ path('', Listings.as_view(), name= 'list'), path('descript/<int:pk>/', Information.as_view(), name='descript'), path('create-bank/', NewBank.as_view(), name='create-bank'), path('change-info/<int:pk>', UpdateInfo.as_view(), name='change-info') ] my models.py from django.db import models …