Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'grappellidjango'
I've installed "grappelli" according to the instructions(https://django-grappelli.readthedocs.io/en/latest/quickstart.html#installation) But when I try "python manage.py collectstatic", I get this: Traceback (most recent call last): File "/home/golovinss/PycharmProjects/test_platform_001/manage.py", line 22, in main() File "/home/golovinss/PycharmProjects/test_platform_001/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/dist-packages/django/core/management/init.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/dist-packages/django/core/management/init.py", line 420, in execute django.setup() File "/usr/local/lib/python3.10/dist-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.10/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.10/dist-packages/django/apps/config.py", line 228, in create import_module(entry) File "/usr/lib/python3.10/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'grappellidjango' How to fix it? -
ValueError at /post/politics Field 'id' expected a number but got 'politics'
I have a template posts.html {% extends 'base2.html' %} {% block posts %} <div class="row"> <div class="leftcolumn"> <div class="cardpost"> <h1>{{posts.title}}</h1> <h5>{{posts.created_at}}</h5> <div class="fs-4">{{posts.body | safe}}</div> </div> </div> </div> {% endblock %} posts.html extends base2.html, because I want the posts.html to have nav bar functionality <nav id="navbar" class="navbar"> <ul> <li><a href="about">About</a></li> <li><a href="guestposting">Guest Posting</a></li> <li class="dropdown"><a href=""><span>Categories</span> <i class="bi bi-chevron-down dropdown-indicator"></i></a> <ul> <li><a href="tech">Tech</a></li> <li><a href="bizconomics">Bizconomics</a></li> <li><a href="politics">Politics</a></li> <li><a href="religion">Religion</a></li> <li><a href="sports">Sports</a></li> </ul> </li> <li><a href="contactform">Contact</a></li> </ul> above is a section of the nav bar which is on base2.html, and also on the index.html. It works perfectly in the index.html. But when the user is on the posts.html-> path('post/str:pk', views.post, name='post') and they click politics category for instance, I get this error: ValueError at /post/politics Field 'id' expected a number but got 'politics'. Here are my url routes path('', views.index, name='index'), path('post/<str:pk>', views.post, name='post'), path('politicalpost/<str:pk>', views.politicalpost, name='politicalpost'), path('bizconomicspost/<str:pk>', views.bizconomicspost, name='bizconomicspost'), path('techpost/<str:pk>', views.techpost, name='techpost'), path('sportspost/<str:pk>', views.sportspost, name='sportspost'), path('religionpost/<str:pk>', views.religionpost, name='religionpost'), path('subscribe', views.subscribe, name ='subscribe'), path('contactform', views.contactform, name='contactform'), path('about', views.about, name='about'), path('guestposting', views.guestposting, name='guestposting'), path('bizconomics', views.bizconomics, name='bizconomics'), #These are the caregory urls path('tech', views.tech, name='tech'), path('sports', views.sports, name='sports'), path('politics', views.politics, name='politics'), path('religion', views.religion, name='religion'), path('culture', views.culture, name='culture'), path('culturepost/<str:pk>', views.culturepost, name='culturepost'), So how can … -
Django: Image not saving on django update view?
I am trying to update a model, every other information in the model get updated but the image does, i cannot really tell what is wrong the view that is updating the models. views.py @login_required def UpdateRoom(request, pk): room = Chatroom.objects.get(id=pk) if not room : return redirect("chats:message") form = ChatRoomForm(instance = room) if request.user != room.host : messages.error(request , "You are not allowed to Edit Room Settings !") return redirect("chats:message") if request.method == "POST": room.roomname = request.POST.get("roomname") room.topic , created = Topic.objects.get_or_create(name = request.POST.get("topic")) room.description = request.POST.get("description") room.image = request.FILES.get("image") room.save() return redirect("chats:chat-room" , pk=room.id) context = {"form": form, "button_value": "Update" , "room" : room } return render(request, "chat/room_update_form.html", context) -
change field type in django forms
I have a model for a group that has two fields: leader and description. models.py class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() forms.py class GroupForm(forms.ModelForm): class Meta: model = Group fields = ('leader', 'description') My issue is that I want to change the field type for leader. Right now the default is a drop down/select with all the available Users in my database. I don't want Users to be able to make Groups in other Users' names. I want instead for the leader field to be a TextInput field and use javascript to change the leader value to whatever the Users.username value is. So, the I added a widget, but now there's more problems: forms.py class GroupForm(forms.ModelForm): class Meta: model = Group fields = ('leader', 'description') widgets = { 'leader': forms.TextInput(attrs={'id': 'leader', 'type': 'hidden', 'value': ''}) } My goal was to use a script tag on my django template to getElementById('leader') and change it's value to user.username all the while keeping it hidden from the current user. However I keep hitting snags, the main one being I can't seem to change the field type for leader from a select to a TextInput, so every time I try and … -
Fetching Django Objects using the __str__ method
I have this Django model called Clause and I have a __str__ method defined for it. Now I have a form that displays a dropdown for the clauses, but when I POST that form, it converts those clauses to strings, whereas I need the Clause objects. Is there a way to get the clause if I have it's .__str__()? -
Deploy Error: Non-Zero Exit Code - Django app on digital ocean
Hi, I'm trying to upload a django app on digital ocean. The build ran fine but I've no idea why it says this. Deploy Error: Non-Zero Exit Code Please help! Thanks in advance :) -
AttributeError: type object 'StaffFilter' has no attribute '_meta'
When i try to access the urls , it kept return AttributeError: type object 'StaffFilter' has no attribute '_meta'. However, i already declared _meta in filters.py but the error kept returning. Is there any way to solve this problem ? filters.py from django_filters.rest_framework import FilterSet from django_filters import DateTimeFilter, BaseInFilter, CharFilter from .models import Staff class StaffFilter(FilterSet): department__in = BaseInFilter(field_name="department", lookup_expr='in') job_grade__in = BaseInFilter(field_name="job_grade", lookup_expr='in') class Meta: model = Staff fields = [ 'job_grade__in', 'department__in',] -
Cannot get polls to show in url
I am following the django tutorials and so far whilst on task 3, I cannot get the polls to show on the url. If I have followed the instructions properly and carefully, it should look like this: models.py: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) views.py from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) urls.py: from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are … -
Put request.path to a url parameter in Django template
I want to create a back button to a page which can be accessed with a link from another page. To do this, I want to put the first page's path to the link, and on the next page I can put it to the back button. I have this anchor tag: <a href="{% url 'page' path=request.path %}">Go to page</a> When I try to go to the site I get the following error: Reverse for 'page' with keyword arguments '{'path': '/my_site/'}' not found. 1 pattern(s) tried: ['notifications\\/(?P<path>[^/]+)\\Z'] -
How to build a django queryset in order to show all related objects grouped and show in the render template
Achieve: Show the data into the template as example bellow: PLan 1: ABC - General Objective 1 - Sub-Objective-1 - Task 1 - Task 2 - Sub-Objective-2 - Task 1 PLan 2: ZZZ - General Objetivo General 1 - Sub-Objetivo-1 - Tarea 1 PLan 3: DDD - General Objetivo General 1 - Sub-Objetivo-1 - Tarea 1 - Sub-Objetivo-2 - Tarea 1 This means that: A plan can have many general objectives and this general objective can have several sub-objectives and each of its objectives can have one or several tasks. My actual models and all relations: class ActionPlan(models.Model): description = models.CharField ( max_length=250, null=False, default='' ) class PlanObjective(models.Model): actionplan = models.ForeignKey ( ActionPlan, on_delete=models.CASCADE ) description = models.TextField ( max_length=1750, null=False, default='') class PlanSubObjective ( models.Model ) : actionplan = models.ForeignKey ( ActionPlan, on_delete=models.CASCADE ) planobjective = models.ForeignKey ( PlanObjective, on_delete=models.CASCADE ) description = models.TextField ( max_length=1750, null=False, default='' ) class PlanSubObjectiveTask ( models.Model ) : actionplan = models.ForeignKey ( ActionPlan, on_delete=models.CASCADE ) planobjective = models.ForeignKey ( PlanObjective, on_delete=models.CASCADE ) plansubobjective = models.ForeignKey ( PlanSubObjective, on_delete=models.CASCADE ) description = models.TextField ( max_length=1750, null=False, default='' ) This is my actual query: plans = PlanSubObjectiveTask.objects.filter(period=period).select_related( 'plansubobjective', 'planobjective', 'actionplan') I was reading the … -
Serving Django`s static/media files via IBM Cloud Foundry
Greetings to everyone! Need some help to figure out proper deployment concept of simple Django app related to serving static/media files. The goal is to use IBM Cloud Foundry capabilities, so the question is probably more platform specific. The problem is Django in DEBUG=False mode does not take care of static files any more, so its time for some fancy webserver config to take into action. As with IBM Cloud Foundry, I cant find proper way to serve my media links, so images are not visible. For example I get '/media/...' instead of '/static/media/...' with my configuration. The solution should be relatively obvious, but I cant figure it out. For IBM Cloud Foundry my manifest.yml: applications: - name: onlinecourse routes: - route: $HOST.$DOMAIN memory: 128M buildpack: python_buildpack - name: onlinecourse-nginx routes: - route: $HOST.$DOMAIN/static memory: 64M buildpack: staticfile_buildpack So actually there are two apps: 'onlinecourse' manages Django files and 'onlinecourse-nginx' serves static. This is kind boilerplates that leverages use of pre-configured staticfile_buildpack with nginx start up somewhere inside, so probably that is a 'devil' here. First things first, my model is: class Course(models.Model): ... image = models.ImageField(upload_to='course_images/') ... In template I try to render image as follows: <img src="{{ course.image.url … -
how to make an AutoField start from 1000 in Django?
i created a Django model this way in models.py: class Contact(models.Model): id = models.AutoField(primary_key=True, auto_created=True) mail = models.EmailField() and i want the id to start auto generating from 1000 not starting from 1. -
how to dont save a empty input django and why is not showing data on admin page?
how to don't save a empty input django and why is not showing data on admin page ? because when i try to click on myhtml page is save the empty column every click and save it on my data base , how to stop saving the empty input or don't allow user input the empty input ? and why i cant see the datetimefield on admin page ?? this my views.py from django.shortcuts import render from .models import Name from django.shortcuts import redirect # Create your views here. def Home(request): if request.method == 'POST': Name.objects.create(massenger_name=request.POST['user_name']) return redirect(Home) return render(request , 'index.html') and this mosels.py from django.db import models # Create your models here. class Name(models.Model): massenger_name = models.CharField(max_length=50) action_time = models.DateTimeField(auto_now_add=True,null=True, blank=True) def __str__(self): return str(self.massenger_name) -
not triggering the post_delete_signal when it's coming from a CASCADE delete
Hello I have two django models linked by a foreign key and it looks like this class Author(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, null=False, db_index=True) number_of_books=models.IntegerField() #other fields class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='books') name = models.CharField(max_length=255, null=False, db_index=True) #other fields The Book model has a post_delete_signal that triggers some computations for te author instance def book_post_delete(sender, instance, **kwargs): # Re save max exposure author = instance.author author.number_of_books = author.books.count() author.save() trigger_computation(author) My problem is that if I delete an author for example, then his books are also deleted because of the on_delete=models.CASCADE, the book_post_delete function is then called and the trigger_computation(author) is called, which takes a lot of time for me and is also useless because the author is being deleted. Is there a way to get around not triggering the computation when the instance that is being deleted is an author? -
Django Title Block Showing on Page Content
example of issue: https://imgur.com/a/dtZsdjr Code views.py def home_view(request, *args, **kwargs): context = { "title" : "PortfolioLog - Home", } return render(request, "base.html", context) base.html <html lang = "en"> <head> <meta charset="utf-8"> <title>{{title}}</title> <meta name="description" content="Home page"> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> <script type="text/javascript" src="{% static 'scripts.js' %}"></script> </head> </html> -
How to create group of users in django
I want to create group where members of the group can see the documents, announcements and also list of members of the group. How do I code that in django models? Do I create custom group? Users can be member of many groups, and group can have a lot of members. So, it should be a many-to-many relationship(?) Do I put users under group models or the other way around? And how do I store announcements and documents of the group? Do I keep it under group models too? Or put group under the announcements and documents model, like how category is put under the post models like this: class Category(models.Model): name = models.CharField(max_length=100) class Post(models.Model): category = models.ForeignKey( Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=250) content = models.TextField() -
Redering a list of objects with date and drop down
I am on the path of learning django. My personal project aims to create a clickable date based on available dates for different destinations. I have some data that is directly scraped from scrapy in the following format: departureDate = [{'departureDate': '2022-07-29', 'id': 'The Bahamas'}, {'departureDate': '2022-11-11', 'id': 'The Bahamas'}, {'departureDate': '2022-11-18', 'id': 'The Bahamas'}, {'departureDate': '2022-12-02', 'id': 'The Bahamas'}, {'departureDate': '2023-01-13', 'id': 'The Baltic Sea'}, {'departureDate': '2023-02-03', 'id': 'The Baltic Sea'}, {'departureDate': '2023-02-17', 'id': 'The Baltic Sea'}, {'departureDate': '2023-03-03', 'id': 'The Baltic Sea'}, {'departureDate': '2023-03-24', 'id': 'The Baltic Sea'}, {'departureDate': '2023-04-07', 'id': 'The Western Mediterranean'}, {'departureDate': '2023-04-14', 'id': 'The Western Mediterranean'}, {'departureDate': '2023-04-28', 'id': 'The Western Mediterranean'}, {'departureDate': '2023-12-21', 'id': 'The Western Mediterranean'}, {'departureDate': '2023-12-28', 'id': 'The Western Mediterranean'}], I want to then be able to load this into my model: Here's my model.py: from django.db import models class Cruises(models.Model): departureDate = models.DateTimeField('Departure Date') id = models.CharField('Destination', max_length=200) Then my views: from django.shortcuts import render from .models import Cruises def basic(request): departure_list = Cruises.objects.values('departureDate', 'id') return render(request, cruise_control/basic.html, context={'departure_list':departure_list}) basic.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Cruises</title> </head> <body> <h1> Cruise Control </h1> {% for dep_l in departure_list %} <form action="/action_page.php"> <label for='destination'>Destination</label> <input type="text" list="destination" /> <datalist id="destination"> … -
TypeError: connect() argument 4 must be str, not WindowsPath
Problem in connecting mysql to django Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 53, in init self.build_graph() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 235, in cursor self.ensure_connection() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb_init.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb\connections.py", line 185, in init super().init(*args, **kwargs2) TypeError: connect() argument 4 must be str, not WindowsPath DATABASES = { 'default': { … -
Unable to save my form field getting error again and again
I built a simple signup form that will take data as the user will click submit it and will save it in the database. But for some reason, I am able to validate it. I removed all the validations and added them again too. Not sure where I am missing? it is not saving and giving the error Error Processing Your Request. which is in the else block of the code Forms.py: class RegisterForm(UserCreationForm): email = forms.EmailField(max_length=100,help_text='Enter Email Address', required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email'})) first_name = forms.CharField(max_length=100,help_text='Enter First Name', required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'})) last_name = forms.CharField(max_length=100,help_text='Enter Last Name', required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'})) username = forms.CharField(max_length=100,help_text='Enter Username', required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})) password = forms.CharField(max_length=200,help_text='Enter Password', required=True,widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) password2 = forms.CharField(max_length=200,help_text='Enter your Password again', required=True,widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) #check = forms.BooleanField(required = True) class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'password', 'password2' #, 'check' ] Views.py: def register(request): if request.method == 'GET': #when you request a form it is in a get request form = RegisterForm() context = {'form' : form} #this creates a object which you want to send to the front end return render(request, 'signup-login.html', context) # here we pushing that form … -
Django rest_framework, logout redirect doesnt work
I am trying to redirect to the home page after clicking on Logout urls.py urlpatterns = [ . . path("api-auth/", include("rest_framework.urls")), ] settigs.py . . LOGOUT_REDIRECT_URL = "/" ACCOUNT_LOGOUT_REDIRECT_URL = "/" The problem is it still redirect to /api-auth/logout/?next=/current-page. This will cause an error because this "current page" needs authentication (requires a login) unlike the home page which doesn't require a login I also tried path("api-auth/logout", RedirectView.as_view(url="/", permanent=True)) but this again didn't work(still redirected to the "current page"). How can I redirect to the home page? -
Telethon TelegramClient.sign_in deadlock
I'm trying to separate my account access logic with Telethon. Thus, first a user enters his phone number, password, and then, when he receives an SMS with a code, he enters it too, and I can work with TelegramClient. Here's my code inside a Django project (the code is incredibly awful since I'm writing it in haste and for myself): urls.py from django.urls import path from .views import main_page, verify urlpatterns = [ path("authenticate/", main_page), path("verification/", verify, name="verify") ] view.py from django.shortcuts import render, redirect from django.urls import reverse from telethon import TelegramClient global phone, password, hash_, client phone = None password = None hash_ = None client = TelegramClient( "Telegram Client", 0, "" ) async def main_page(request): global phone, password, client, hash_ if request.POST: phone = request.POST['phone'] password = request.POST['password'] print("Connecting to the client") await client.connect() print("Sending an SMS with the code") hash_ = await client.send_code_request(phone) return redirect(reverse("verify")) return render(request, "credentials.html") async def verify(request): global phone, password, client, hash_ if request.POST: print("Connecting to the client") await client.connect() print( "Data before signing in: " "phone {}, password {}".format(phone, password) ) # Here is a deadlock. client = await client.sign_in( phone, request.POST["code"], password=password, phone_code_hash=hash_.phone_code_hash ) print( "Check after signing in", await … -
Django. Updating the model instance
Let's say I have a model: class PurchaseOrder(models.Model): supplier = models.ForeignKey('Supplier', on_delete=models.DO_NOTHING) employee = models.ForeignKey('employees.Employee', on_delete=models.DO_NOTHING) total_price = models.FloatField(null=True, blank=True) creation_date = models.DateTimeField(auto_now_add=True) posted = models.BooleanField(default=False) required_shipment_date = models.DateField(null=True, blank=True) date_shipped = models.DateField(null=True, blank=True) date_of_receiving = models.DateField(null=True, blank=True) shipment_address = models.CharField(max_length=255) order_status = models.CharField(max_length=255, choices=OrderStatus.ORDER_STATUS_CHOICES, default='ACCEPTED') def __str__(self): return f"Purchase order {self.supplier} № {self.pk}" def get_absolute_url(self): return reverse('purchases:purchase-order-details', kwargs={'pk': self.pk}) def compute_total_price(self): total_price = PurchaseOrder.objects.annotate( value=models.Sum(models.F('purchaseorderitem__quantity') * models.F('purchaseorderitem__price_per_unit')) ) print("total price") self.total_price = total_price[0].value In my model I have a method "compute_total_price" which gets all order items and multiplies quantity and price for every item and then sum it. The issue is I don't know how to save value to my model's field "total_price". I thought accessing self will do that, but it doesn't. The method computes the value however field isn't updated. -
django.db.utils.IntegrityError: NOT NULL constraint failed: Eid_Post_name.massenger_name
i have this issue "django.db.utils.IntegrityError: NOT NULL constraint failed: Eid_Post_name.massenger_name " and these my codes views.py from .models import Name # Create your views here. def Home(request): name_input = request.POST.get('user_name') name_in_model = Name(massenger_name=name_input,) name_in_model.save() return render(request , 'index.html') and this models.py from datetime import datetime # Create your models here. class Name(models.Model): massenger_name = models.CharField(max_length=50) action_time = models.DateTimeField(default=datetime.now) def __str__(self): return self.massenger_name and this index.html <!DOCTYPE html> <html lang="en" dir="rtl"> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" href="{% static 'CSS/style.css' %}"> </head> <body> <div id="form"> <form class="row" method="POST"> <div class=""> <input type="textarea" class="form-control" placeholder="أكتب أسمك (مثلا/أخوكم عبدالله العتيبي)" id="text_name" name="user_name"> </div> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-3" id="button">حمل الصورة</button> </div> </form> </div> </body> </html> -
Best way to use "context" on Django templates for many variables / dictionaries
I want to send a lot of data to 1 Django template (to show it on 1 specific page). The data comes from 2 sources: At least 1 list, with many dictionaries inside (I can't change any of this, it comes from Google Ads API). Many variables (I can change them, for example, to turn them into dictionaries or tuples if necessary). The variables are very simple, something like "variable = other_variable / 100" (just 1 value, no need for a key), so I don't need the variables to be turned into a dictionary. But I've understood (maybe wrong) that the "context" from Django's render needs dictionaries. The variables' data comes from the list (I do some calculations using some of the list values), but maybe this is not relevant for my question. Right now I'm doing something like this in my views.py: campaign_data = [] CODE TO FILL THAT LIST WITH API DATA (MANY DICTIONARIES INSIDE) clicks = sum(data['campaign_clicks'] for data in campaign_data) sum_clicks = {"sum_clicks" : clicks} context = { 'campaign_data' : campaign_data, 'sum_clicks' : sum_clicks } return render(request, 'testing.html', context) And then on the Django template I use the data from views.py like this: {% for element … -
Wierd behaviour in django
I am using SQLite in my Django project, I am gathering the data into the database manually with python. everything worked fine in that phase, now when I am trying to reach them in the templates file, something weird is happening, Django keeps giving me a NoReverseMatch match (because I am having a link that is referring to a view for some calculations, this view needs a URL which I have in my template), the weird thing is, when I open my 127.0.0.1:8000/admin and opening the data I've gathered and saved them, Django won't give me an error! it seems I have to do something like migrating my new data manually to project too, its very confusing