Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting SSL error when sending mail via Django
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997) This is what I see when I send mail via Django. This is my email configuration in settings.py # Email Settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "xxxxxxxx@gmail.com" EMAIL_HOST_PASSWORD = "xxxxxxxxxxxxx" EMAIL_USE_TLS = True this is how I send mail send_mail( "Subject", "Test message", settings.EMAIL_HOST_USER, ["xxxxxxxxx@gmail.com"], fail_silently=False, ) -
Django filter queryset and get unique items
I am using Django and SqLite. I have this model table: class TestPROD(models.Model): prodID = models.CharField(max_length=15) ProdDate = models.CharField(max_length=15) Price1 = models.DecimalField(max_digits=10, decimal_places=3,default=0) Price2 = models.DecimalField(max_digits=10, decimal_places=3,default=0) post_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.prodID def get_Total(self): TotPRC =self.Price1 +self.Price2 return round(TotPRC, 2) def get_absolute_url(self): return reverse('Custom', args=[self.prodID]) class Meta: ordering = ('-TestDate',) in my data base I have many rows which contains duplicated items for example prodID HP or Lenovo have 1000 or more rows. my question is how to filter the data and give me only the last ProdDate of the product HP and so the last item for Lenovo and one. in my views.py I tried many solution but I din't get the good results def welltests(request): testprodms = TestPROD.objects.annotate(latest_test_date=('prodID')).order_by('-ProdDate').distinct() return render(request, 'Home/AllProd.html', {'testprodms': testprodms}) this will gives my all the data (50000 rows) but organized by product. the unique prodID in my database is about 600. so I need 600 rows of different product with the last ProdDate then I tried this and many other but not working; def welltests(request): testprodms = TestPROD.objects.order_by().values_list('prodID', flat=True).distinct() return render(request, 'Home/AllProd.html', {'testprodms': testprodms}) this gives me the number of my products but with no other data in my … -
i want create url when user click pass to profile page -- NoReverseMatch at /home
i want create url when user click pass to profile page ++++ models class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) music = models.CharField(max_length=50) skils = models.CharField(max_length=50) search = models.CharField(max_length=50) posts = models.CharField(max_length=50) boi = models.TextField() img = models.ImageField(upload_to="profile-img") def __str__(self): #return self.user or 'User' return str(self.id) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) +++ views def home(request): return render(request, 'main-frond.html') def profile_edit(request, id): pro_edit = profile.objects.get(id=id) if request.method == 'POST': user_form = User_Form(request.POST, request.FILES, instance=pro_edit) if user_form.is_valid(): user_form.save() return redirect('profile_views') else: user_form = User_Form(instance=pro_edit) context = {'user_form' : user_form} return render(request, 'profile_edit.html', context) +++url path('home', views.home, name="home"), path('profile/<int:id>/edit', views.profile_edit, name="profile_edit") +++ html <a href="{% url 'profile_views' %}">profile</a> django give me problem Reverse for 'profile_views' with no arguments not found. 1 pattern(s) tried: ['profile/(?P<id>[0-9]+)\\Z'] i want create url when user click pass to profile page -
preserve multiple GET parameters in Django URL
In my django project I have a page displaying a list of times. On this page there is 3 GET forms which are for: Parsing through pages Selecting graph data Sorting items If a user is to select a field in all of these forms the URL should look something like this: http://127.0.0.1:8000/watchlist/?page=1&graph_data=price&sort=quantity_desc But when a user submits one of these forms it only saves that GET parameter in the URL. eg: selects page = 2 http://127.0.0.1:8000/watchlist/?page=2 selects sort = quantity_asc http://127.0.0.1:8000/watchlist/?sort=quantity_asc The page parameter is over written when both parameters should be present in the URL. How can i preserve multiple GET parameters in the URL? views.py def watchlist(request): #get requests graph_metric = request.GET.get("graph-data-options", "avg_price") page = int(request.GET.get("page", 1)) sort_field = request.GET.get("sort-field", "avg_price-asc") return render(request, "App/watchlist.html", context=context) html <!-- Page number --> <form id="page-buttons-form" action="{% url 'watchlist' %}" method="GET"> {% for page_button in num_pages %} <input name="page" type="submit" value="{{page_button}}"> {% endfor %} </form> <!-- Sort items --> <form id="sort-form" action="{% url 'watchlist' %}" method="GET"> <label for="sort-field">Sort:</label> <select onchange="this.form.submit()" name="sort-field"> {% for sort in sort_options %} <option value="{{sort.value}}">{{sort.text}}</option> {% endfor %} </select> </form> <!-- Graph data --> <form action="{% url 'watchlist' %}" method="GET"> <label for="graph-data-options">Graph Data</label> <select onchange="this.form.submit()" name="graph-data-options"> {% … -
Django Template doesn't work with a for loop in range. Why?
VIEWS.PY def index(request): posts = Post.objects.all() posts_quantity = range(1) return render(request, 'index.html', {'posts':posts, 'posts_quantity':posts_quantity}) HTML {% for index in posts_quantity %} <a href = "{% url 'architectural_post' posts.index.slug %}" class = "post"> {% endfor %} it gives me an error: Reverse for 'architectural_post' with arguments '('',)' not found. But everything works well if I put 0 instead of index, like this (just for debugging): {% for index in posts_quantity %} <a href = "{% url 'architectural_post' posts.0.slug %}" class = "post"> {% endfor %} Why and how to fix it? Thanks. -
Why django forms shows input in row instead of a column
I wonder why django modelForm shows input in a row instead of a column like this: I like all input in my model to be in a column when putting {{ form|crispy}} in the template, as you can see in the template, even if add col-md-3 to resize the input in a col it does not work, I think there is something I need to know about django-forms. template: --- Bootstrap-5 <div class="container"> <div class="row justify-content-center"> <div class="col-md-3"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy}} <button type="submit" class="btn btn-primary">Create Student</button> </form> </div> </div> </div> The Result: My Forms.py file: class PrimaryForms(forms.ModelForm): signature_of_student = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) signature_of_guardian = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) class Meta: model = Primary fields = ['admission_number', 'profile_picture', 'first_name', 'last_name', 'gender', 'address_of_student', 'class_Of_student', 'comment_of_student', 'year_of_graduation', 'date_of_birth', 'religion', 'mother_name',] How can I make my input to be in column? -
Javascript returns the same id for every iterated element in html
I have website which i build using Django where every visitor can leave their message or press a like button on any comment. I would like to show how many of a comment has been liked by the user. As each comment is unique, I think to access the comment_id attribute which I wrote in the html part. I then use a simple js function to retrieve the id. The problem is, although html is showing unique id for each comment, Javascript still return the same id, that is the id of the first comment that is written on the page. Can someone tell me where is my mistake in this case? Thank you in advance for your help. my code in js: function likeButton(){ let el = document.getElementById("chat-icon-thumbsup") alert(el.attributes["comment_id"].value) }; my html code, which is looping the datatable records "comment" from a datatable in Django framework: {% for comment_ in comments %} <strong> {{ comment_.name }} - {{ comment_.date_added }} <button><i comment_id="{{ comment_.comment_id }}" id="chat-icon-thumbsup" class="fa fa-fw fa-thumbs-up" title="like this comment" onclick="likeButton()"></i></button> {{ comment_.nr_of_likes }} <br/> </strong> {{ comment_.body }} <br/> {% endfor %} image 1: here you see when I inspect the DOM elements, it retrieves different "comment_id" … -
Django permissions are present but has_perm() returns False
I'm working on the permissions on a Django 4.1 application. All these permissions are given by groups. First permission first problem: Permission codename: can_see_all_images appname for the permission: dating group having this permission: X-Gold As you can see on the screenshot it seems that all the informations are correct: First line: User is in the group Second line, the group has the permission Third line: The permission has the good codename but line4: the user doesn't have the perm. I restarted the server disconnected the user and reconnected it, nothing changed. Note that if I give the permission directly to the user, it doesn't work. So I guess the problem does not come from the group. Any idea? Here is how the permission is created in the model: permissions = [('can_see_all_images', _('Can see all images'))] Thanks in advance -
Trying to get and update or create model from json in Django
Im trying to get and update or create object in model from json list of dicts but i got an error: "TypeError: Tried to update field authentication.CounterParty.GUID with a model instance, <CounterParty: CounterParty object (3)>. Use a value compatible with UUIDField. " models.py class CounterParty(models.Model): GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) name = models.CharField(max_length=150) customer = models.BooleanField(default=False) contractor = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Counter Party' tasks.py def create_counter_party(): response = [ { "CounterpartyGUID": "e58ed763-928c-4155-bee9-fdbaaadc15f3", "CounterpartyName": "name1", "Customer": False, "Contractor": True }, { "CounterpartyGUID": "123e4567-e89b-42d3-a456-556642440000", "CounterpartyName": "name2", "Customer": False, "Contractor": False }, ] rep = response for item in rep: try: counter_party = CounterParty.objects.get(GUID=item['CounterpartyGUID']) updated_counter_party = CounterParty.objects.update(GUID=counter_party, name=item['CounterpartyName'], customer=item['Customer'], contractor=item['Contractor']) updated_counter_party.save() except CounterParty.DoesNotExist: counter_party = CounterParty.objects.create(GUID=item['CounterpartyGUID'], name=item['CounterpartyName'], customer=item['Customer'], contractor=item['Contractor']) counter_party.save() errors: [2023-01-28 15:29:31,894: ERROR/ForkPoolWorker-8] Task authentication.tasks.create_counter_party[a86333d9-e039-479e-8d35-37fa6b17dbfa] raised unexpected: TypeError('Tried to update field authentication.CounterParty.GUID with a model instance, <CounterParty: CounterParty object (3)>. Use a value compatible with UUIDField.') Traceback (most recent call last): File "/home/zesshi/.local/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/home/zesshi/.local/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/mnt/c/Users/Shalltear/Desktop/Python/unica_django/authentication/tasks.py", line 27, in create_counter_party counter_party = CounterParty.objects.update(GUID=counter_party, name=item['CounterpartyName'], File "/home/zesshi/.local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/zesshi/.local/lib/python3.9/site-packages/django/db/models/query.py", line 1191, in update rows = … -
Reference a custom user model in views.py
I am trying to save to a model named Blog from inside Django's views.py file. This Blog model is itself linked to the custom user model that I created. How exactly do I do that? Below are the models.py file (custom user model is here) models.py file (Blog model created here - in another Django app) views.py file where I try to save to the Blog model. How do I reference the user here? Please excuse the noob-ness of this question. I'm just starting out :) Inside models.py, I have a custom user model: class UserExtended(AbstractUser): is_email_verified = models.BooleanField(default=False) company = models.CharField(null=True, blank=True, max_length=255) position = models.CharField(null=True, blank=True, max_length=255) email = models.EmailField(unique=True) I also created a model for blog articles in models.py: class Blog(models.Model): title = models.CharField(max_length=200) blogSubject = models.CharField(null=True, blank=True, max_length=200) keywords = models.CharField(null=True, blank=True, max_length=300) audience = models.CharField(null=True, blank=True, max_length=200) # connection to custom user model profile = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) In views.py, I am trying to save to the Blog model: def saveBlogTopic(request, blogTopic): # create a Blog model instance blog = Blog.objects.create( title = blogTopic blogSubject = request.POST['blogSubject'] keywords = request.session['keywords'] audience = request.session['audience'] profile = request.user ### ???????? ### ) I have no idea how to … -
static files not loading when DEBUG is False
I set my DEBUG variable to False in setting.py and deployed my project in cpanel,used collectstatic command but static files not loading. setting.py STATIC_URL = '/static/' MEDIA_URL = '/media/' if DEBUG: STATICFILES_DIRS = [( BASE_DIR / 'static/') ] MEDIA_ROOT = os.path.join(BASE_DIR, "static_cdn", "media_root") else: STATIC_ROOT = "/home/smartsbi/public_html/static" MEDIA_ROOT = "/home/smartsbi/public_html/media" urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('blog/', include('blog.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('contact_us.urls')), path('', include('service.urls')), ] if settings.DEBUG: # add root static files urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # add media static files urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to fix python: can't open file '//manage.py': [Errno 2] No such file or directory in Django
How to fix Remainder of file ignored python: can't open file '//manage.py': [Errno 2] No such file or directory when use command docker-compose up This is all my code, and I've also attached an image file. dockerfile files FROM python:3.10 ENV PYTHONUNBUFFERED 1 COPY requirements.txt . RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD = mariadb - MYSQL_DATABASE = mariadb - MYSQL_USER = mariadb - MYSQL_PASSWORD = mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 3306:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: context: . dockerfile: Dockerfile restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mariadb+mariadbconnector://user:mariadb@db:3306/mariadb ports: - "8000:8000" depends_on: - db adminer: image: adminer restart: always ports: - 8080:8080 depends_on: - db volumes: mysqldata: setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mariadb', 'USER': 'mariadb', 'PASSWORD': 'mariadb', 'HOST': '127.0.0.1', 'PORT': 3306, } } file image Django -
django.db.utils.OperationalError: no such column: blog_follow.followed_me_id
I tried delete migration file and python manage.py makemigrations [appname]. However, this is not solve my problem models.py class User(AbstractUser): followers = models.ManyToManyField("Follow",blank=True,related_name="follow_user") class Post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.CharField(max_length=500,null=True,blank=True) timestamp = models.DateField(auto_now_add=True) like = models.ManyToManyField(User,blank=True,related_name="liked_user") @property def number_of_likes(self): return self.like.all().count(), def __str__(self) -> str: return self.post class Follow(models.Model): followed_me = models.ForeignKey(User, on_delete=models.CASCADE,related_name="followed_me", default=None) followed_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followed_by", default=None) def __str__(self) -> str: return f"{self.followed_by.username} start following {self.followed_me.username} " views.py def profile(request,username): my_account = get_object_or_404(User,username=username) my_post = Post.objects.filter(user=my_account).order_by("id") following = False if request.user.is_authenticated: followers = my_account.followers.filter(followed_by_id=request.user.id) if followers.exists(): following = True return render(request,"blog/profile.html",{ "posts":my_post, "post_count": my_post.count(), }) def follow(request,username): all_user = User.objects.all() my_account = get_object_or_404(User,username=username) my_post = Post.objects.filter(user=my_account).order_by("id") following = False if request.user.is_authenticated: followers = my_account.followers.filter(followed_by_id=request.user.id) if followers.exists(): following = True return render(request,"blog/following.html",{ "al_us": all_user, "following":following }) def follow_or_unfollow_user(request,user_id): followed = get_object_or_404(User,id=user_id) followed_by = get_object_or_404(User,id=request.user.id) follow,created =Follow.objects.get_or_create(followed_me=followed,followed_by=followed_by) if created: followed.followers.add(follow) else: followed.followers.remove(follow) follow.delete() return redirect('index') urls.py path("profile/<str:username>",views.profile,name="profile"), path("follow/<str:username>",views.follow,name="follow"), path("follow_or_unfollow/<int:user_id>",views.follow_or_unfollow_user,name="follow_or_unfollow") profile.html <div>total Post {{post_count}} <span>total follower {{currently_followed}}</span> <span>total following {{following_count}}</span></div> {%for pst in posts%} {%if user.id == pst.user.id%} <div class="post-outer-container"> <div class="post-container"> {{pst.post}} {{pst.user}} {{pst.timestamp}} <a href="{%url 'edit-post' pst.id%}" style="margin-left:15px ;"> Edit</a> <a href="{%url 'delete' pst.id%}" style="margin-left:15px ;"> Delete</a> </div> </div> {%endif%} {%endfor%} {%endblock%} following.html <h1>All user</h1> {%for i … -
django deploy nginx auto log out
I am experiencing an issue with my Django application where I am automatically logged out when trying to access my admin panel. I suspect that the problem may be related to session preservation. To further investigate, I have included my nginx configuration and my Django settings file below. map $sent_http_content_type $expires { default off; text/html epoch; text/css max; application/javascript max; ~image/ max; } server { listen 80; listen [::]:80; server_name www.khalimbetovulugbek.com khalimbetovulugbek.com; return 301 https://khalimbetovulugbek.com; } server { listen 443 ssl http2; ssl_certificate /etc/nginx/ssl/server.crt; ssl_certificate_key /etc/nginx/ssl/server.key; server_name khalimbetovulugbek.com www.khalimbetovulugbek.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/benku/portfolio/src; } location /media/ { root /home/benku/portfolio/src; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } expires $expires; }``` and is it correct location for media file? seems like my session is not preserved and that is why i am logging out settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Connection to Postgresql server on socket "/var/run/postgresql/.s.PGSQL.5432" failed. OperationalError on railway.app
I deployed my Django app on railway.app recently. After deployment, I tried to login into my app when I was confronted by this OperationalError. The Traceback looks something like this: Environment: Request Method: POST Request URL: http://optimuscore.up.railway.app/ Django Version: 4.0 Python Version: 3.10.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', 'dhule', 'solapur', 'mathfilters', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/opt/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/opt/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/opt/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection connection = Database.connect(**conn_params) File "/opt/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) The above exception (connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? ) was the direct cause of the following exception: File "/opt/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/accounting/account/views.py", line 72, in login print('fm: ', fm) File "/opt/venv/lib/python3.10/site-packages/django/forms/utils.py", line 55, in render context or self.get_context(), File "/opt/venv/lib/python3.10/site-packages/django/forms/forms.py", line … -
How to send data from list to create?
I have a problem, I would like to transfer the appropriate field parameters from one list to the form for creating something else. The names of the fields match but they are not the same in both and I would like to send only those that are the same. Example - I have a list of requests and on this list I have a button next to each record. After press the button i would like to redirect to add customer form where I will have autofill data from list request. What can I do? def add_customer_from_list(request, pk): application = Contact.objects.get(id=pk) #data from Contact list form = CustomerForm(request.POST, instance=application)#to CustomerForm if form.is_valid(): name = form.cleaned_data['name'] #same email = form.cleaned_data['email'] #same phone_number = form.cleaned_data['phone_number']#same address = form.cleaned_data['address'] dog_name = form.cleaned_data['dog_name']#same dog_age = form.cleaned_data['dog_age'] service_type = form.cleaned_data['service_type']#same (multi choice) training_place = form.cleaned_data['training_place'] contact_date = form.cleaned_data['contact_date'] source = form.cleaned_data['source'] status = form.cleaned_data['status'] notes = form.cleaned_data['notes'] customer = Customer(name=name, email=email, phone_number=phone_number, address=address, dog_name=dog_name, dog_age=dog_age, service_type=service_type, training_place=training_place, contact_date=contact_date, source=source, status=status, notes=notes) customer.save() return redirect('xxx') return render(request, 'xxx', {'form': form}) I try do somethin in view and templates -
Add an endpoint for borrowing return
I have this tasks for borrowing books in the library: Implement return Borrowing functionality Make sure you cannot return borrowing twice Add 1 to book inventory on returning Add an endpoint for borrowing books POST: borrowings//return/ - set actual return date (inventory should be made += 1) I can not understand how to make a return endpoint. book/models.py from django.db import models class Book(models.Model): COVER_CHOICES = [("HARD", "Hard cover"), ("SOFT", "Soft cover")] title = models.CharField(max_length=255) authors = models.CharField(max_length=256) cover = models.CharField(max_length=15, choices=COVER_CHOICES) inventory = models.PositiveIntegerField() daily_fee = models.DecimalField(max_digits=7, decimal_places=2) class Meta: ordering = ["title"] def __str__(self): return ( f"'{self.title}' by {self.authors}, " f"cover: {self.cover}, " f"daily fee: {self.daily_fee}, " f"inventory: {self.inventory}" ) def reduce_inventory_book(self): self.inventory -= 1 self.save() def increase_inventory_book(self): self.inventory += 1 self.save() borrowing/models.py from django.conf import settings from django.contrib.auth.models import AbstractUser from django.core.exceptions import ValidationError from django.db import models from book.models import Book class Borrowing(models.Model): borrow_date = models.DateField(auto_now_add=True) expected_return_date = models.DateField() actual_return_date = models.DateField(null=True, blank=True) book = models.ForeignKey(Book, on_delete=models.PROTECT, related_name="borrowings") user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="borrowings" ) @staticmethod def validate_book_inventory(inventory: int, title: str, error_to_raise): if not (inventory > 0): raise error_to_raise( {"book": f"There is currently no book: {title} to borrow"} ) def clean(self): Borrowing.validate_book_inventory( self.book.inventory, self.book.title, ValidationError ) … -
Request Handling at backend (Django)
I have two api endpoints 1- stockpurchases/ || stockpurchases/{id}/ 2- stockpurchases/{id}/stocks/ || stockpurchases/{id}/stocks/{id}/ So if some one want to purchase he should create a stockpurchase first and than add a stock to it and when someone POST stock I plus quantity and amount of stockpurchase. The problem is if some one call POST request consecutively for a loop the amount operation will goes incorrect. I want handle multiple request at the backend. Supose if the server gets consecutive request to perform operation how can i make others request wait till completion of first procedsed. After that second request is processed and so on. StockPurchase Model class StockPurchase(models.Model): qty = models.IntegerField(default=0) amount = models.IntegerField(default=0) Stock Model class Stock(models.Model): stockpurchase = models.ForeignKey("StockPurchase", on_delete=models.CASCADE, related_name='stocks') product = models.ForeignKey("Product", on_delete=models.CASCADE, related_name='stocks') project = models.ForeignKey("Project", on_delete=models.CASCADE, related_name='stocks') rate = models.IntegerField() def save(self, *args, **kwargs): if not self.pk: self.stockpurchase.amount += self.rate self.stockpurchase.qty += 1 self.stockpurchase.save() super().save() So if I Call like this with await no issue async function create() { for (let i = 0; i < 10; i++) { let response = await fetch( "http://localhost:8000/api/stockpurchases/2/stocks/", { method: "POST", body: bodyContent, headers: headersList, } ); } } but if call it without await async function the … -
How to style the validation error list display by changing the error class by overwriting built-in form templates. error_class errorlist ErrorList
I couldn't find an up-to-date answer, so I'll write my own solution based on the Django documentation https://docs.djangoproject.com/en/4.2/ref/forms/api/#how-errors-are-displayed. Explain: I override built-it templates of ErrorList using TemplatesSetting() which refers to the template engine. Now I can change HTML in custom templates. `from django.forms.renderers import TemplatesSetting from django.forms.utils import ErrorList class CustomErrorList(ErrorList): def __init__(self, initlist=None, error_class=None, renderer=None): super().__init__(initlist, error_class="list-group", renderer=TemplatesSetting()) template_name = "forms/errors/default.html" template_name_text = "forms/text.txt" template_name_ul = "forms/errors/ul.html" class OfferForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.error_class = CustomErrorList class Meta: model = Offer exclude = ['city', 'user', 'is_active', 'count_of_views', 'in_favorites']` settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] in ul.html: {% if errors %}<ul class="list-group">{% for error in errors %}<li class="list-group-item text-white bg-danger">{{ error }}</li>{% endfor %}</ul>{% endif %} -
Unable to reset password in Django
I have an app which allows the user to reset password. I user the django authentification system but everytime I want to send an email I get the error ' 535, b'5.7.8 Username and Password not accepted. '. I have already generated and app password and replace the password in my "settings.py" but I still get this error. -
Sort objects in django admin panel based on a charfield which also have certain characters like $, Euro Symbol, comma, etc.,
In the Django Admin panel, I want a functionality for admin that allows him to Sort the car based on price. Here price is a CharField and contains different characters other than numbers in string format. which makes it difficult to sort. I want to filter the Cars based on price but price is a string and contains characters like $, comma and Euro symbols. I don't understand how to filter this. class MostExpensiveCars(admin.SimpleListFilter): title = _("Most Expensive Cars") parameter_name = "most_expensive_cars" def lookups(self, request, model_admin): return ( ("today", _("Today")), ("yesterday", _("Yesterday")), ("this_week", _("This Week")), ) def queryset(self, request, queryset): if self.value() == "today": # get today's date today = datetime.today().date() # get the most expensive cars sold today queryset = queryset.filter(sold_on=today) if self.value() == "yesterday": # get yesterday's date yesterday = datetime.today().date() - timedelta(days=1) queryset = queryset.filter(sold_on=yesterday) # get the most expensive cars sold yesterday # return queryset if self.value() == "this_week": # get the most expensive cars sold this week seven_days_ago = datetime.today().date() - timedelta(days=7) queryset = queryset.filter(sold_on__gte=seven_days_ago) # TODO: code to filter queryset by price since the price is a string # and contains many characters like $, commas, etc. ........... @admin.register(Car) class CarAdmin(admin.ModelAdmin): list_display = [ … -
Doesn't the parent model's object of "one to one relationship" have "_set" in Django?
I have Person and PersonDetail models below which have one-to-one relationship: class Person(models.Model): name = models.CharField(max_length=20) class PersonDetail(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE) age = models.IntegerField() gender = models.CharField(max_length=20) But, when using persondetail_set of a Person object as shown below: obj = Person.objects.all()[0] print(obj.persondetail_set.all()) # ↑ ↑ Here ↑ ↑ There is the error below: AttributeError: 'Person' object has no attribute 'persondetail_set' So, I changed one-to-one relationship to one-to-many relationship as shown below: class PersonDetail(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) # ... Then, there was no error: <QuerySet [<PersonDetail: 32 Male>]> Or, I changed one-to-one relationship to many-to-many relationship as shown below: class PersonDetail(models.Model): person = models.ManyToManyField(Person) # ... Then, there was no error: <QuerySet []> So, doesn't the parent model's object of one-to-one relationship have _set in Django? obj = Person.objects.all()[0] print(obj.persondetail_set.all()) # ↑ ↑ Here ↑ ↑ -
Cannot render values in django template using for loop
So i have a zipped list inside my view and I have passed it into context like this: combined_data = zip(hostnames_list, values, values1, values2, values3, values4, values5) context = {'combined_data': combined_data} return render(request, 'base/snmp-table.html', context) but when i try to render this data into the django template like this, the data is not displayed: <table> <thead> <tr> <th>Hostname</th> <th>Value1</th> <th>Value2</th> <th>Value3</th> <th>Value4</th> <th>Value5</th> <th>Value6</th> </tr> </thead> <tbody> {% for host, val1, val2, val3, val4, val5, val6 in combined_data %} <tr> <td>{{host}}</td> <td>{{val1}}</td> <td>{{val2}}</td> <td>{{val3}}</td> <td>{{val4}}</td> <td>{{val5}}</td> <td>{{val6}}</td> </tr> {% endfor %} </tbody> </table> </table> <script type="text/javascript"> setTimeout(function () { location.reload(); }, 2 * 1000); </script> The lists which are zipped are not empty because when i do this inside my view: for host, val1, val2, val3, val4, val5, val6 in combined_data: print(host, val1, val2, val3, val4, val5, val6) I get the output in my console 10.1.1.1 not found not found not found not found not found not found 10.1.1.2 not found not found not found not found not found not found Note: 'not found' is the value inside list. Any insight please? thank you -
How to get an X from a range (1000, 0) in Django Template when you run through a for loop (0, 1000)?
Actually, I run through a regular loop: {% for post in posts %} And I need here X = 1000 then 999 then 998. {% endfor %} How to do it? Do you have any ideas? I tried: {% with x=1000 %} {% for post in posts %} {{ x|add:"-1" }} {% endfor %} {% endwith %} But it doesn't save that x. It shows 999 each time. -
How to serve two projects on same server one is django and another is django
I have created two projects one is python django and another is on Php as the backend. I want to connect its front end which is on flutter and put it on live .Suggests some ideas on how to do it. Please share some feasible ideas