Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Django letting me instantiate a model without a required field?
I have the following model in Django (using v4.0): class MyModel(models.Model): owner = models.OneToOneField(OtherModel, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=50) value = models.FloatField(default=0) # Some methods ... My question is why I don'get any errors when I execute anywhere the following code: new_model = MyModel.objects.create(owner=get_valid_owner(), value=500) Shouldn't name be required since I did not set blank=True to it? If I got it wrong, how can I make that field required? Thanks in advance. -
Not able to scrape data from ziprecruiters.com
I want to scrape some job data from ziprecruiters.com for populating my database. It is working with indeed but not with ziprecruiters.com class Command(BaseCommand): base_url = "https://www.ziprecruiter.com/" def generate_search_url(self, radius, search, location): url_template = self.base_url+"candidate/search?radius={}&search={}&location={}" url = url_template.format(radius, search, location) return url def request_url_from_website(self, url): response = requests.get(url, verify=False, timeout=10,) if response.status_code == 200: return response.text else: return response.reason command_class = Command() url = command_class.generate_search_url("10","python","remote") print("Generated url: ", url) request_url = command_class.request_url_from_website(url) print("Response received: ", request_url) Generated url: https://www.ziprecruiter.com/candidate/search?radius=10&search=python&location=remote Response received: Forbidden -
django filters - dictionary of filters alongside Q filtering
I have a django query which is built from URL get paramaters. These are constructed by a dictionary named 'filters': filters['published_date__year'] = year filters['published_date__week'] = week filters['source__slug'] = source queryset = Headline.objects.filter(**filters) What I'm also wanting to do is apply multiple AND filters on a field name 'tag'. filter1 = Q(tags__slug=windows) filter2 = Q(tags__slug=microsoft) Where the results would be filtered to only show headlines that have windows AND microsoft. Is it possible to apply both these Q filters, alongside the standard ones? Cheers -
What is a "slug" in Djang0?
How does slug work on this site?? This is slug test. Stack over flow slug test. When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? a=1 b=1 c=a+b print(c) -
Not getting perfect results using ngram
this is the python code , the model includes many foreign key connections.I dont know how to make accurate matching. we need accurate results for example instacart.com , this website is made with elasticsearch. class ProductSearchelastic(generics.ListAPIView): # serializer_class = ListVariantSerializer permission_classes = [AllowAny] pagination_class = SmallPagesPagination queryset=Variant.objects.all() serializer_class = NewsDocumentSerializer def get(self, request,*args,**kwargs): query=self.request.GET.get("q",None) query=query.lower() # super().get(self,request,*args,**kwargs) try: document = NewsDocument # serializer_class = NewsDocumentSerializer # fielddata=True search = NewsDocument.search() # search = search.filter('match', code=query) groupField=Item.objects.filter(group_id__name=query).first() uomField = Item.objects.filter(uom_id__name=query).first() materialField = Item.objects.filter(material_id__name=query).first() brandField = Item.objects.filter(brand_id__name=query).first() categoryField = Item.objects.filter(group_id__category_id__name=query).first() divisionField = Item.objects.filter(group_id__category_id__division_id__name=query).first() itemField = Item.objects.filter(name=query).first() variantField = False if divisionField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=divisionField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page = self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if categoryField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=categoryField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page = self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if brandField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=brandField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page = self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if materialField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=materialField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page = self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if uomField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=uomField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page =self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if groupField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=groupField.code) … -
Upload a CSV file to a DB table in Django
I am trying to develop a button that uploads a CSV that has some words in it to a DBtable through a button, the problem is that when I click the button nothing happens, I don't know if I'm missing something or I have to do it some other way. Thank you views.py: def uploadWords(request): up = request.POST.get('Upload') if up == "Upload": if request.user.is_authenticated: form = UploadFileForm() if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] usr = User.objects.get(username=request.user) if file.name.endswith(".csv"): reader = csv.reader(file) for row in reader: wt = WordsTable() wt.user = usr wt.word1 = row[0] wt.word2 = row[1] wt.word3 = row[2] wt.word4 = row[3] wt.word5 = row[4] wt.save() messages.success(request, "File uploaded successfully") return redirect("home") else: messages.info(request, "File is not csv") return redirect("home") context = {'form': form} return render(request, "base.html", context) else: return redirect("index") urls.py: urlpatterns = [ path('', views.index, name='index'), path('home/', views.home, name='home'), path('login/', views.loginView, name='login'), path('logout/', views.logoutUser, name='logout'), path('register/', views.register, name='register'), path('upload/', views.uploadWords, name='upload'), ] base.html: <div style="text-align:center;display:block;"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="upload" accept=".csv, .xlsx"> <br> <button class="button btn btn-primary" type="submit" name="up" value="Upload">Upload</button> </form> </div> -
CSRF verification failed. Request aborted error for sending request error. Unable to send api request to djoser urls
I am trying to use djoser to create user. So I am using vscode thunder client to do send the api request. However even after writing the url correctly along with the trailing slash I am still getting the below error Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. This is how I have configured the settings and the urls urls.py urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE' : True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL' : True, 'SET_USERNAME_RETYPE':True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL':'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL':'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS':{ 'user_create': 'account.serializers.UserCreateSerializer', 'user': 'account.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } Please suggest what should I do. -
Which one to use [closed]
I am creating a enterprise web application, I want it to be scalable, super fast, secure. I want to do it with django(python), spring boot(Java), asp.net(c#), Can someone tell me which one to use with my above requirements -
I want to get e-mail authentication
An authentication number function that generates eight random characters was implemented. i inputted username, and mail. because i want to write searching password html and request it at view with Ajax. When I enter my username and email, I want the authentication number to be sent to the email. At the same time, the code created in ajax should show the authentication number window. but, it happened nothing. what should i do...? help me! #html <body> {% block content %} <form method="get" enctype="multipart/form-data"> {% csrf_token %} <div class="container"> <div class="inner-box"> <div class="title"> <h1>비밀번호 찾기</h1> </div> <div class="input-box"> <div class="id"> <input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required /> </div> <div class="password"> <input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required /> </div> </div> <div class="btn"> <div class="btn-white" id="btn_white"><button type="submit">임시 비밀번호 발송</button></div> </div> <div class="loading-box"> <div id="loading"></div> </div> </div> <script> $(document).ready(function () { $('#find_pw').click(function () { $('#loading').replaceWith('<div id="loading_end" class="loading"></div>') var name = $("#pw_form_name").val(); var email = $("#pw_form_email").val(); $.ajax({ type: "POST", url: "/users/recovery/pw/find/", dataType: "json", data: { 'name': name, 'email': email, 'csrfmiddlewaretoken': '{{csrf_token}}', }, success: function (response) { // loading_end 이걸 지움 $('#loading_end').remove() alert('회원님의 이메일로 인증코드를 발송하였습니다.'); // 나는 이메일전송버튼이지 $('#btn_white').remove() $('#result_pw').replaceWith( '<hr><div class="row justify-content-md-center"><form class="form-inline" … -
Ordering alphabetically words and numbers in django
I have a queryset to be ordered alphabetically. I have this series of names such as: Mission 1, Mission 2 etc. My problem is that, once the database has more than 9 entries, the sorting works like that: Mission 1, Mission 11, Mission 2, Mission 3 etc. I tried a query like: Mission.objects.all().order_by('name') but the problem is still there. I need to have an order like --> Mission 1, Mission 2 .... Mission 9, Mission 10, Mission 11 etc. -
Controlling access to fake model in Django admin
I have the below code in admin.py where it creates models. However, this model is available to anyone in the system how can i control access to this model like any other model class BalaceForm(admin.ModelAdmin): def has_add_permission(*args, **kwargs): return False def has_change_permission(*args, **kwargs): return True def has_delete_permission(*args, **kwargs): return False def changelist_view(self, request): context = {'title': 'My Custom AdminForm'} if request.method == 'POST': form = CustomerProfilesForm(request.POST) if form.is_valid(): # Do your magic with the completed form data. # Let the user know that form was submitted. messages.success(request, 'Congrats, form submitted!') return HttpResponseRedirect('') else: messages.error( request, 'Please correct the error below' ) else: form = CustomerProfilesForm() context['form'] = form return render(request, 'admin/change_form.html', context) class AccountStats(object): class _meta: app_label = 'onboardapi' # This is the app that the form will exist under model_name = 'account-stats' # This is what will be used in the link url verbose_name_plural = 'Account summary' # This is the name used in the link text object_name = 'ObjectName' app_config = "" swapped = False abstract = False admin.site.register([AccountStatsAll],BalaceForm) -
How to get image url directly in django queryset
I have a filefield where images are present, class MyModel(models.Model): display_picture = models.FileField(blank=True, null=True) # #In Use this field is in use so I can not make any model changes. Now this model is connected to another model PriceList. Now previously I was making two db query with one to MyModel and another to PriceList. But right now as they are connected, i want to do this in a single query. so my query looks something like this ( I am accessing the MyModel through PriceList so I am making a query over PriceList, as they are connected through a inf field ) all_info_with_price_list.values('inf__display_picture', # I can do this 'inf__display_picture__url' # but not this ) How can I get the url in the query itself? just doing inf__display_picture gives me the complete filename. -
ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none)--
i try to deploy my application on heroku while the process going on i got a error the error is ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none) ERROR: No matching distribution found for apturl==0.5.2 ! Push rejected, failed to compile Python app. ! Push failed -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the buildpack default: python-3.10.4 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.10.4 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing SQLite3 -----> Installing requirements with pip ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from versions: none) ERROR: No matching distribution found for apturl==0.5.2 ! Push rejected, failed to compile Python app. ! Push failed plese this is my first app deployment please help how to slove it -
Is it possible get two fields from parent model to one child model using foreign key?
consider the below models, class Country_City(models.Model): country_name = models.CharField(max_length=200) city_name = models.CharField(max_length=200) class Register_user(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE,related_name='country', null=True) city = models.ForeignKey(Country_City,on_delete=models.CASCADE,related_name='city',null=True) is it a right way to use? I want to get two fields from parent model to child model -
Write a program to help the manager to find out the employee of the week [closed]
There is a family consisting of a husband-wife from Stone Age. Every day, the husband goes fishing in the sea and brings a certain number of fishes for food at the end of the day. The mood of the wife i.e.to be happy or sad depends on the number of fishes' husband brings back home. Everyday wife updates record of 'max' and 'min' fishes husband caught. She gets happy only when the husband brings more fishes than 'max' of the all the previous day and gets sad when he brings fewer fishes than 'min' of the all previous day. Write a program to predict the overall happiness of the wife with her husband. Create your own logic to define the "overall" happiness and clearly state your assumptions. Sample Input: 9 10 5 20 20 4 5 2 25 1 Sample Output: You can show output in your own way. But output should represent Happiness. It may be in percentage or count of happiness and sadness. Explanation: As the husband caught less fish than his all past fishing records for 4 days and caught record- breaking fish for 2 days. Hence 4 - 2 = 2 is overall happiness (difference of … -
What is the best approach to use cache in Django?
I have a GET and POST request in a Django APIView. from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status class DemoView(APIView): def get(self, request): user_id = request.query_params.get('user_id', None) num = MyModel.objects.get(id=user_id).num for i in range(num): num = num*i + 1. # In real work, much more complicated. return Response({'success': True, 'square':num}, status=status.HTTP_200_OK) def post(self, request): user_id = request.data.get('user_id', None) num = request.data.get('num', None) num_from_my_model = MyModel.objects.get(id=user_id).num if num == num_from_my_model: MyModel.objects.filter(id=user_id).update(num=num) return Response({'success': True}, status=status.HTTP_200_OK) The problem is in my real work, GET method may need a long time(about 10 seconds) to finish. Here is how I do it: (1) First of all, I create a database MyCache to see if num has changed in POST method. (2) If changed, MyCache will turn the cache_changed parameter to True(default False). (3) In GET method, I will check if cache_changed is True. If True, I will save result into cache. If False, I will get result from cache. from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.core.cache import cache class DemoView(APIView): @method_decorator(cache_page(60)) def get(self, request): user_id = request.query_params.get('user_id', None) cache_changed = MyCache.objects.get(id=user_id).cache_changed if cache_changed: num … -
How i can handle django nested serializer with django sub nested model
I want to find a more convenient way to handle the Django nested serializer with Django sub-nested models. I have create these two model with override function get_attribute. It's work fine for me but I'm, looking for more convential way to handle this. Two serilizers `class ProductSerializer(serializers.ModelSerializer): def get_attribute(self, instance): if isinstance(instance, Invoice): instance = instance.invoiceitems.all().first().price return super().get_attribute(instance) class Meta: model = Product class InvoiceSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Invoice ` from Invoice model i can access Product by reverse ORM method like i use in get_attribute overirde function. e.g: invoice_object.invoiceitems.all().first().price. For now it's working fine for me. But looking for more conventional way. Thank you in advance. -
I Can't Create a Virtual environment For Django
I wanted to create a Virtual Environment for My Django Project But whenever i tried to install pipenv it doesn't work. Please I want to install and create a Virtual environment. -
dateutil.parser parsing the time problem, unable to get the correct time
Using celery to execute tasks asynchronously, the time of the text needs to be parsed in the task. Normally, an error will be reported in the try process during parsing, and then the correct time will be obtained by executing the content of except But the local running process is normal, but the online is wrong, the content under except is not executed online, and the wrong time is obtained. # environment python3.8 ubuntu14 python-dateutil = ">=2.5.2" # imported package from dateutil.parser import parse # parsing time def parse_datetime(msg): try: dt = parse(msg, fuzzy=True) print("dt: ", dt) return dt.strftime('%Y-%m-%d %H:%M:%s') except Exception as e: print(e) ... return time_.strftime('%Y-%m-%d %H:%M:%S') # result of execution time_ = parse_datetime(msg="下午5点53") # dt print result dt :2053-05-25 00:00:00 # type:<class 'datetime.datetime'> # The result is normally an error when formatting, but the online environment does not report an error, and the result is directly obtained The result of local parsing is normal:local run result The online running result is wrong, the code content below the except is not executed, and the wrong result is directly obtained:Online Environmental Results The result of the local python environment test is also wrong:local python -
Django ImageField is not being updated while submiting a form
Issue describrion I have a model which describes a UserProfile and a dedicated form to allow user to update the model. Except photo(ImageField), everything is working fine. Issue with photo field is that the image is not being changed at all with EditProfileForm. In other words I have same image attached to this field before and after form submition, the photo is pointing to the same picture, and nothing new was uploaded to the server. It is worth to be noted that photo field is working through the form from admin panel. No issues with other fields related to UserProfile and User: all of them can be updated, and the update is saved in database. Environment details For a time being I am using Django in version 4.0.3 running with DEBUG=True and build in development server. Code ### Models def get_image_save_path( instance, filename:str ) -> str: save_dir = instance.__class__.__name__ file_name = uuid.uuid4().hex file_extension = pathlib.Path(filename).suffix return f"{save_dir}/{file_name}{file_extension}".lower() def validate_image_size(image): if not image: raise ValidationError("No image found") if image.size > 512*1024: raise ValidationError("Max size is 512kb") class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile', primary_key=True) photo = models.ImageField(upload_to=get_image_save_path, verbose_name="Photo", validators=[validate_image_size], default="userprofile/default_photo.jpg", null=False, blank=False) bio = models.TextField(default='', blank=True) def __str__(self): return f"{self.user.username}" @receiver(post_save, … -
Need to generate a client and project code for a client and project in django rest framework
models.py class Client(models.Model): client_name=models.CharField(max_length=30,default=None) client_code = models.CharField(max_length=3, default=None, null=True) company=models.CharField(max_length=200) finance_contact_email=models.EmailField(max_length=25,default=None) business_purpose=models.CharField(max_length=50,null=True,default=None) location=models.CharField(max_length=200) emergency_contact=models.CharField(max_length=200,null=True,default=None) website=models.URLField(max_length=200,null=True) comments=models.TextField(max_length=300,null=True, blank=True) start_Date = models.DateTimeField(max_length=10,null=True) end_Date=models.DateField(max_length=10,null=True) class Meta: db_table ='Client' def __str__(self): return '{}'.format(self.client_name) #Project model class Project(models.Model): project_code = models.CharField(primary_key=False, editable=False, max_length=10,default=None,null=True) #client_project_code = models.CharField(primary_key=False, editable=False, max_length=10,default=None,null=True) project_name = models.CharField(max_length=30,unique=True,default=None) client_code = models.ForeignKey(Client,on_delete=CASCADE,related_name="Client5",default=None, null=True) # need to get the client code instead of name but the name should be returned in client model client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) user=models.ManyToManyField(User,related_name='users',default=None) description=models.TextField() type=models.TextField() #dropdown start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) technical_contact_name = models.CharField(max_length=30) email=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) delivery_head_contact_name=models.CharField(max_length=30) class Meta: db_table ='Project' def save(self, **kwargs): if not self.id: max = Project.objects.aggregate(id_max=Max('project_code'))['id_max'] self.project_code = "{}{:03d}".format('', max if max is not None else 1) super().save(*kwargs) def __str__(self): return '{}'.format(str(self.client_code), str(self.project_code)) As per the above code I created a client code in client model and I need to combine the client code plus the project code which is auto generated in the project code field itself or in a new field. for ex: client code: ICN and project code: ICN001. And one main thing is i want the client name to be returned in the client model and i need to link the client code from the client model to the project, I was … -
(1062, "Duplicate entry '' for key 'email'") and (1062, "Duplicate entry '' for key 'phone'") in Django
I am trying to implement Sign Up page in Django using User models. In HTML page, there is an input field for email or phone number. The value I got from this field is assigned to username in Django User model and if the entered value is email, then the value is assigned to email in the User model. Otherwise value assigned to the phone in the User model. When I run the server, user can enter his details with email once. For the second time onwards, I got an error like this: IntegrityError at /Accounts/CandidateRegister/ (1062, "Duplicate entry '' for key 'phone'") Request Method: POST Request URL: http://127.0.0.1:8000/Accounts/CandidateRegister/ Django Version: 4.0.2 Exception Type: IntegrityError Exception Value: (1062, "Duplicate entry '' for key 'phone'") Exception Location: C:\job\venv\lib\site-packages\MySQLdb\connections.py, line 254, in query Python Executable: C:\job\venv\Scripts\python.exe Python Version: 3.9.7 Python Path: ['C:\\job\\jobsite', 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\job\\venv', 'C:\\job\\venv\\lib\\site-packages'] Similarly, when a user enter with his phone number, their details will saved to database once. After that I got an error like this: IntegrityError at /Accounts/CandidateRegister/ (1062, "Duplicate entry '' for key 'email'") Request Method: POST Request URL: http://127.0.0.1:8000/Accounts/CandidateRegister/ Django Version: 4.0.2 Exception Type: IntegrityError Exception Value: (1062, "Duplicate entry '' for key … -
Django Submitting two forms depending on each other with single submit button
I'm building a django app for managing orders. I have divided the orders management into two separated tables as follows: Order: Fields include customer (Foreign Key), order_date, total_order_value and order_status. OrderLine: Fields include item (Foreign Key), quantity, discount, total, order_id (Foreign Key). I am trying to do the template for the order page such as below. <div class="row mb-2 mt-2" style="text-align: center;"> <div class="col-2"> <input type=button value="Back" class="btn btn-secondary" onClick="javascript:history.go(-1);"> </div> <div class="col-9"></div> </div> <form method="POST" action="" enctype="multipart/form-data" id= "test"> {% csrf_token %} <form id="order" action="" method="POST" enctype="multipart/form-data"></form> <form id="orderLine" action="" method="POST" enctype="multipart/form-data"></form> <div class="card"> <div class="card-header" style="text-align: center;"><h1> Order Details </h1></div> <div class="card-body"> <div class="card-text"> <div class="row"> <div class="col-md-6"> <label for="id" class="form-label">Order ID</label> <input type="text" class="form-control" id="id" value="{{order.id}}" readonly> </div> <div class="col-6"> <label for="order_date" class="form-label">Order Date</label> {{orderForm.order_date}} </div> <div class="col-6"> <label for="customer" class="form-label">Customer Name</label> {{orderForm.customer}} </div> <div class="col-6"> <label for="status" class="form-label">Order Status</label> {{orderForm.status}} </div> </div> </div> </div> </div> <div class="row"> <br> </div> <div class="card"> <div class="card-body"> <div class="card-text"> <table class="table table-hover"> <thead> <tr> <th scope="col">Item</th> <th scope="col">Unit Price</th> <th scope="col">Quantity</th> <th scope="col">Discount</th> <th scope="col">Total</th> </tr> </thead> {{ orderLineForm.management_form }} <tbody> {% for orderLine in orderLineForm %} <tr class="orderline"> <th>{{orderLine.item}}</th> <td>0</td> <td>{{orderLine.qty}}</td> <td class="omr" id="disc">{{orderLine.disc}}</td> <td class="omr" id="total">{{orderLine.total_price}}</td> </tr> {% … -
Put the user name in change_reason when deleting with SafeDeleteModel
I am using django-simple-history and SafeDeleteModel I override the save()and store the updater name in _change_reason. then When deleting, I want to put the deleter name in _change_reason However it doesn't works. How can I make it? class BaseModel(AuditableModel, SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE objects = DeletedInvisiableManager() class Meta: abstract = True def save(self, operator: str = None, **kwargs): self._change_reason = operator return super().save(**kwargs) def delete(self,operator: str = None,**kwargs): self._change_reason = operator return super().delete(**kwargs) -
Show particular records at the bottom in webpage
I have drf website where i am showing the records of some sought on my website i have 4 different type of statuses on my webpage for records how do i show a particular status records related to the records at the bottom. class MyListView(APIView):