Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make the inventory decrease by 1 book when I borrow from the library, and increase by 1 when I return the book?
In the Book model, I made 2 methods to call them in the Borrowing field, but I haven't figured out how exactly to do it. And it is especially not clear how to connect the logic of returning the book. In the Borrowing model, there is only the actual_return_date field, when it is filled in, 1 should be added to the inventory, I think so. I tried to change the create method but it didn't work. model Book: from django.db import models class Book(models.Model): COVER_CHOICES = [("HARD", "Hard cover"), ("SOFT", "Soft cover")] title = models.CharField(max_length=255) authors = models.CharField(max_length=256) cover = models.CharField(max_length=15, choices=COVER_CHOICES) inventory = models.PositiveIntegerField() daily_fee = models.DecimalField(max_digits=7, decimal_places=2) class Meta: ordering = ["title"] def __str__(self): return ( f"'{self.title}' by {self.authors}, " f"cover: {self.cover}, " f"daily fee: {self.daily_fee}, " f"inventory: {self.inventory}" ) def reduce_inventory_book(self): self.inventory -= 1 self.save() def increase_inventory_book(self): self.inventory += 1 self.save() book/view.py from rest_framework import viewsets from book.models import Book from book.serializers import BookSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer book/serializers.py from rest_framework import serializers from book.models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ("id", "title", "authors", "cover", "inventory", "daily_fee") model Borrowing: from django.conf import settings from django.contrib.auth.models import AbstractUser from … -
Django: how to exclude certain results based on the values of other rows in the table?
I have a Django model called ProductPrice with a custom QuerySet as a manager: class ProductPriceQuerySet(models.QuerySet): def available(self, user): Group = apps.get_model("memberships", "Group") q = Q(title="Non-Member") if user.is_authenticated and user.member: q = q | Q(membership__members__user=user) return self.annotate( available=Case( When( membership_group__in=Group.objects.filter(q), then=True, ), default=False, ) ).order_by("stock", "-price") class ProductPrice(models.Model): stock = models.ForeignKey( StockManagement, on_delete=models.CASCADE, related_name="prices" ) membership_group = models.ForeignKey( "memberships.Group", null=False, blank=False, on_delete=models.PROTECT ) price = models.FloatField() objects = ProductPriceQuerySet.as_manager() This works for displaying available prices on the front end. But what I want to do is exclude the higher non-member price if the user is able to buy the item at a lower price point. What would be the best way to do this? I was thinking of another annotation like: display=Case( When( membership_group__in=Group.objects.filter(q) & ProductPrice.objects.filter( price__lt=F("price"), ), then=True, ), default=False, ) But this gives the error Cannot combine queries on two different base models. Is there an option to do this with SubQuery? Or would that be too expensive? -
Django complex filter through ManyToManyField and ForeignKey
I have a number of database tabels that are connected via manytomany and foreign key fields. from django.db import models class User(models.Model): name = models.CharField(max_length=20) class Bookings(models.Model): user = user = models.ForeignKey( User, blank=True, null=True, on_delete=models.SET_NULL) class Event(models.Model): bookings = models.ManyToManyField( Booking, related_name="event_bookings", blank=True) class ScheduleManager(models.Manager): def for_user(self, user): """ Returns a Schedule queryset for a given user object. Usage: user= User.objects.first() Schedule.objects.for_user(user) """ qs = self.get_queryset() #need to extend this to return Schedule qs return qs class Schedule(models.Model): event = models.ForeignKey( Event, on_delete=models.CASCADE ) objects = ScheduleManager() I would like to query the database to output a Schedule queryset for a given User object by calling Schedule.objects.for_user(User). I have been playing with a combination of prefetch_related and select_related to no prevail. I can get hold of the correct qs by using a bunch of chained queries and loops but its not the most elegant and I'm am hitting the db far too many times. Any help will be appreciated. -
OperationalError at /admin/store/product/
http://127.0.0.1:8000/admin/store/product/ it shows the error on that http://127.0.0.1:8000/admin/store/product/add/ links works perfect but whenever I try to add product it shows same error -
lookup was already seen with a different queryset. Django
I have a Quotes model referenced by the Comment model, which has a liked field (likes of the Comment model). I am trying to optimize the query so that there is no n+1 error, but this exception occurs. The problem is that I need to pull the user out of Comment and like, but it doesn't come out. How to do it? Table 'user' - it's ForeignKey Table 'liked' - it's ManyToManyField Views.py def get(self, request, *args, **kwargs): post = Quotes.objects.prefetch_related( Prefetch( 'quotes_comment', queryset=Comment.objects.select_related('user')) ).prefetch_related( Prefetch( 'quotes_comment', queryset=Comment.objects.select_related('liked') ) ) -
How to make filtering with SerializerMethodField()?
I'm creating table that show objects of a model and I have a SerializerMethodField that shows a value from a different table with same transaction ID. The problem is I'm using the serializers for the filtering table and chargeback is not working in there. How Can I make it filterable? Simplifying the code, a have this model: class PSerializer(serializers.ModelSerializer): ... chargeback = serializers.SerializerMethodField() def get_value(self, obj): ctransaction = CTransaction.objects.raw('SELECT * ' 'FROM ctransaction ' 'WHERE TRIM(mid)=TRIM(%s) ' 'AND TRIM(unique_id)=TRIM(%s) ' 'AND TRIM(num)=TRIM(%s) ' 'AND rc_code IN (%s, %s, %s)', [obj.mid, obj.unique_id, obj.num, '1', '1', '1']) if len(cs_transaction) > 0: return 'Yes' return 'No' -
Django Api-Key with unit test
I am trying to implement unit tests to an existing project, the existing project uses Api-Key's to access and authenticate against the Api endpoints. if I do the following via postman or command line: curl --location --request GET 'http://127.0.0.1:8000/api/user_db' \ --header 'Authorization: Api-Key REDACTED' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "test@testing.local" }' This will call the following view function and return the user details with the corresponding oid (json response) without error. from django.shortcuts import render from rest_framework_api_key.permissions import HasAPIKey from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from user_api.classes.UserController import ( GetBusinessUser, CreateBusinessUser, UpdateBusinessUser, DeleteBusinesssUser ) from celery.utils.log import get_task_logger import environ logger = get_task_logger(__name__) env = environ.Env() class ProcessUserRequest(APIView): permission_classes = [HasAPIKey |IsAuthenticated ] def get(self, request): logger.info("Get Business User Request Received") result = GetBusinessUser(request) return Response(result["result"], content_type='application/json charset=utf-8', status=result["statuscode"] This additionally calls the following shortened function: def GetBusinessUser(request) -> Dict[str, Union[str, int]]: logger.info(f"Processing Get Username Request: {request.data}") valid_serializer = ValidateGetBusinessUserFormSerializer(data=request.data) valid_serializer.is_valid(raise_exception=True) username = valid_serializer.validated_data['username'] return BusinessUser.objects.filter(username=username).first() As I wish to make unit test cases to ensure I can validate prior to deployment, I have implemented the following in the modules tests.py file: from rest_framework.test import APITestCase, APIClient from rest_framework_api_key.models import … -
500 internal server error while accessing hx-requests in Django project
I am working on a Django project to create a dynamic form using HTMX using a YouTube video.. As I am clicking "Add" button to add a form, no form gets added.. and as I inspect the browser console, I get the following error: GET http://127.0.0.1:8000/businesscase/htmx/project-form/ 500 (Internal Server Error) lr @ htmx.org@1.8.5:1 (anonymous) @ htmx.org@1.8.5:1 i @ htmx.org@1.8.5:1 Response Status Error Code 500 from /businesscase/htmx/project-form/ St @ htmx.org@1.8.5:1 ee @ htmx.org@1.8.5:1 Q @ htmx.org@1.8.5:1 fr @ htmx.org@1.8.5:1 o.onload @ htmx.org@1.8.5:1 load (async) lr @ htmx.org@1.8.5:1 (anonymous) @ htmx.org@1.8.5:1 i @ htmx.org@1.8.5:1 I tried to search a lot in Google to get rid of this error, but unfortunately all I received was to refresh browser, clear cache etc which I did but the problem persists.. I'd really appreciate of any quick solution here.. many thanks.. -
We have created django app , I am making test script for my api but I have getting AssertionError: 401 != 201 , I am giving sample code
We have created django app , I am making test script for my api but I have getting AssertionError: 401 != 201 , I am giving sample code error :- Traceback (most recent call last): File "C:\Abhishek\Git\taskManagement\tests.py", line 108, in test_auth_user_can_create_project self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 401 != 201 views.py class Projects(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAuthenticated] """ To create the project """ def post(self, request): request.data['created_by'] = request.user.id request.data['username'] = request.user.username serializer = ProjectSerializer(data=request.data) if not serializer.is_valid(): print(serializer.errors) return Response({ 'success': False, 'errors': serializer.errors, 'message': _("something is wrong") }) serializer.save() return Response({ 'success': True, 'Project': serializer.data, 'message': _("Project create successfully") }) tests.py def test_auth_user_can_create_project(self): client = APIClient() data = { "project_name": "Test project testscript", "project_description": "test project desc", } response = self.client.post('/api/project/', data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) -
Retrieve the human readable value of a a charfield with choices via get_F00_display in Django views.py
What I want to do : Display the human readable value of a charfield with choices via get_F00_display or other in views.py and then in template. I have a Leave model for leaves management et want to display a template with all the leaves associated with the authenticated user. What I have done : Of course, I've read Django documentation (4.1) and find something interesting with get_F00_display but cannot make it works fine. model.py (simplified) class Leave(CommonFields): LEAVES_TYPES = [ ('10', _('Type 1')), ('20', _('Type 2')), ('30', _('Type 3')), ] owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) type = models.CharField(max_length=3, choices=LEAVES_TYPES, null=True, default="10") def __str__(self): return self.owner.first_name + " " + self.owner.last_name + " : du " + self.begin_date.strftime("%d-%m-%Y") + " au " + self.end_date.strftime("%d-%m-%Y") views.py from django.shortcuts import render from django.utils.translation import gettext as _ from .models import Leave from django.views import generic class LeaveListView(generic.ListView): model = Leave context_object_name = 'leave_list' def get_queryset(self): return Leave.objects.filter(is_active=True).values('type', 'begin_date','end_date','range','comment','status') def get_context_data(self, **kwargs): # Call the base implementation first to get the context context = super(LeaveListView, self).get_context_data(**kwargs) # Create any data and add it to the context context['colHeaders'] = ['Type', 'From', 'To.', 'Range', 'Comment', 'Status',] return context leave_list.html {% extends "main/datatables.html" %} <!-- TABLE … -
Writable nested serializers for multiple items for same base class
I have been following the guide to write nested serializer. Previously, I had only one item in my json object which was CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents and I am able to save the data properly in the databae. I want to add NetIncomeLoss the same way but I am running into the issue below. Can someone please point me where my mistake is? I am unable to find documentation/example or an answer online TypeError: Basetable() got unexpected keyword arguments: 'NetIncomeLoss' Serializer: class PeriodSerializer(serializers.ModelSerializer): instant = serializers.CharField(required=False, max_length=255) startDate = serializers.CharField(required=False, max_length=255) endDate = serializers.CharField(required=False, max_length=255) class Meta: model = Period fields = "__all__" extra_kwargs = {'cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id': { 'required': False}, 'netincomeloss_id': { 'required': False}} class CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = Cashcashequivalentsrestrictedcashandrestrictedcashequivalents fields = ['decimals', 'unitRef', 'value', 'period'] class NetIncomeLossSerializer(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = Netincomeloss fields = ['decimals', 'unitRef', 'value', 'period'] class CashFlowSerializer(serializers.ModelSerializer): CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer( many=True) NetIncomeLoss = NetIncomeLossSerializer( many=True) class Meta: model = Basetable fields = "__all__" def create(self, validated_data): itemOneData = validated_data.pop( 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents') cashflow = Basetable.objects.create(**validated_data) for data in itemOneData: period_data = data.pop("period") my_long_named_obj = Cashcashequivalentsrestrictedcashandrestrictedcashequivalents.objects.create( basetable_id=cashflow, **data) period_object = Period.objects.create( cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id=my_long_named_obj, **period_data ) itemTwoData = validated_data.pop( 'NetIncomeLoss') cashflow = Basetable.objects.create(**validated_data) for data in itemTwoData: period_data … -
Set same color as prev row if data matches otherwise different color when rows are dynamically created
I need to set same color as previous row if data matches otherwise use a different color when rows . The code works if the rows, cells and text within cells are hardcoded as here https://codereview.stackexchange.com/questions/121593/set-same-color-as-prev-row-if-data-matches-otherwise-different-color but produces alternating colouring when the rows, cells and text are dynamically generated. $(document).ready(function () { var c = 0; $("#tblExport tbody tr").each(function () { var $item = $("td:first", this); var $prev = $(this).prev().find('td:first'); if ($prev.length && $prev.text().trim() != $item.text().trim()) { c = 1 - c; } $(this).addClass(['zebra-even', 'zebra-odd'][c]); }); }); #tblExport>tbody { font: normal medium/1.4 sans-serif; } #tblExport { border-collapse: collapse; width: 100%; } #tblExport th,td { padding: 0.25rem; text-align: left; border: 1px solid #ccc; } #tblExport th { background: #bfbfbf; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> {% for product in products %} <tr> <td>{{product.name}}</td> <td>{{product.price}}</td> </tr> -
Django Forms - Declarative Fields Meta class is not iterable
Why django throws me an error TypeError at /primary argument of type DeclarativeFieldsMetaclass is not iterable. I'm trying to work with django-forms for the first time, after i added this into my forms.py file, it keeps showing me the error message saying: TypeError at /primary argument of type 'DeclarativeFieldsMetaclass' is not iterable, how can i solve this problem? Forms.py from django import forms from .models import Primary, PrimaryAlbum, Secondary, SecondaryAlbum from jsignature.forms import JSignatureField from jsignature.widgets import JSignatureWidget class PrimaryForms(forms.Form): signature_of_student = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) class Meta: model = Primary fields = ['admission_number', 'profile_picture', 'first_name', 'last_name', 'gender', 'address_of_student', 'class_Of_student', 'signature_of_student'] Views.py from .forms import PrimaryForms class CreatePrimaryStudent(LoginRequiredMixin, CreateView): model = Primary fields = PrimaryForms template_name = 'create_primary_student_information.html' success_url = reverse_lazy('Home') def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['year_of_graduation'].queryset = PrimaryAlbum.objects.filter(user=self.request.user) return form def form_valid(self, form): form.instance.user = self.request.user return super(CreatePrimaryStudent, self).form_valid(form) -
I need to insert data in table SQLite Django
I am new to Django. I think it's really easy one for Django expert, so I wish I could get help from you. I have two tables in SQLite DB-namely Process and ScrapedData. While migrating models I have several error so I just create these two tables manually by Navicat. Following shows models. class Process(models.Model): PLATFORM=( ('Instagram','Instagram'), ('Facebook','Facebook'), ('LinkedIn','LinkedIn'), ('TikTok','TikTok'), ('Youtube','Youtube'), ('Twitter','Twitter') ) hashtag=models.CharField(max_length=300) platform=models.CharField(choices=PLATFORM,max_length=9) date=models.DateField(auto_now_add=True) class ScrapedData(models.Model): homepage=models.CharField(max_length=500) email=models.CharField(max_length=100) process_id=models.ForeignKey( Process, on_delete=models.CASCADE, verbose_name="the related Process") Then I tried to insert data into these two tables then I got following error. File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: table info_scrapeddata has no column named process_id_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\task\scrapping\scraping for google api\College-ERP\info\views.py", line 116, in attendance_search ScrapedData.objects.create(homepage=url.strip(),email=email, process_id=new_process) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) File … -
Celery basic scheduling with apply_async is extremely slow
Scheduling tasks from Django endpoints are very slow. .delay / .apply_async of any (even dummy) task takes about 150-200ms which is terrible. Redis is up and running in docker, task is being scheduled to worker without any retries, but it takes ~200 ms just to deliver task to queue. Maybe i am missing some configuration options? My setup: Python 3.10 Django 4 Celery 5.2.7 Eager execution is disabled, celery configs are pretty much default. Attached is a profiler output where simple task eats twice a time of a heavy DB-load operations (see marked (!)): Line # Hits Time Per Hit % Time Line Contents ============================================================== 339 @profile 340 def handle_single_transition( 341 self, 342 *, 343 cr: CR, 344 user: User, 345 taxonomy_data: dict, 346 cr_metadata: dict, 347 attachments: list[InMemoryUploadedFile] = None, 348 ) -> CR: 350 1 0.0 0.0 0.0 target_state_id = cr_metadata.get("target_state_id") 351 1 0.0 0.0 0.0 action_id = cr_metadata.get("action_id") 352 354 1 0.0 0.0 0.0 if target_state_id is None or (cr.state_id == target_state_id): 355 return cr 356 357 1 28.0 28.0 6.1 transition = cr.workflow.get_transition( 358 1 0.0 0.0 0.0 target_state_id=target_state_id, 359 1 0.0 0.0 0.0 action_id=action_id, 360 ) 361 363 1 0.1 0.1 0.0 if taxonomy_data and … -
CORS Issues with Nginx as Reverse Proxy for Django
I am running Nginx as my webserver to server the static frontend files and as a reverse proxy for my Django Server. The Problem is that i am having CORS Issues, when doing request from the frontend. My Design-Plan was to use the Apex Domain example.com for the frontend and all API Calls go to api.example.com. I already did a tone of research and tried to catch OPTIONS request etc. but i still have CORS Errors. Also Django has the django-cors package installed and Axios is using .withDefaultCredentials = true. My current nginx config looks like this: server { listen 80; listen [::]:80; server_name $DOMAIN_HOSTNAME; root /var/www/example.com/dist; location /media { alias /var/www/example.com/media/; } location / { try_files $uri $uri/ /index.html =404; } } upstream djangoserver { server django:8000; } server { listen 80; listen [::]:80; server_name $API_DOMAIN_HOSTNAME; location / { proxy_pass http://djangoserver; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header 'Access-Control-Allow-Origin' $http_origin; proxy_set_header 'Access-Control-Allow-Credentials' 'true'; proxy_redirect off; add_header 'Access-Control-Allow-Origin' 'https://example.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Allow-Credentials' 'true'; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' 'https://example.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Allow-Credentials' 'true'; return 204; } } } Also so … -
Server refusing to run in Pycharm giving the following error: OSError: [WinError 127] The specified procedure could not be found
OSError: [WinError 127] The specified procedure could not be found The app was working fine until after I pip installed django-sms. I have since uninstalled django-sms but still getting the same error. Contro panel output -
Django Request input from User
I'm having a Django stack process issue and am wondering if there's a way to request user input. To start with, the user is loading Sample data (Oxygen, CHL, Nutrients, etc.) which typically comes from an excel file. The user clicks on a button indicating what type of sample is being loaded on the webpage and gets a dialog to choose the file to load. The webpage passes the file to python via VueJS/Django where python passes the file down to the appropriate parser to read that specific sample type. The file is processed and sample data is written to a database. Issues (I.E sample ID is outside an expected range of IDs because it was keyed in wrong when the sample was taken) get passed back to the webpage as well as written to the database to tell the user when something happened: (E.g "No Bottle exists for sample with ID 495619, expected range is 495169 - 495176" or "356 is an unreasonable salinity, check data for sample 495169"). Maybe there's fifty samples without bottle IDs because the required bottle file wasn't loaded before the sample data. Generally you have one big 10L bottle with water in it, the … -
How to migrate from StaticBlock to StructBlock?
I have to change an already existing StaticBlock to a StructBlock: class SomeBlock(blocks.StaticBlock): pass class Meta: ... to: class SomeBlock(blocks.StructBlock): ... class Meta: ... However if the wagtail page has already SomeBlock configured in it, I receive the error: NoneType is not iterable Since I don't have anything inside the StaticBlock. I need to write a custom data migration for this. Based on Schema Operations listed, I couldn't find a way to change the actual block type. How do I approach this? -
Using for loop to Html Form in Django Template
I am facing problems handling forms in Django template for loop. <form method="post" id="infoloop{{forloop.counter}}"> {% csrf_token %} <div class="form-group"> <button type="submit" name="infobutton" class="btn btn-warning float-right {% if subs%} {% else %}disabled{% endif %}">update</button> </div> </form> I want to create this form my all employees, but seems doesn't work. Only first loop can create form tag so i can't update second employee info's. Can anyone help me? -
URL Parameters to CreateView and automatic select value in a dropdown
I need, from a listview table, with an js button, open the createview and pass with parameter the id about an specific row that, in the createview form, select automatically the value in a dropdown. I imagine that, it would be with a parameter in the url of the createview and, in the createview, select in the post def the dropdown's row with the value of the parameter. Sorry if my explication it's very complicated. Examples. I have one model, Projects and I have a second model, Phases of these Projects. When I have listed the projects, from a button in one Project's row, I would need that to open the phases's createview and in the form, to select automatically the value of the dropdown's row. Projects form (the icons are bad): projects form When I click on the button with the url path('phases/add/', phasesCreateView.as_view(), name='phases_create'),, I need that in the destiny form phases form, the first dropdown would be completed automatically. -
When to run tests in dockerized django application?
I'm building a CI/CD for a django application. We dockerized the application and now our goal is to automate the building process triggered by push on a github repository. We are now building the GitHub Actions side. The project requires all containers to be running. I'm wondering where I should be running tests. Running them in the docker file seems useless as there are several tests that would fail if the other containers are not running (postgres container for example, or rabbitmq ). The approach I was thinking was to maybe setup a job in GitHub actions, build and start all containers with compose and then run the tests ? What is the recommended approach ? -
how to create celery periodic task in django rest framework Views?
I use django rest framework. I want the celery task to execute an operation once on the date that the user enters... this is my celery conf: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Bimsanj.settings') celery_app = Celery('Bimsanj') celery_app.conf.task_queues = ( Queue('default', routing_key='default'), Queue('reminder', routing_key='reminder'), ) celery_app.conf.task_default_queue = 'default' celery_app.conf.task_routes = { 'send_reminder_message_task' : {'queue' : 'reminder'}, } # Load task modules from all registered Django apps. celery_app.autodiscover_tasks() celery_app.conf.broker_url = BROKER_URL celery_app.conf.result_backend = RESULT_BACKEND and this is my View: class InsuranceReminderView(GenericViewSet, CreateModelMixin): serializer_class = InsuranceReminderSerializer model = InsuranceReminder def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) clocked = ClockedSchedule.objects.create(serializer.validated_data['due_date']) PeriodicTask.objects.create( clocked=clocked, name=str(uuid4()), one_off=True, task="apps.insurance.tasks.send_message_insurance_reminder", args=([serializer.validated_data['title'], serializer.validated_data['mobile'], serializer.validated_data['due_date']]) ) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) and this is my task: logger = get_task_logger(__name__) @celery_app.task(name="apps.insurance.tasks.send_message_insurance_reminder") def send_message_insurance_reminder(title, mobile, due_date): logger.info('send message insurance reminder') # return send_reminder_message(title, mobile, due_date) return f'{title} _ {mobile} _ {due_date}' What is the correct way to create a periodic task and execute the task at the date that the user enters? Thanks. -
ERROR: Encountered errors while bringing up the project. DJANGO Docker
Successfully built 112f09badeb6 Successfully tagged be-django-nw_nginx:latest be-django-nw_db_1 is up-to-date Recreating cb0d468ab8a2_be-django-nw_web_1 ... error ERROR: for cb0d468ab8a2_be-django-nw_web_1 Cannot start service web: failed to create shim: OCI runtime create failed: runc create failed: unable to start container process: error during container init: error mounting "/opt/BE-Django-Nw/.env" to rootfs at "/backendPeti/backendPeti/.env": mount /opt/BE-Django-Nw/.env:/backendPeti/backendPeti/.env (via /proc/self/fd/6), flags: 0x5000: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type ERROR: for web Cannot start service web: failed to create shim: OCI runtime create failed: runc create failed: unable to start container process: error during container init: error mounting "/opt/BE-Django-Nw/.env" to rootfs at "/backendPeti/backendPeti/.env": mount /opt/BE-Django-Nw/.env:/backendPeti/backendPeti/.env (via /proc/self/fd/6), flags: 0x5000: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type ERROR: Encountered errors while bringing up the project. i try docker image prune, docker system prune and i remove .env and i make it again but doesnt work. what should i do?? -
Int object is not callable in the code ${{order.get_cart_total}}
I have the following code in the model, while calling the get_cart_total int not callable or unsupported operand type(s) for +: 'int' and 'method'appaers I am expecting to get total from get_cart_total class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total @property def get_cart_total(self): items = self.get_cart_items() for item in items: total += item.get_total() return total class OrderItem(models.Model): ORDER_ITEM_TYPE = ( ('type1', 'Collection1'), ('type2', 'Collection2'), ) order = models.ForeignKey(Order, on_delete=models.CASCADE) collection_type = models.CharField(max_length=255, choices=ORDER_ITEM_TYPE) collection1 = models.ForeignKey(Collection1, on_delete=models.SET_NULL, null=True, blank=True) collection2 = models.ForeignKey(Collection2, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField() def get_total(self): if self.collection_type == "type1": return self.collection1.price * self.quantity elif self.collection_type == "type2": return self.collection2.price * self.quantity