Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can exculde the data in Django
I am trying to exclude that orders which in my orderRequest table, but it show only that orders which is in orderRequest table and exclude the others.Function get the right id's of orders but it not exclude that orders. It exclude the other orders and show that orders which already in orderRequest table View.py class OrderProduct_View(TemplateView): template_name = 'purchase/orderProduct.html' def get(self, request, *args, **kwargs): allOrder = OrderProduct.objects.all() allOrd = Order.objects.all() categories = Category.objects.all() categoryId = self.request.GET.get('SelectCategory') product = Product.objects.filter(category_id=categoryId) def filter_order(order): try: orderReq = order.orderRequest return orderReq except: return True filteredOrders = list(filter(filter_order, allOrd)) args = {'categories': categories, 'product': product, 'filteredOrders': filteredOrders} return render(request, self.template_name, args) Model.py class Order(models.Model): orderProduct = models.ForeignKey(OrderProduct, on_delete=models.CASCADE) created_by = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) destination = models.CharField(max_length=30) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) shipping_cost = models.IntegerField() class OrderRequest(models.Model): order_status = models.CharField(max_length=10) order = models.OneToOneField(Order, related_name='orderRequest', on_delete=models.CASCADE) HTML {% for allOrders in filteredOrders%} {{ allOrders.orderProduct.id }} {{ allOrders.orderProduct.product.name }} {{ allOrders.orderProduct.quantity }} <button><a href="{% url 'allVendor' %}?product_id={{ allOrders.orderProduct.product.id }}&orderProducts_id={{ allOrders.orderProduct.id }}">Place Order</a></button> {% endfor %} -
Wanted to eliminate the repetition in the classes created to reduce duplication
Can some one help me on how to eliminate repetition to reduce duplication score on the below classes created in the code. I needed to reduce the code to improve the coding standards no idea on how to go about it please someone help me. Wanted to eliminate the repetition in the classes created to reduce duplication class SubmissionFieldsSerializer(serializers.ModelSerializer): class Meta: model = submissionfields fields = '__all__' def update(self, instance, validated_data): for key, value in validated_data.items(): if hasattr(instance, key): if key == "email_embedd": # special case instance.email_embedd = json.dumps(value) else: setattr(instance, key, value) # instance.ef_underwriter_decision = validated_data.get('ef_underwriter_decision', # instance.ef_underwriter_decision) # instance.ef_feedback = validated_data.get('ef_feedback', instance.ef_feedback) # NBI USE CASE if instance.ef_underwriter_decision == configur.get('decisions', 'non_binding_indication'): # enquiry Log dict_obj = temp_dict() # Update Submission table based on underwriter decision submission.objects.filter(email_id=instance.email_id).update(email_status='active') submission.objects.filter(email_id=instance.email_id).update( email_uwriter_decision=instance.ef_underwriter_decision) submission.objects.filter(email_id=instance.email_id).update( email_today_mail=configur.get('mailstatus', 'nbi_mail_type')) instance.email_today_mail = configur.get('mailstatus', 'nbi_mail_type') # setting email_today maio to 0 for submission fields # CR7.1 Changes (FROM COMPLETED TAB TO PROCESSED TAB) submission.objects.filter(email_id=instance.email_id).update( email_deleted=configur.get('mailstatus', 'nbi_mail_type')) temp_email_table = submission.objects.filter(email_id=instance.email_id).values( 'email_id', 'enquiry_id', 'email_sender', 'email_subject', 'email_broker', 'email_outlook_date', 'email_today_mail', 'email_assigned_user', 'email_deleted') for today in temp_email_table: for t in today: dict_obj.add(t, today[t]) if len(validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) == 0: dict_obj.add('ef_insured_name', not_avbl) else: dict_obj.add('ef_insured_name', validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) == 0: dict_obj.add('ef_obligor_name', not_avbl) else: dict_obj.add('ef_obligor_name', … -
Deadlock with concurrent Celery workers in Django
I have dozens of concurrent Celery workers creating, updating, and deleting data from various models in my Django application. I'm running into the following error: deadlock detected DETAIL: Process 3285070 waits for ShareLock on transaction 559341801; blocked by process 3285058. Process 3285058 waits for ShareLock on transaction 559341803; blocked by process 3285070. HINT: See server log for query details. And these are the blocks of code where it's throwing the error: with transaction.atomic(): for score in list_of_scores_to_update: score.save() time_delta = timezone.now() - timezone.timedelta(minutes=2) with transaction.atomic(): Score.objects.select_for_update(of=('self'), skip_locked=True).filter(checked_date__lte=time_delta).delete() How can I prevent these deadlocks by acquiring a write lock on all of the rows prior to updating them? -
post save signal only when update called
hello i have two models and a post_save signal, but my signal only when object is updated is work and when i create a new object it not work my code : class Attendance(models.Model): classroom = models.ForeignKey('Class', on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE) is_present = models.BooleanField(default=False) present_time = models.DateTimeField(null=True, blank=True) def __str__(self): return self.student.username class Class(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) students = models.ManyToManyField(User) quantity = models.PositiveSmallIntegerField() start_time = models.DateTimeField() end_time = models.DateTimeField() class Meta: unique_together = ['quantity', 'course'] def __str__(self): return f'{self.quantity} / {self.course}' @receiver(post_save, sender=Class) def create_attendance(sender, instance, **kwargs): for student in instance.students.all(): try: Attendance.objects.get(classroom=instance, student=student) except Attendance.DoesNotExist: Attendance.objects.create(classroom=instance, student=student) -
sessions in django showing None
I have to use variable defined in a function in views.py in another function. For that I am making a session but when I use it in another function it is showing value as None. Views.py def foo(request): mySession = request.session.get('mySession') color = "blue" request.session['mySession'] = color def anotherfoo(request): myColor = request.session.get('mySesssion') print(myColor) as I print it always shows `"None" rather it should print "blue" -
how to use angular 12 as front end with django rest framework as backend? I want to deploy it on heroku. I am using virtual environment
I want to create search api and use Django rest framework as backend and Angular as frontend. I havent tried anything yet I am beginner in both technologies. I know how to setup angular and django separately but dont know how to use them together -
How diploy experta rule based system in django
i am using experta (based on pyknow) to make some rules, but i wanna display the result in an html file with django, i have this rules: @Rule( Saber11(math=P(lambda x: x > 80), writ=P(lambda x: x > 80), nat=P(lambda x: x > 80), lang=P(lambda x: x > 80), soc=P(lambda x: x > 80))) def rule1(self): print("Study the carrer of your highest preference") @Rule( Saber11(math=P(lambda x: x > 80), writ=P(lambda x: x <= 80), nat=P(lambda x: x > 80), lang=P(lambda x: x <= 80), soc=P(lambda x: x <= 80))) def rule2(self): print("Study Engineering or Science") but i dont know how return the result, i try sometime like: @Rule( Saber11(math=P(lambda x: x > 80), writ=P(lambda x: x > 80), nat=P(lambda x: x > 80), lang=P(lambda x: x > 80), soc=P(lambda x: x > 80))) def rule1(self): return "Study the carrer of your highest preference" but did not work, the KnowledgeEngine.run() method (it is charge of run all rules) return None, i read the documentation found here but all the examples and docs just print in console. here is the method in django where i run the rules and try to display: engine = rules.ChooseProfession() engine.reset() saber = rules.Saber11(math=sab.cleaned_data['math'], writ=sab.cleaned_data['writ'], nat=sab.cleaned_data['nat'], lang=sab.cleaned_data['lang'], soc=sab.cleaned_data['soc']) … -
zmq cannot send message from broker to frontend
I am dealing with this issue for a few days now but I am sure the solution has to be relatively simple. The structure of my app is based on the "Figure 17 - Request-Reply Broker" from this link. More in detail, my frontend side, which is running with django, looks like that: context, client_socket, port = create_client_socket() client_socket.connect("tcp://localhost:%s" % 5559) to_send = list() # this is the request that it will be sent to the broker to_send = ..... # setting what the request is # sending the request client_socket.send(json.dumps(to_send).encode('utf-8')) # send message # waiting for response results = client_socket.recv(1024).decode() # receive response client_socket.close() context.term() if results: # working with the results received from the broker ............... return render(request, 'front_app/my.html', {'records': results}) My broker looks like that : context = zmq.Context() frontend = context.socket(zmq.ROUTER) frontend.bind("tcp://*:5559") # The port that the clients should be using for communication backend_sockets = list() for i in range(number_of_server_nodes): # currently there are 2 server nodes port = range(5550, 5558, 2)[i] backend = context.socket(zmq.DEALER) backend.bind("tcp://*:{}".format(port)) backend_sockets.append(backend) # Initialize poll set poller = zmq.Poller() poller.register(frontend, zmq.POLLIN) # poller.register(backend1, zmq.POLLIN) # poller.register(backend2, zmq.POLLIN) for back_sock in backend_sockets: poller.register(back_sock, zmq.POLLIN) # Switch messages between sockets while True: socks … -
Add "Date field" in UserCreationForm in Django and connect it to model
I am trying to add a date field in the form.py file and save the data to the User model. After doing the below works, the date field is not showing up. I am stuck on is how to process the form data and save it within the view. So I think my form is not working. I am stuck and cannot think of the right code. models.py from django.db import models from django.contrib import auth # Create your models here. class User(auth.models.User, auth.models.PermissionsMixin): date = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return "@{}".format(self.username) forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms from . models import User class UserCreateForm(UserCreationForm): last_date = forms.DateField(label='Last Donated',required=True) class Meta: model = User fields = ("username", "email", "password1", "password2", "last_date") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.last_date = self.cleaned_data["last_date"] if commit: user.save() return user views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from accounts.forms import UserCreateForm # Create your views here. class SignUp(CreateView): form_class = forms.UserCreateForm form = UserCreateForm(request.POST) if form.is_valid(): user = form.save() date = form.cleaned_data.get('last_date') Profile.objects.create(user=user, date=last_date) … -
How to pass django datetime in URL
I am trying to pass django datetime in URL and I can't seem to figure how, I have only passed int or str on URl before so this is a first for me : I am trying to create this URL in my urls.py : path('reservation_process/<int:year>/<int:month>/<int:day>/<int:hour>/<int:year>/<int:month>/', reservation_views.add_reservation,name= "reservation_process") This is the view that it invokes : def add_reservation(request,room,res_title,res_from,res_to,employee): context = {} has_reserved = Reservation.objects.filter(reservation_from=res_from, reservation_to=res_to, employee_id=request.user.employee.id, room_id=room).count() context['availibility']= True context['reserved'] = True current_room_availibility=RoomAvailability.objects.get(room_id=room,available_from=res_from, available_to=res_to).availibility if current_room_availibility!="available": context['availibility']= False else : if has_reserved!=0 : context['reserved']= False else: reservation=Reservation(title=res_title,reservation_from=res_from, reservation_to=res_to, employee_id=request.user.employee.id, room_id=room) RoomAvailability.objects.filter(room_id=room, available_from=res_from, available_to=res_to)[0].update( availibility="unavailable") return render(request, 'added.html', context) And these are the models I am using: class Room(models.Model): title = models.CharField(max_length=25) def __str__(self): return self.title class RoomAvailability(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) availibility_from = models.DateTimeField() availibility_to = models.DateTimeField() availibility = models.CharField(max_length=25) def __str__(self): return f"{self.room}" so if you can help me out on how I can pass datetime in URl that would be great thank you -
how to delete row of table in SQLITE3 using Django Shell?
in practicing using sqlite3 with django, I've created a single row via the Django Shell: # Import our flight model In [1]: from flights.models import Flight # Create a new flight In [2]: f = Flight(origin="New York", destination="London", duration=415) # Instert that flight into our database In [3]: f.save() # Query for all flights stored in the database In [4]: Flight.objects.all() Out[4]: <QuerySet [<Flight: Flight object (1)>]> Now I set a variable called flights to store the query: # Create a variable called flights to store the results of a query In [7]: flights = Flight.objects.all() # Displaying all flights In [8]: flights Out[8]: <QuerySet [<Flight: 1: New York to London>]> # Isolating just the first flight In [9]: flight = flights.first() Now in models.py I've done the following: class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="departures") destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals") duration = models.IntegerField() def __str__(self): return f"{self.id}: {self.origin} to {self.destination}" After running Migrations: # Create New Migrations python manage.py makemigration # Migrate python manage.py migrate I get the following error, because I need to delete my existing flight from New York to London to support the … -
Django KeyError - How to handle
I had an app on Heroku but then I deleted my Heroku app (free edition, so it got slow of inactivity) to do improvements in the speed. But now I got one error after another. Those are "just" KeyError, so it's doable, but my solution seems to fail somehow, and I do not get it. I got this one line here: val_b = our_total[city_data[1]][i] if our_total[city_data[1]][i] is not None else 0 that causes the KeyError. I dont really get it, it gives these errors in some cities just. I find it very frustrating, as it worked before I redeployed it on a new app. Can anybody spot what I do wrong? I tried to do something like try: val_b = our_total[city_data[1]][i] if our_total[city_data[1]][i] is not None else 0 except KeyError: continue It will then not display some cities where I know there is data in my db with the cities. Refrences: views.py class InventoryStatusView(LoginRequiredMixin, View): template_name = "lager-status.html" cinnamon_form = CinnamonForm(prefix="cinnamon_form") peber_form = PeberForm(prefix="peber_form") pc_model = InventoryStatus.objects.all() product_model = Product.objects.all() order_item_model = WCOrderItem.objects.all() shipment_model = WCOrderShipment.objects.all() def get_method_title(self, shipment): city_values = dict(InventoryStatus.CITIES).values() # Get total added to each city city_sum_added = self.pc_model.values('city').annotate(Sum('cinnamon'), Sum('peber')) print(f'city_sum_added: {city_sum_added}') # … -
Django: This site can't be reached
I am new to django development and everytime I try to access my project site on my browser, I get: This site can’t be reached 127.0.0.1 refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED My Debug is set to True and the port has been added as an allowed host. Please, what should I do? -
Django Models setup
I'm getting a typeerror: init() missing 1 required positional argument: 'on_delete enter code hereclass Topic(models.Model) enter code here text=models.CharField(max_length=200) enter code here date_added=models.DateTimeField(auto_now_add=True) enter code hereclass Entry(models.Model): enter code here topic = models.ForeignKey(Topic) enter code here text = models.TextField() enter code here date_added=models.DateTimeField(auto_now_add=True) enter code here class Meta: enter code here verbose_name_plural='entries' enter code here def str(self): `enter code here' return self.text[:50] + "..." -
CORS Not Working On Apache and django app
hi i have an app that runs django on an apache server on windows server. i'm trying to fetch data from the api using axios in react but the cors blocks me with the following message: No 'Access-Control-Allow-Origin' header in the requested resource. when I runs the application without the apache it works perfectly so I believe the problem is in the apache configuration. The following apache: RewriteEngine On RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L] Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers "authorization, origin, user-token, x-requested-with, content-type" Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT" <VirtualHost *:443> .... <Directory path> Options Indexes FollowSymLinks MultiViews AllowOverride None </Directory> </VirtualHost> React sample: x = await axios.get("https://localhost/test") Django sample: def test(){ return JsonResponse(context={"test": "testing"}, safe=False) } -
How to auto insert the current user into my db when inserting records from Frontend
I have columns Month and Values on my db.Am inserting month and values from front-end to my db.I need my current user(username) also to be stored in a seperate column whenever I pass my month and values from front end. Another question is that,When my month is entered once ,I should not be able to enter the same month again..How to set validations for this?? I got stuck at this level.Can anyone help me sorting this? Html file: <html> <head> <title>FRONTEND VALUES BP</title> </head> <body> <p>BLOOD PRESSURE</p> <form action="index" method="post"> {% csrf_token %} <label>Month1:</label> <input type="text" name="JanMonth" placeholder="enter your month"></br></br> <label>Value:</label> <input type="text" name="JanValue" placeholder="enter your value"></br></br> <label>Month2:</label> <input type="text" name="FebMonth" placeholder="enter your month"></br></br> <label>Value:</label> <input type="text" name="FebValue" placeholder="enter your value"></br></br> <label>Month3:</label> <input type="text" name="MarMonth" placeholder="enter your month"></br></br> <label>Value:</label> <input type="text" name="MarValue" placeholder="enter your value"></br></br> <label>Month4:</label> <input type="text" name="AprMonth" placeholder="enter your month"></br></br> <label>Value:</label> <input type="text" name="AprValue" placeholder="enter your value"></br></br> <label>Month5:</label> <input type="text" name="MayMonth" placeholder="enter your month"></br></br> <label>Value:</label> <input type="text" name="MayValue" placeholder="enter your value"></br></br> <label>Month6:</label> <input type="text" name="JunMonth" placeholder="enter your month"></br></br> <label>Value:</label> <input type="text" name="JunValue" placeholder="enter your value"></br></br> <label>Month7:</label> <input type="text" name="JulMonth" placeholder="enter your month"></br></br> <label>Value:</label> <input type="text" name="JulValue" placeholder="enter your value"></br></br> <label>Month8:</label> <input type="text" name="AugMonth" placeholder="enter your month"></br></br> <label>Value:</label> <input … -
The problem of getting an object created thanks to TabularInline
My model A uses TabularInline, which creates objects of model A1. I want to output information about object A1 to the console when I save object A. I use the clean/save method. When I save an existing A object, it's fine, but if I create one, it outputs an error. How can I track the creation of object A1 in object A? Thank you. class A(models.Model): name = models.CharField(max_length=120) def save(self, *args, **kwargs): super().save(*args, **kwargs) print(self.a_name.all()) class A1(models.Model): description = models.CharField(max_length=120) name = models.ForeignKey(A, on_delete=models.CASCADE, related_name="a_name") -
How do you solve Import "django_filters.views" could not be resolvedPylance error
I suddenly received this error when I opened vscode: Import "django_filters.views" could not be resolvedPylance I was programming a django project about a month ago using vscode, but I didn't work on the project for about a month since I had other things to do. However, when I opened my vscode to start working on the project again, I received the above error. New edits in the code seem to be a grey color now as well. I think vscode got automatically updated while I was away, but I have no idea why this issue is occurring. I hope you guys could help me find the problem. If there is any information you need, please comment below. Thanks. -
Can't get ajax data, send with Post method to Django Views
I tried to get/catch the data which is sent from ajax as the Post method. I believe data is sent properly cause I can see the send data in the console. I think I have issues with the view. Here is my code. home.html <script> document.getElementById('postForm').addEventListener('submit',postName); function postName(e){ e.preventDefault(); var name = document.getElementById('id_name').value; var price = document.getElementById('id_price').value; var data = { 'name':name, 'price':price, } var xhr = new XMLHttpRequest(); xhr.open('POST',"{% url 'ajax-home' %}",true); xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); var myData= JSON.stringify(data); xhr.onload = function(){ console.log(myData); } xhr.send(myData); } </script> views.py def ajax_home(request): if request.method == 'POST': form = ProductForm(request.POST or None) if 'name' in request.POST: name = request.POST['name'] else: name = "stil not found" p = Product(name=name,price=100) p.save() else: form = ProductForm() products = Product.objects.all() context = { 'form':form, 'products': products} return render(request, 'myapp/home.html', context) -
Tinytag - No such file or directory
I want to get the duration of an audio file using the Tinytag library inside a django view. def someview(request): newaudio = Recordings.objects.create(audio=audio_file) audio_url = newaudio.audio.url audio_duration = TinyTag.get(sitepath+newaudio).duration I get: No such file or directory: 'http://127.0.0.1:8000/media/recordings/806316951.ogg' When I go to the link, the audio plays. Thank you for any suggestions -
How to check if user has previously authenticated in the current session in Django?
Can I know if a user was previously authenticated in the current session in Django? Quick list of expected results: User is currently logged in: return true User was logged in at once but is currently logged out: return true User had never logged in since the browser was opened: only case that returns false I'd hate to touch cookies, which is the only solution that I can come up with (still, I don't have much of an idea of how to approach the problem with cookies). Thanks in advance. -
Problem rendering template after my code has run Django
Hello I have the code below in my views.py. if result_code != 0: booking = book_room(user, room, check_in, check_out) print (booking) return render(request, 'booking/paymentcomplete.html') else: return render(request, 'booking/paymenterror.html') I believe the code is running well since print(booking) produces below results What exactly am I doing wrong because the templates don't render? -
How to exclude some fields in ModelSerializer
I have Account model. At the other side I have model Student. They Have a relationship, indeed I wanted to manage different types of users. class Account(AbstractBaseUser): class Gender(models.TextChoices): MALE = "M", "Male" FEMALE = "F", "Female" OTHER = "O", "Other" UNSET = "U", "Unset" email = models.EmailField(verbose_name="email", max_length=100, unique=True) first_name = models.CharField(verbose_name="first name", max_length=30) last_name = models.CharField(verbose_name="last name", max_length=40) gender = models.CharField(max_length=1, choices=Gender.choices, default=Gender.UNSET) date_joined = models.DateTimeField( verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return self.email @property def is_student(self): return hasattr(self, 'student') @admin.display(boolean=True) def is_student_display(self): return self.is_student def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Student: class Student(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.user.email I need to serializes Student model rather than Account model. But I need to to have field user. So I did: class StudentBaseSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ("user",) depth = 2 As you may guess, this returns all the fields, like password, is_admin, is_staff so on. How can I exclude some fields while depth=2? -
Django urls redirect - strange behavior of site's home page. One 200 and 302 return
Earlier i had RedirectView in urls.py for home page: urls.py urlpatterns = [ path('', RedirectView.as_view(url='al_home.html'), path('al_home.html', views.home, name="home"), path('al_about.html', views.about, name="about"), path('search_all.html', views.search_all, name="doorway"), path('<slug:cat_>/', views.page_Category_Main, name='cat'), path('<slug:cat_>/<slug:product_>', views.page_Product, name='product'), path('robots.txt', TemplateView.as_view(template_name="robots.txt", content_type="text/plain")), path('sitemap.xml', TemplateView.as_view(template_name="sitemap.xml", content_type="text/xml")), path('favicon.ico', RedirectView.as_view(url='/static/marketability/favicon.ico', permanent=True)), ] After, I CHANGED IT: urlpatterns = [ path('', views.home, name="home"), path('al_home.html', views.home, name="home"), path('al_about.html', views.about, name="about"), .... And it worked properly and on production deploy and on developer PC... For a few days. But some troubles begans on production server: It began one time work with redirect (return 302 code) and recheck to https://host/al_home.html by link to https://host or http://host/ or http://www.host/. Enother times it work properly and return 200. Developer installation - work normally http://127.0.0.1:8000/ return 200 and show home page ok, without printing al_home.html Internet Search system (Yandex.ru) every day print in report two string: '/' - was 200 OK - become 302; '/' - was 302 - become 200 OK; WebServer on deploy - Nginx. May be it adjust of Web Server? But it strange for me that error is float. -
First obj in the list is not updating in django model
I am iterating over a list of the object and saving them I created a Method for update def UpdateLeadgers(obj, leadger): l = leadger.objects.filter(id__gte=obj.id).order_by('id') print('update ', obj.total_amount) diff = obj.total_amount - l.first().total_amount print('--diff--' + str(diff)) for i in l: print(i.total_amount) print("-------") print(i.net_Balancse) i.net_Balancse += diff print("++++++++") i.save(updateProcessing=True) print(i.net_Balancse) print("_+_+_+_+_") I am Actually updating Netbalancse I call the UpdateFunction in save() method def save(self, *args, **kwargs): c = CashInHandPerson.objects.all().first() if self.id == None: if self.transaction_type == 'Credit': c.current_Balance += self.total_amount self.net_Balancse = c.current_Balance else: c.current_Balance -= self.total_amount self.net_Balancse = c.current_Balance c.save() else: up = kwargs.pop('updateProcessing', {}) if not up: UpdateLeadgers(self, CashLeadger) self.cashInHandPerson = c super(CashLeadger, self).save(*args, **kwargs) its update all value but not the first one: Suppose I have a list Like Now if I update 200 to --> 300 Then it's not updating the NetBalance of 200 Total Field Its update the below fields: Result