Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the BooleanField of a model which is True if and only one can be true at all in Django?
I have the following model which has two boolean fields. Due to my logic, they won't be both true at anytime. How can I get the field which is True in a simple straight forward way? class Vote(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote') user = models.ForeignKey(Account, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) def __str__(self): return f'Vote by {self.user}' This is how I'm doing it right now: voted_for = Vote.objects.get(poller_id=poller_id, user=request.user) is_true = voted_for.poller_choice_one_vote is_also_true = voted_for.poller_choice_two_vote if is_true: voted_for = voted_for.poller_choice_one_vote elif is_also_true: voted_for = voted_for.poller_choice_two_vote else: pass -
how to request url of that model detail views in search result
I am searching in three model and all model has different detail views and but i am unable to figure out how to tell django to locate the view acc to their model this is my view for seaching in models def search_item(request): results = [] search_item = request.GET.get("search") if search_item: q = Q(title__icontains=search_item) | Q(written_by__icontains=search_item) for model in (crypto, News, Movie): results.extend(model.objects.filter(q)) return render(request, "result.html", {"results": results}) and for that template {% for result in results %} <a class="blog-card" href=""> <div class="card col-4" style="width: 18rem;"> <img src="{{ result.title_image.url }}" class="card-img-top" width="100%" height="200px"> <div class="card-body"> <h5 class="card-title text-center" style="color:black">{{ result.title|truncatewords:7 }}</h5> <p class="card-text text-center" style="color:black">{{ result.info|truncatewords:10 }}</p> <p class="number text-center" style="color: black;"> Wriiten By:<strong> {{ result.written_by }}</strong></p> <p class="last text-center" style="color: black;"> Last update:<strong> {{ result.joined_date }}</strong></p> </div> </div> </a> {% endfor %} and all the model has different detail views, so how to do that urls.py path('crypto/<slug:title>/',views.ttt_read,name="ttt_read"), path('news/<slug:title>/',views.news_read,name="news_read"), path('movie/<slug:title>/',views.movie_read,name="movie_read"), path('penmen/search/',views.search_item,name='search') any help and suggestion will be appreciated -
Djongo/PyMongo keeps creating new DB connections for Django REST framework API requests
I'm experiencing an issue with djongo when used with Django REST framework where it initiates a new connection with my MongoDB at every request except for the very first one after starting the webserver. This means the first request to my Django API is fast (~80 ms) but all the following requests are significantly slower (~800 ms) because they all initiate a new connection. When profiling the requests I can see that pymongo\pool.py:950(_create_connection) and pymongo\pool.py:1263(connect) are present in each request except for the first one, which I assume means the first request uses the pre-initiated DB connection, but all the others have to create a new connection, hence why it's so slow. I'm also seeing huge spikes of connections in my MongoDB dashboard, there should be only 1 connection, but when I'm testing this it suddenly gets up to 50+ connections, and even when I shut down the webserver, the connections only drop by one and plenty of zombie connections remain that only die after some timeout. Here are the profiling results for the first and second request. I can't figure out if it's an issue with django, djongo, pymongo or djangorestframework. For the installation and configuration, I've followed the … -
django.db.utils.ProgrammingError: constraint already exists
so i am trying to make my custom migration file to make partitions for my tables ,i have create a custom CreatePartitionedModel to do the work for me however i keep having a a db.utils.ProgrammingError saying that i have duplication in my constraints: django.db.utils.ProgrammingError: constraint "summary_result_id_d5ba54ba_fk_token_id" for relation "summary" already exists My custom CreateModel : class CreatePartitionedModel(CreateModel): def __init__(self, name, fields, partition_sql='LIST(lang)', **kwargs): self.partition_sql = partition_sql super().__init__(name, fields, **kwargs) def database_forwards(self, app_label, schema_editor, from_state, to_state): collector = type(schema_editor)( schema_editor.connection, collect_sql=True, atomic=False ) with collector: super().database_forwards( app_label, collector, from_state, to_state ) collected_sql = collector.collected_sql schema_editor.deferred_sql.extend( collector.deferred_sql ) model = to_state.apps.get_model(app_label, self.name) create_table = 'CREATE TABLE %s' % schema_editor.quote_name( model._meta.db_table ) all_langs = ['en','fr','ar','es','da','de','it','ja','nl','pl','pt','ru','zh'] langs_partition = "" for sql in collected_sql: if str(sql).startswith(create_table): for lang in all_langs: langs_partition+=f"create table {self.options['db_table']}_{lang} partition of {self.options['db_table']} for values in ('{lang}');" primary_keys = ",primary key (id ,lang ),unique ( lang, id))" sql = sql.replace("serial NOT NULL PRIMARY KEY","serial NOT NULL") sql = '%s %s PARTITION BY %s; %s' % (sql.rstrip(');'), primary_keys,self.partition_sql, langs_partition) schema_editor.execute(sql) and this is my migration file and the table that i have problems in: CreatePartitionedModel( name='Summary', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('base', models.CharField(max_length=255)), ('pattern', models.CharField(max_length=255)), ('lang', models.CharField(max_length=255)), ('frequency', models.IntegerField()), ('relevance', models.FloatField(null=True)), ('count', … -
How to search for substring in array of JSON Field?
I'm using a JSONField provided by Django and I store this type of data in that field: [ { "number": 1, "text": "This text is about dogs" }, { "number": 2, "text": "Only cats in this text here" }, { "number": 3, "text": "However, this text does also contain dogs" }, ] What I'm trying to achieve is some sort of substring match - ie, if a person searches for the string "dog", the result should return something like: { "number": 1, "text": "This text is about dogs" }, { "number": 3, "text": "However, this text does also contain dogs" }, Looking at the Django docs, it seems possible to query for JSON fields, as such Model.objects.filter(field__text__contains='dogs') However, contains only works for single dictionary values, not when there is an array of dictionaries. Any tips? Either through the Django ORM or through Postgres straight up. -
How To Fix TemplateDoesNotExist at /agents/ agents/agents_list.html, leads/agent_list.html
How To Fix I Saw A Directory and everything is right but i still get same error TemplateDoesNotExist at /agents/ agents/agents_list.html, leads/agent_list.html Code class AgentListView(LoginRequiredMixin, generic.ListView): template_name = "agents/agents_list.html" def get_queryset(self): return Agent.objects.all() -
Markdown2 text rendering as a string using Python and Django
I'm working on a project that takes in a markdown page and converts it into HTML before inserting it into the correct document. This is the code I'm running Python def markdown(request, entry): pathOfFile = "entries/" + entry + ".md" return render(request, "encyclopedia/entry.html", { "html_markdown": markdown2.markdown_path(pathOfFile) }) HTML {% block body %} <div> {{ html_markdown }} </div> {% endblock %} And this is what is returning on the web page <h1>CSS</h1> <p>CSS is a language that can be used to add style to an <a href="/wiki/HTML">HTML</a> page.</p> When I inspect the source of the page the HTML is encased in quotes. Is the problem that my html_markdown variable is being read as a string? What steps can I take to get the HTML to render properly? Thanks in advance for your help! -
Getting following error when trying to use replica database: "django.db.utils.ProgrammingError: relation "vt_ecommerce_orderitem" does not exist"
When I am trying to run "OrderItem.objects.using("replica").all()" or any query on "replica" database, I am getting that error. Please help me out! When I am trying to run "OrderItem.objects.using("replica").all()" or any query on "replica" database, I am getting "*** django.db.utils.ProgrammingError: relation "vt_ecommerce_orderitem" does not exist" error. Please help me out! settings is as following: DATABASES = { "default": { "ENGINE": "django_tenants.postgresql_backend", "NAME": os.environ.get("POSTGRES_DB", "starling"), "USER": os.environ.get("POSTGRES_USER", "vesatogo"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD", "vbhv3301"), "HOST": os.environ.get("POSTGRES_HOST", "db") if VT_ENV in PROD_ENV_TAGS else "localhost", "PORT": os.environ.get("POSTGRES_PORT", 5432), "TEST": {"NAME": os.environ.get("POSTGRES_TEST_DB", "starling_test")}, }, "replica": { "ENGINE": "django_tenants.postgresql_backend", "NAME": os.environ.get("POSTGRES_DB", "starling"), "USER": os.environ.get("POSTGRES_USER", "vesatogo"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD", "vbhv3301"), "HOST": os.environ.get("POSTGRES_HOST", "db") if VT_ENV in PROD_ENV_TAGS else "localhost", "PORT": os.environ.get("POSTGRES_PORT", 5432), "TEST": {"NAME": os.environ.get("POSTGRES_TEST_DB", "starling_test")}, } } yml file is as following: version: '3' services: db: image: mdillon/postgis container_name: sl_database ports: - "5432:5432" volumes: - db_vesatogo_starling_v1:/var/lib/postgresql/data env_file: - ./config/dev.env networks: - db_network pgadmin: image: dpage/pgadmin4:4.28 container_name: sl_admin links: - db depends_on: - db environment: PGADMIN_DEFAULT_EMAIL: admin PGADMIN_DEFAULT_PASSWORD: password ports: - "80:80" networks: - db_network redis: image: redis:latest container_name: sl_redis ports: - "6379:6379" restart: always networks: - redis_network networks: db_network: driver: bridge redis_network: driver: bridge volumes: db_vesatogo_starling_v1: static: -
Django 3x built in url template tag // dynamic urls via name pattern
Hello fellow human beings, I try to build a rather simple application and I have a struggle with handling url template tags. I looked up many different sources and coded the project 3 times new I have no idea whats the problem any suggestion is a big help. thanks C:. ├───nps │ ├───templates │ └───__pycache__ └───user ├───migrations │ └───__pycache__ ├───templates │ └───user └───__pycache__ nps/urls.py from django.contrib import admin from django.urls import path,include from django.views.generic import TemplateView #include urls from user-app urlpatterns = [ path('',TemplateView.as_view(template_name='homepage.html')), path('user/',include('user.urls')), path('admin/', admin.site.urls), ] user/urls.py from django.urls import path from . import views as user_views #define names for the specific urls urlpatterns = [ path('home/',user_views.home,name='user-home'), path('login/',user_views.loginPage,name='user-login'), path('register/',user_views.registerPage,name='user-register') ] #---------------------------------------------------------------------------------------# base layout for templates user/templates/user/base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> <title>Document</title> </head> <body> {%block main%}{%endblock main%} </body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script> </html> home.html with navlinks and url tags user/templates/user/home.html {%extends 'user/base.html'%} {%block main%} <ul class="nav justify-content-center"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Active</a> </li> <li class="nav-item"> <a class="nav-link" href="{%url'user-home'%}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{%url'user-login'%}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{%url'user-register'%}">Register</a> </li> </ul> {%endblock main%} #----------------------------------------------------------------------------------------# ERROR MESSAGE TemplateSyntaxError at/user/home Error during template … -
Order with id=<id> didn't have expected object=<obj_name>
Sometimes my order object doesn't have an expected foreign key object. Here is my model, that represents Paypal Order(some fields are skipped): class Order(models.Model): order_id = models.CharField(...) # naive polymorphism object1 = models.ForeignKey(...) object2 = models.ForeignKey(...) object3 = models.ForeignKey(...) The logic is following: The user can create one of the objects (object1, object2, objects3) and then he will need to pay for it. Order can have only one object assigned to it. User creates an object User creates an order instance with object id. User pays a specified amount of money in the order. System waits for an API call from PayPal (webhook). Webhook logic is following: Fetch order instance Fetch object by a sequence of ifs: if order.object1: handle_object1(order.object1) if order.object2: handle_object1(order.object2) if order.object3: handle_object1(order.object3) else: raise Exception() At this point, I can get an exception, that the expected object doesn't exist. Later when I try to fetch the expected object from DB - it is there. It's weird, because it takes some time to PayPal to make a request. The expected object must exist at this time. Also it's impossible to create an Order instance with not valid object id. -
Bad Gateway in Django Production Server
The below configuration were working fine before. I pulled my latest code for django project which was not reflecting. So I wanted to refresh it. I killed gunicorn by killall gunicorn Now it is giving bad gateway. How do I resolve it? I tried restarting nginx, uwsgi sudo systemctl restart nginx sudo service uwsgi restart Created a file called my_project in /etc/nginx/sites-enabled server { listen 80; server_name my_ip_address; # customize with your domain name location /static/ { # static files alias /home/ubuntu/static/; # ending slash is required } location /media/ { # media files, uploaded by users alias /home/ubuntu/media/; # ending slash is required } location / { proxy_pass http://127.0.0.1:8000; } } linked it using cd /etc/nginx/sites-available sudo ln -l /etc/nginx/sites-available/project_name In /home/ubuntu/conf/ created a file called gunicorn_config.py command = '/home/ubuntu/DJango/env/bin/gunicorn' pythonpath = '/home/ubuntu/DJango/my_project' bind = 'IP_address:8000' workers = 3 -
The authorization server is sending back unauthorized error no matter what
I am trying to authenticate users from another 3rd party application. The authorization server uses oauth2. All my client credentials are correct. But when implementing get a request to obtain code from the authorization server. According to the documentation of the authorization server, I should encode state to bas64. Below is my view def one_id_login(request): state = "{'method':'IDPW'}"; state = base64.b64encode(state.encode('ascii')) state = state.decode() scope = 'e_mehmon' redirect_url = 'http://127.0.0.1:8000/home/o/redirect/' return render(request, 'client/login.html', {'url': auth_one_id_url, 'state': state, 'scope': scope, 'redirect': redirect_url}) And this is HTML <body> <form name="OAuthForm" action="{{ url }}" method="get"> <input type="hidden" name="response_type" value="one_code" /> <input type="hidden" name="client_id" value={{client_id}} /> <input type="hidden" name="redirect_uri" value={{ redirect }} /> <input type="hidden" name="scope" value={{e_scope}} /> <input type="hidden" name="state" value={{ state }} /> </form> <script type="text/javascript"> document.OAuthForm.submit(); </script> </body> But always I am receiving the following error message {'error': 'unauthorized_client', 'error_description': 'Unknown Client'} -
get the values of the created object in the same view in django rest framework
How can i get values of the created object in the same view ? in the same view after creating the instance i need to send an email to the user, using the email entered by him and the code gerated randomly. Models.py def generate_activation_code(): return int(''.join([str(random.randint(0,10)) for _ in range(6)])) class Email_for_Verification(models.Model): email = models.EmailField( max_length=100, verbose_name='email', unique=True) code = models.CharField(max_length=100, default=generate_activation_code) Views.py class EmailForVerificationView(CreateAPIView): queryset = models.Email_for_Verification.objects.all() serializer_class = EmailForVerificationSerializer def create(self, request): data = request.data email_for_verification = self.create(email=data.email) send_mail( 'Here is the code of verification', email_for_verification.get['code'], 'info@ivan-online.ru', [email_for_verification.get['email']], fail_silently=True, ) i'm facing the following error: 'QueryDict' object has no attribute 'email' -
Django Web App Help! How to Add Attendance to Requested Students
I have my Django web app nearly complete but am stuck on one final component. Background of the app: teachers will be able to request students for tutoring. Once the tutoring period expires, teachers can then enter attendance for those students. What is the best way to approach this? Below are my models, views and forms. Thank you so much in advance! MODELS from django import forms from django.db import models from django.forms import ModelForm from django import forms # Create your models here. class Student(models.Model): first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) AdvisoryRoom = models.CharField(max_length=200, null=True) # def __str__(self): return self.last_name + ", " + self.first_name class Meta: ordering = ['last_name'] class AdvisoryTeacher(models.Model): first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) room_number = models.CharField(max_length=200, null=True) phone_number = models.CharField(max_length=200, null=True) def __str__(self): return self.last_name + ", " + self.first_name class Meta: ordering = ['last_name'] class Teacher(models.Model): first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) room_number = models.CharField(max_length=200, null=True) phone_number = models.CharField(max_length=200, null=True) def __str__(self): return "" + str(self.last_name) + ", " + str(self.first_name) class Meta: ordering = ['last_name'] class RequestAStudent(models.Model): MARK =( ('Present', 'Present'), ('Late', 'Late'), ('Absent', 'Absent'), ) PERIODS=( ('Academic Network 1', 'Academic Networking 1'), ('Academic Network 2', … -
django partial search issue
This sample text that needs to be searched State Model { "region": "National Capital Territory of Delhi", "country": "in" }, { "region": "Union Territory of Chandigarh", "country": "in" }, I have two models on the server, First is a country model in which user selects the country they reside in then from that state is filter and is displayed. So now if they type Chandigarh when am using they query state = loginModels.State.objects.filter(country=country_code.lower()).filter(region__icontains=state).get() It automatically selects -> Union Territory of Chandigarh BUT, Now if the user types NCT of Delhi the above query fails I tried Q method too as suggested in blogs, this also FAILS. state = loginModels.State.objects.filter(country=country_code.lower()).filter(Q(region__icontains=query)).get() P.S Note In this user stands for the system, so backend system calls like NCT and above query fails in several places we don't want to hardcode places. Any kind of help will be really appreciated. -
Django Unit Test - filtered query results in the view
I am relatively new to Django and very new to writing unit tests. I'd like to ask for assistance but I'm a bit stuck with where to even begin. The app in question allows a teacher to assign multiple assignments to a student. On the student dashboard, an assignment should only be available if the start date <= today's date. The student should only see the first assignment in the list on their dashboard. I need to compose a unit test to cover this scenario: I'd like to assign multiple assignments to a student and then use the same query that is used for the student dashboard to ensure that the only assignments returned are the ones with a start date <= today's date AND that the student only sees the first assignment (with the earliest start date) in the list. Below I have posted the relevant code that is pulling what displays on the student dashboard. Please let me know if additional code is needed to help me get started with this. Thanks very much for any help you can offer! from my home/views.py file @login_required def index(request): user_type = request.user.type.text if user_type == 'Student': """ Only return the … -
Opening a connection to an additional database specifying cursor_factory
I've defined a named database in settings.py::DATABASES, called db. I want to open a connection to that database and get a NamedTupleCursor instead of the default psycopg2 cursor. Ny naive attempt was to do: from psycopg2.extras import NamedTupleCursor db = connections["db"].connection with db.cursor(cursor_factory=NamedTupleCursor) as cursor: ... But .connection is None until I explicitly connect to the database. I can manually connect to the database, then access the underlying connection, like this: db = connections["db"] if not db.connection: db.connect() connection = db.connection with connection.cursor(cursor_factory=NamedTupleCursor) as cursor: ... But this all feels very ad-hoc and un-Djangoesque. Also, I'm not sure whether the connection will ever be closed because I haven't used a context manager. Is there an accepted way to get a connection to one of your DATABASES which will allow me to specify the cursor_factory? -
error when trying to execute python manage.py migrate
django.db.utils.OperationalError: (1046, 'No database selected') I get the above error when I try to execute: python manage.py migrate The database settings in my settings.py file are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'DATABASE': 'financeblog', 'USER': 'financeblog', 'PASSWORD': 'xxxxx', 'HOST': '127.0.0.1', 'PORT': '3308', } } I have confirmed that the database does in fact exist. The port is 3308 -
Error generating pdf from latex file in django in production
I developed a system to generate a pdf through a latex file and deployed it to a Windows server using Microsoft SII, on my local machine it generates the pdf normally, but in production it generates the following error: Command 'cd "C:\Windows\TEMP\tmpzrdfals9" && pdflatex -interaction=batchmode texput.tex' returned non-zero exit status 1. Here's the code of the view: def verFormularioDesconto(request,id): with connections['integracaoSiem'].cursor() as cursor: sql = "SELECT VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'APROVACAO'),\ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'CRM_RT') ,\ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'NM_RT'), \ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'NU_REGISTRO_EMPRESA'),\ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'RAZAO_SOCIAL'),\ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'CNPJ'), \ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'ID_SOLICITACAO'), \ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'PRAZO') \ FROM DUAL" valores = {'id':id} cursor.execute(sql,valores) resultado = cursor.fetchall() context = { "date": datetime.now().strftime("%d/%m/%Y %H:%M:%S"), "CRM_RT": resultado[0][1], "NM_RT": resultado[0][2], "NU_REGISTRO_EMPRESA": resultado[0][3], "RAZAO_SOCIAL": resultado[0][4], "CNPJ": resultado[0][5], "ID_SOLICITACAO": str(resultado[0][6].zfill(5)), } if resultado[0][0] =='A' and resultado[0][7] == 'S': return render_to_pdf(request, "latex/formularioDesconto.tex", context,filename='Requerimento_de_desconto.pdf') else: return HttpResponseNotFound('<h1>Página não encontrada</h1>') latex code: \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{anysize} \usepackage{fancyhdr} \pagestyle{fancy} \fancyhf{} \lhead{ {{date}} } \rhead{ Nº Solicitação: {{ID_SOLICITACAO}} } \cfoot{ \thepage} \marginsize{30mm}{30mm}{20mm}{20mm} \date{} \begin{document} \section*{REQUERIMENTO DE DESCONTO DE 80\% NA ANUIDADE PESSOA JURÍDICA 2021} %\maketitle Número de registro da EMPRESA no CRMMG: {{NU_REGISTRO_EMPRESA}} \\ Número de inscrição no CNPJ: {{CNPJ}} \\ Razão Social: {{RAZAO_SOCIAL}} \vspace{1em} Eu, {{NM_RT}}, CRMMG n.º {{CRM_RT}}, Responsável Técnico do estabelecimento acima identificado, venho REQUERER junto ao Conselho Regional de Medicina do Estado de Minas Gerais, desconto … -
django postgresql cumulative sum
I am trying to make a party ledger. which details will show by a date search result. I have a column name balance which will display cumulative data by the date search. The balance field is a decimal field. I am trying the following in views.py def partyDetails(request,pk): form = DateRangeForm() search = [] until = [] cumbalance = 0.00 if request.method == 'POST': form = DateRangeForm(request.POST or None) if form.is_valid(): search = PurchasePayment.objects.filter(vendor=pk,date__range=( form.cleaned_data['start_date'], form.cleaned_data['end_date'] )) for balancet in search: cumbalance += Decimal(balancet.balance) else: return redirect('party_ledger') return render(request, 'purchase/party_details.html', {'dateform':form, 'party':search,'name':pk, 'cumbalance':cumbalance}) But I am getting error unsupported operand type(s) for += If I try cumbalance += [balancet.balance] then get [Decimal('200000.00'), Decimal('-200000.00')] MY Models.py are given bellow class PurchasePayment(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) invoice = models.CharField(max_length=20) vendor = models.CharField(max_length=50) amount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) discount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) payment = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) balance = models.DecimalField(max_digits=9, decimal_places=2) remarks = models.TextField(blank=True) extra = models.CharField(max_length=100, blank=True) def __str__(self): return self.vendor How can I make a cumulative view in balance field -
Celery is killed after running gunicorn
I have implemented all of Celery, Redis, Nginx and Django configurations. First, I am running Redis, then after I am running Celery. I can see that celery is working but when I run gunicorn, celery is being killed. I wonder what is the problem here, I have to start gunicorn so that to access Django application. -
How to get the logged in user ip and compare it with the previous ip, if the ip address is different, a message is issued (Django)
I'm quite new to the world of python and django programming, I'm developing my first app which is basically a very simple blog. I would like to know how to do what I have described in the title. I haven't created a user model but i have used settings.AUTH_USER_MODEL, a form.py for the Login and a view.py. Form.py class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password,) if not user: raise forms.ValidationError('Account does not exist') if not user.check_password(password): raise forms.ValidationError('Wrong password') if not user.is_active: raise forms.ValidationError('User disabled') return super(UserLoginForm,self).clean(*args, **kwargs) View.py def login_view(request): next = request.GET.get('login') title = 'Login' form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if next: return redirect(next) return render(request,'bloggo/homepage.html', {}) return render(request, 'bloggo/account_form.html', {'form': form, 'title': title}) Thank u all!! -
How to use the add tag in django admin templates
in django admin change_list_results.html there is a part which is responsible for the items that get registered for a model in the screen {% for item in result %} {{ item }} {% endfor %} Now I wanted to add something to the first of every item, I know if it was in pagination, I could do add:paginator.page.start_index but in this case, there is no start_index key for item, or result : {{ forloop.counter|add:item.start_index }} or {{ forloop.counter|add:result.start_index }} returns Failed lookup for key [start_index] in '<td class="action-checkbox"><input type="checkbox" name="_selected_action" value="705" class="action-select"></td>' So what should I do to add something to the listview of an item in django admin? -
How to merge two Querysets and create new queryset in django
class IndoorInventory(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) product = models.CharField(max_length=50) indoor_brand = models.CharField(max_length=100, null=True, blank=True) indoor_model_no = models.CharField(max_length=100, null=True, blank=True) indoor_sr_no = models.CharField(max_length=100, null=True, blank=True) outdoor_model_no = models.CharField(max_length=100, null=True, blank=True) class OutdoorInventory(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) product = models.CharField(max_length=50) outdoor_brand = models.CharField(max_length=100, null=True, blank=True) outdoor_model_no= models.CharField(max_length=100, null=True, blank=True) outdoor_sr_no = models.CharField(max_length=100, null=True, blank=True) indoor_model_no= models.CharField(max_length=100, null=True, blank=True) I have two models for two parts of AC, that is IndoorInventory for the indoor unit which shows all indoor unit information, and OutdoorInventory for showing outdoor unit information. I am passing a queryset of IndoorInventory to my Django template and fetching all the data there. enter image description here Now I want to get the outdoor_sr_no from OutdoorInventory models and pass it to the IndoorInventory queryset so that outdoor_sr_no value also get fetched on the table -
How to make Tags and Categories Separate in django wagtail
How to make Tags and Categories Separate... I have a tag for SCRC and a Tag for Libraries, but How can i make it so when I create a blog, and choose each different tag, the posts show up?