Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the difference between cached_property in Django vs. Python's built-in?
Django has a decorator called cached_property which can be imported from django.utils.functional. On the other hand, Python 3.8 added cached_property to the standard library which can be imported from functools. Are both equivalent, i.e., are they interchangeable? or what is the difference between both? Are there any best practices when to use one or the other? -
How to recommend items in Django?
I want to track the user and which categories of blogs he/she is searching/reading then utilise this data to recommend blogs in a recommended blogs section in the home page. I have been researching for several days and found Django-recommends but the documentation is very unclear.Thanks in Advance... -
How can I use the information of a field from one model to calculate another field in other model?
Im creating a restaurant software with python and Django. I have an Ingredient model that has cost and quantity fields. I use them to return the cost_per_unit calculated field (cost / quantity). Then, I created a recipe model, with the fields: ingredient as Foreign key, ingredient_quantity and cost_per_ingredient. How can I use the information that I already have in the Ingredient model (cost_per_unit) to calculate the cost_per_ingredient (it would be cost_per_unit * ingredient_quantity) ? Thanks in advance -
How to filter list data by id and show the single object in HTML template by django?
This is the Json List Below: "chartOfAccounts": [ { "id": 147, "name": "Sales Product - Wholesale test", "description": "Sales - Wholesale", "balance": "0.00", "is_active": true, "is_editable": true, "account_detail_type": { "id": 5, "name": "Accounts Receivable (A/R)", "account_type": { "id": 2, "name": "Accounts Receivable (A/R)", "principle": { "id": 1, "name": "Asset", "calculation_type": "dr" } }, "calculation_type": "dr" } }, { "id": 146, "name": "Sales Product - Wholesale test", "description": "Sales - Wholesale", "balance": "0.00", "is_active": true, "is_editable": true, "account_detail_type": { "id": 5, "name": "Accounts Receivable (A/R)", "account_type": { "id": 2, "name": "Accounts Receivable (A/R)", "principle": { "id": 1, "name": "Asset", "calculation_type": "dr" } }, "calculation_type": "dr" } }, { "id": 145, "name": "Cash in hand rony", "description": "Cash in hand rony", "balance": "-45980.00", "is_active": true, "is_editable": true, "account_detail_type": { "id": 1, "name": "Cash and cash equivalents", "account_type": { "id": 1, "name": "Cash and cash equivalents", "principle": { "id": 1, "name": "Asset", "calculation_type": "dr" } }, "calculation_type": "dr" } }, { "id": 144, "name": "6yt4", "description": "gyyy", "balance": "5203.00", "is_active": true, "is_editable": true, "account_detail_type": { "id": 1, "name": "Cash and cash equivalents", "account_type": { "id": 1, "name": "Cash and cash equivalents", "principle": { "id": 1, "name": "Asset", "calculation_type": "dr" } }, "calculation_type": "dr" … -
Django TrigramSimilarity search gives no such function: SIMILARITY
I am trying to do a TrigramSimilarity search in my Django project. As written in the django documentation i have done the following import: from django.contrib.postgres.search import TrigramSimilarity; I have also added 'django.contrib.postgres' inside the INSTALLED_APPS of the settings.py file. This is the code that brings to the error (i say 'brings' because the error itself comes only if i use the queryset: for example, if i do print(articles)(obviously after query) the error comes): articles = Article.objects.annotate( similarity=TrigramSimilarity('name', search_str), ).filter(similarity__gt=0.3).order_by('-similarity') print(articles) #that line causes the error (no such function: SIMILARITY) I have literally searched for everything, but it seems that no one had this error before. I have exactly did what the documentation says -> here -
Django - How to populate manytomany field in forms by previously selected options by users
How can I populate manytomany form field with previous user selected subs. In this code forms render choices with empty checkboxes. I want checkboxes to show which subscriptions user subscribed to. models.py class Subscription(models.Model): SUBSCRIPTION_TYPES = ( ('SUB1', _('sub 1')), ('SUB2', _('sub 2')), ) subscription_type = models.CharField(choices=SUBSCRIPTION_TYPES, max_length=30, unique=True) description = models.CharField(max_length=255, blank=True) class UserSubscription(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) subscriptions = models.ManyToManyField(Subscription, related_name='subscriptions', related_query_name='subscriptions') forms.py class SubscriptionForm(forms.ModelForm): class Meta: model = UserSubscription fields = ('subscriptions',) widgets = { 'subscriptions': forms.CheckboxSelectMultiple(), } views.py class SubscriptionFormView(FormView): template_name = 'profile/subscription.html' form_class = SubscriptionForm -
How to save and return multiple objects using PUT and PATCH method in Django
I'm trying to update some records in a DB table using the Update API view which consists of PUT and Patch methods. Upon calling the API I'm getting MultipleObjectsReturned: get() returned more than one error. Below are sample records that I'm trying to update. [ { "id": 1, "value": 1.00, "spec_id": 6, }, { "id": 2, "value": 1.00, "spec_id": 6, }, { "id": 3, "value": 1.00, "spec_id": 6, }, I'm sending spec_id in API for ex:- /api/specification/:spec_id/ and payload as {'value':2.00}, which will basically be used for updating the data on the basis of spec_id by querying in to the table. Code to look data in the DB table based on spec_id and update all the records related to spec_id & return: views.py class SpecificationUpdateAPIView(BaseAuthenticationMixin, generics.UpdateAPIView): serializer_class = SpecificationAdminSerializer permission_classes = [IsAdminUser] lookup_field = "spec_id" queryset = Specification.objects.all() serializers.py class SpecificationAdminSerializer(CreateUpdateModelSerializer): class Meta(CreateUpdateModelSerializer.Meta): model = Specification fields = ("id", "value", "spec") urls.py path( "api/specification/<int:spec_id>/", views.SpecificationUpdateAPIView.as_view(), name="specification-update-view", ) Could someone please help me resolve this issue, highlight the mistake I'm doing or navigate me to any other better approach to make this kind of scenario work? Thanks in advance. -
Custom filter with Django Filters
I am trying to write my own custom filter class as follows using django_filters: from django_filters import rest_framework as filters class FooFilter(filters.FilterSet): class Meta: model = Model fields = ['custom_field',] class Foo(): filter_backends = (filters.DjangoFilterBackend,) filterset_class = FooFilter In models, as I do not have the field custom_field, it will give the error: TypeError: 'Meta.fields' must not contain non-model field names: custom_field Question: Is it possible to define my own custom query that is a non-model field name using Django Filterset? -
Django AssertRedirects throws Assertion error 301 != 302
My Django view conditionally redirects to either error page or the target page on invoking 'get'. I am using redirect(reverse()) for the redirection logic. When I run this application, the url redirections are working as expected. For writing test cases, I mocked the function that returns this redirect(reverse()). I confirmed that the mock response is being returned when the method is called. But the response in the test case either shows http404ResponseNotFound or an assertion Error 301 != 302. How to properly test for redirection? Below code for reference Class MyView: def foo(self): try: # some logic return redirect(reverse('someview', kwargs={'key': '12345'})) except(ExceptionClass1, ExceptionClass2) as err: return errorView.as_view()(err) def get(self): # some logic if (some_condition) return self.foo() # Test case is for this line. return something_else Class MyViewTests: @mock.patch(MyView.foo) def test_1(self, mock_foo): mock_foo.return_value = redirect(reverse('step', kwargs={'key': '123'})) client = Client() response = client.get('/myview', follow=True) self.assertRedirects(response, '/view/step/123', fetch_redirect_response=False) Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/mock/mock.py", line 1346, in patched return func(*newargs, **newkeywargs) File "/usr/src/app/django/tests/test_api.py", line 488, in test_1 self.assertRedirects(response, '/view/step/123', fetch_redirect_response=False) File "/usr/local/lib/python3.8/site-packages/django/test/testcases.py", line 274, in assertRedirects self.assertEqual( AssertionError: 301 != 302 : Initial response didn't redirect as expected: Response code was 301 (expected 302) -
OperationalError at /admin/login/ even after making migrations
I have made migrations still i am getting this error . I have tried deleting the database and making it again. I have tried making migrations again and again but problem is still there. OperationalError at /admin/login/ no such table: auth_user -
Javascript Uncaught ReferenceError: grp is not defined
This error occured in the admin model object list panels. This caused the select all checkbox to not work. (grp.jQuery); Is at the end of a few admin js files. Yet I cannot find where grp is defined. Reinstalling django did not work for me. Edit: This problem occured after I uninstalled grappelli, I am fairly sure I have removed everything related to that. -
How to delete model data on button click? - Django
I have the following button: <a style="float:right; margin:5px; color: white;" href="" class="btn btn-success" >Accept</a> When the button is clicked on by the user, I want to delete data that is associated with the pk For example, when the button is clicked, I want to pass the {{donation.pk}} into a function and delete the Donation that is associated with it I have done so much research but I can not find out a way to do this. -
django displaying subcategories of categories
how can i pass subcategories to a category, i am trying {%for subcat in cat.sub_categories_set.all %} is it worth doing it separately? then I will not be able to display new categories? template <div class="widget catagory mb-50"> <!-- Widget Title --> <h6 class="widget-title mb-30">Categories</h6> {% for cat in categories %} <div class="catagories-menu"> <ul id="menu-content2" class="menu-content collapse show"> <!-- Single Item --> <li data-toggle="collapse" data-target="#{{ cat.name }}"> <a href="#">{{ cat.name }}</a> <ul class="sub-menu collapse show" id="{{ cat.name }}"> <li><a href="{% url 'shop_clothing' %}">All</a></li> {% for subcat in cat.sub_categories_set.all %} <li><a href="{% url 'shop_subcategory' subcat.slug %}">{{ subcat.name }}</a></li> {% endfor %} </ul> </li> </ul> </div> {% endfor %} *view* class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = True model = Item def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) categories = Category.objects.all() sub_categories = SubCategory.objects.all() context['categories'] = categories context['sub_categories'] = sub_categories return context def get_ordering(self): return self.request.GET.get('orderby', ) -
How to proccess token?
I have a question. In my project, after a user loges in my app generates an access token and then put it on cookies. This access token contains information like user rights and some other details about him. For authentication part I use 'DEFAULT_AUTHENTICATION_CLASSES' which is mapped to a class that subclasses TokenAuthentication class from rest_framework.authentication. Instead of decoding again the access token in every view, how can I have it's rights from access token? What should I use? May put decoded token in request.session? -
Hi, is there any way of getting rid of the autocomplete background when my webpage has loaded my saved login credentials?
If i delete the login credentials, the colour of the field is fine. it turns back to the grey colour that you can see in the image i've provided. However when reloading the page the light blue colour appears, which as you can see doesn't look very appealing. I've tried to find a solution on YouTube and i cant seem to find anything. Does anyone have a solution for this? image of my field HTML code: <form method="POST" autocomplete="off" action="" name="form" > {% csrf_token %} <div class="wrapper"> <h1>Login</h1> <div class="form" > <div class="user_input" style="padding-top:10px ;"> <input type="text" name="username" placeholder="Username" class="form-control" style="border: none; background-color:#e9e9e9; height: 40px; padding:10px;"> </div> <div class="user_input"style="padding-top:10px;" > <input type="password" name="password" placeholder="Password" class="form-control" style="border: none; background-color:#e9e9e9; height: 40px; padding:10px;"> </div> <div class="button" > <button type="submit" style="width: 130px; height: 40px; border-radius: 8px; color: white; background-color:#0088a9; border: none;" >Login</button> </div> {% for message in messages %} <p id="messages" style="text-align: center; margin-top: 20px;">{{message}}</p> {% endfor %} <div class="loginbtn"> <p style="margin-top: 20px; text-align: center; color: black;">Don't have an account?<br> click here to <a href="{% url 'register' %}">Sign up</a> </p> </div> </div> </div> </form> CSS code: *{ margin: 0; padding: 0; box-sizing: border-box; outline: none; text-decoration: none; font-family: 'Raleway', sans-serif; } .wrapper{ position: … -
Django LOGIN_REDIRECT_URL changes does not affect behavior
The login redirect url was set to the dashboard since now when I have tried to change it to all-records. I have noticed that no matter what url I put there, it will redirect to dashboard. Even if I delete the line it redirects to dashboard. I am using django debug toolbar and the settings file is saved and updated correctly. How do I fix this. settings.py LOGIN_REDIRECT_URL = 'all-records' app/urls.py from django.urls import path from . import views urlpatterns = [ path('dashboard/', views.DashboardView.as_view(), name='dashboard'), path('all-records/<str:filter>', views.TbEntranceRightListView.as_view(), name='all-records'), ] -
Django Allauth: How to add more custom fields on signup form?
I am using Django Allauth on my project and I need more than the default fields on the signup form. I've tried many tutorials, but none seems to work for me. Which is the best way to customize the User model and the forms while using allauth, to save this new data? Thanks in advance! -
error message:===Invalid block tag on line 31: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
PLease do let me know where i went wrong>>> -
Django html form: how to only populate field value if it exists?
My Django app has a Person model with some optional text fields, such as: nickname = models.CharField(max_length=20, null=True, blank=True, default='') When a record doesn't have one of these fields populated, it just appears empty in the Django Admin (as expected). I have a little form where a person can update some select fields on the record, and the field appears on the form like so (prefilling the field with the current value): <label class="col-form-label mt-4" for="nickname">Nick name:</label> <input type="text" class="form-control" value="{{ person.nickname }}" id="nickname" name="nickname"> The Problem: For a record where the field is empty, 'None' is shown as the value on the form field, and if you submit the form without removing it, the record is updated with the string 'None' saved for that field. How can I update my code so the form only pre-fills that 'value' if there's actually an existing value to use? -
Method Not Allowed (POST) in Django 3.1
I am new to Django. Practicing in a small project in Dango 3.1 I get the error "Method Not Allowed (POST)". The error appears when a user presses the Guarder (Save) button. Method Not Allowed: /pizarra/comunicado/ [30/Jul/2021 09:10:03] "POST /pizarra/comunicado/ HTTP/1.1" 405 0 Everything was working before and I can't understand what I'm doing wrong. Please if someone can help me. Thanks in advance. comunicado_form.html {% extends 'gestion/base_gestion.html' %} {% block page_content %} <form method="POST" class="form-group"> {% csrf_token %} <div class="col-xl-12 col-md-12 mb-12"> {% if obj %} <div class="card border-left-warning shadow h-100 py-2"> {% else %} <div class="card border-left-success shadow h-100 py-2"> {% endif %} <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-success text-uppercase mb-1"> {% if obj %}Editar{% else %}Nuevo{% endif %} Comunicado </div> <div class="dropdown-divider"></div> <div class="col-sm-8"> <div class="col-8"> <div class="form-group"> <label for="id_contenido">Contenido del mensaje:</label> {{ form.contenido }} </div> </div> <div class="col-3"> <div class="form-group"> <label for="id_fecha_vto">Fecha Vto:</label> {{ form.fecha_vto }} </div> </div> <div class="col-2"> <div class="form-group"> <label for="id_hora_vto">Hora Vto:</label> {{ form.hora_vto }} </div> </div> <div class="col-3"> <div class="form-group"> <label for="id_es_borrador">¿Es Borrador?:</label> {{ form.es_borrador }} </div> </div> <div class="col-2"> <div class="form-group"> <label for="id_es_borrador">Estado:</label> {{ form.estado }} </div> </div> <!-- {{ form.as_p }} --> </div> … -
models.ForeignKey() in django
Here is my code from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) So I'm kinda confused with what models.DateTimeField(default=timezone.now) do, what does "default" mean here? And I'm also confused what models.ForeignKey(User, on_delete=models.CASCADE) do, what is "on_delete=models.CASCADE" do and mean? And is this code ( from django.contrib.auth.models ) a database for users? -
How to change the name of a third party app on Django?
I am using django-allauth and its account app conflicts with my account app. I managed to fix this conflict by creating an app label for allauth.account based on this solution from django.apps import AppConfig class AllAuthAccountConfig(AppConfig): name = 'allauth.account' label = 'allauth_account' verbose_name = 'aullauth_account' and then adding it to installed apps INSTALLED_APPS = ( ..., 'apps.allauth.apps.AllAuthAccountConfig', ..., ) Now, when I try to migrate it gives an error CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0001_initial, 0002_email_max_length in allauth_account). To fix them run 'python manage.py makemigrations --merge' but python manage.py makemigrations --merge also fails with the following error: ValueError: Could not find common ancestor of ['0001_initial', '0002_email_max_length'] How can I change the allauth.account app name so it doesn't conflict with my app or my migations? -
Using Adobe pdf extract API in Django
I am trying to get the InMemoryUploadedFile from django rest api and pass it on to the adobe extract API function. The error says like its not a pdf or something. But i just uploaded the sample pdf that the adobe gave. I am guessing I am wrong somewhere in the source file part, but not sure. Could somebody help? Here is the code for adobe api thingy ''' import logging import os.path from adobe.pdfservices.operation.auth.credentials import Credentials from adobe.pdfservices.operation.exception.exceptions import ServiceApiException, ServiceUsageException, SdkException from adobe.pdfservices.operation.pdfops.options.extractpdf.extract_pdf_options import ExtractPDFOptions from adobe.pdfservices.operation.pdfops.options.extractpdf.extract_element_type import ExtractElementType from adobe.pdfservices.operation.pdfops.options.extractpdf.extract_renditions_element_type import \ ExtractRenditionsElementType from adobe.pdfservices.operation.pdfops.options.extractpdf.table_structure_type import TableStructureType from adobe.pdfservices.operation.execution_context import ExecutionContext from adobe.pdfservices.operation.io.file_ref import FileRef from adobe.pdfservices.operation.pdfops.extract_pdf_operation import ExtractPDFOperation def extract(file_object): logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) try: # get base path. # base_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) base_path = os.path.dirname(__file__) # print(base_path, os.path.dirname(__file__), os.path.abspath(__file__)) # print(base_path) # Initial setup, create credentials instance. credentials = Credentials.service_account_credentials_builder() \ .from_file(base_path + "/adobe_credentials/pdfservices-api-credentials.json") \ .build() # Create an ExecutionContext using credentials and create a new operation instance. execution_context = ExecutionContext.create(credentials) extract_pdf_operation = ExtractPDFOperation.create_new() # Set operation input from a source file. # source = FileRef.create_from_local_file( # base_path + "/resources/sample_statement_thiyagaraja.pdf") source = FileRef.create_from_stream( file_object, media_type="application/pdf") extract_pdf_operation.set_input(source) # Build ExtractPDF options and set them into the operation extract_pdf_options: … -
Update status in django field - status CHOICES
I have a model django and I want to update my fields Status Choices: my models.py class Top(core.BaseModel): class Status(models.IntegerChoices): EMPTY = 0,'-----' SEND_CANCEL = 1, 'Send' CANCELLED = 2, 'Cancel' my views.py class TopUpdateView(core.UpdateView): template_name = 'top/update_top.html' form_class = UpdateTopForm @require_POST def cancel_status(request, pk, status): top = get_object_or_404(Top, pk=pk, status=None, user=request.user) top.status= status.CANCELLED top.save(update_fields=['status']) return redirect('top:item-detail') urls.py path('top/<pk>/cancel/', views.cancel_status, name='cancel-status'), template: <button class="btn"> <a href="{% url 'top:cancel-status' object.id %}"> Cancel </button> All what I want here it is update CHOICE field status from EMPTY on CANCELLED when I click on button. But it is does not work (((( I know how to update and save simple field but do not unserstand the best way update Choices Field in view.Anybode please help me! -
authtoken/access token validation in django
So I know there are a lot of DRF packages for auth token authentication but my project uses simple functions as API and I need some auth token type features. It should be able to validate the access token and only then it should give a response. Is there any 3rd party package I can use for the same?