Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Simple JWT to work for all users in a django project (Not just super user)?
I've been using Simple JWT when making a project involving Django REST backend and React JS frontend. My authentication was going well until I realized that I am only getting a token when the user is a Super User in the Django app. Any other user account simply results in {"detail":"No active account found with the given credentials"} In some form another, when I try it via logging in from React, on my token/obtain page in Django, and in a curl script through command prompt. The user is labelled as active within Django admin Is there a setting I am missing? Here are my current JWT settings in settings.py: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=14), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', } -
Looping through a list of attirubutes from Django
Basically, I've learned this far that coding something the right way means you shouldn't have to copy and paste a lot.. At least from what I've read. I basically need to assign my Django model points based on a boolean statement. If True add points otherwise dont add points. The point values will change but for now I have them set as 1. I can either copy/paste as many of these are I have to record scores for or I can see if there's an easier way, so ultimately thats my question, is there an easier way? scores_bool = { 'spc': 1, 'medical': 1, 'photo_id': 1, 'presolo_test': 1, 'presolo_checkout': 1, 'endorsement_solo': 1, 'solo': 1, 'dual_xc': 1, 'inst_training': 1, 'dual_night': 1, 'tol_tower': 1, 'solo_xc': 1, 'solo_xc_150': 1, 'checkride_prep': 1, } if ppl.spc: ppl.points += scores_bool['spc'] if ppl.medical: ppl.points += scores_bool['medical'] if ppl.photo_id: ppl.points += scores_bool['photo_id'] if ppl.presolo_test: ppl.points += scores_bool['pre_solo_test'] So basically each ppl attribute has a True False statement, if true add the points to it...etc Ideally I would loop through the scores_bool.keys() and say something like: for i in scores_bool.keys(): if ppl.i: ppl.points += scores_bool[i] Thankyou! -
In Django how to convert an uploaded pdf file to an image file and save to the corresponding column in database?
I am creating an HTML template to show the cover of a pdf file(first page or user can choose one). I want Django to create the cover image automatically without extra upload. The pdf file is uploaded using Django Modelform. Here is the structure of my code models.py class Pdffile(models.Model): pdf = models.FileField(upload_to='pdfdirectory/') filename = models.CharField(max_length=20) pagenumforcover = models.IntegerField() coverpage = models.FileField(upload_to='coverdirectory/') form.py class PdffileForm(ModelForm): class Meta: model = Pdffile fields = ( 'pdf', 'filename', 'pagenumforcover', ) views.py def upload(request): if request.method == 'POST': form = PdffileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('pdffilelist') else: form = PdffileForm() return render(request, "uploadform.html", {'form': form}) def pdfcover(request, pk): thispdf = get_object_or_404(Pdffile, pk=pk) return render(request, 'pdfcover.html', {'thispdf': thispdf}) In the 'pdfcover.html', I want to use the Django template language so I can render different HTML for different uploaded pdf files. That's why I want to save the image file to the same column as the pdf file. I am new to Python, new to Django, and obviously new to stack overflow. I have tried pdf2image and PyPDF2 and I believe they all could work however I just cannot find the right code. If you guys enlighten me I will be thankful. -
Views/ forms / models. Can someone help me in it?
I tryed to add validation to ContactModel, by doing Forms.py but I went too far away with it and now dont know to fix it. Can someone help ? def addContact(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # form = Contact( # full_name = request.POST ('fullname'), # relationship = request.POST ('relationship'), # email = request.POST ('email'), # phone_number = request.POST ('phone-number'), # address = request.POST ('address'), # ) form.save() return redirect('/contact') context = {'form': form} return render(request, 'contact/new.html', context) def contactProfile(request,pk): contact = Contact.objects.get(id=pk) return render(request, 'contact/contact-profile.html', {'contact': contact}) In my opinion in Views I have big mess.. When I fill up all fields data isn't sending to database. forms.py: from django.forms import ModelForm from .models import Contact class ContactForm(ModelForm): class Meta: model = Contact fields = '__all__' models.py: from django.db import models # Create your models here. class Contact(models.Model): full_name = models.CharField(max_length=500) relationship = models.CharField(max_length=50) email = models.EmailField(max_length=254) phone_number =models.CharField(max_length=20) address = models.CharField(max_length=100) def __str__(self): return self.full_name -
How can i write expression in Django 3+?
It is an old version, how to rewrite it to new requirements? url(r'^reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', -
Django middleware doesn't working template
I implemented Django middleware for dynamic logo, site title, etc. It is working very slowly. example. When I updated my site title, it was not updated instantly. But when I server restarted It is working. this is my code class AppBasicInfo(): def __init__(self, get_response): self.site = SiteInfo.objects.first() if SiteInfo.objects.first() else "Not Implemented" self.get_response = get_response def __call__(self, request, *args, **kwargs): request.site = self.site response = self.get_response(request) return response settings file MIDDLEWARE = [ 'blog.middleware.AppBasicInfo', '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', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'blog.middleware.AppMenu', 'blog.middleware.SocialIcon', 'blog.middleware.DynamicYear', ] and I call middleware variable as my template like {{request.site.site_title}} -
Successfully deployed Django to Heroku but received application error
My application works fine on Django local server. It deployed successfully to Heroku as well. But when I go to the website, it says application error. I see a bunch of H10 and H14 error codes. I've tried updating the Procfile without the initial space. I've tried deleting and re-adding the requirements.txt file. Maybe it's something with the static files? One SO solution said delete a bunch of things from requirement.txt file that you don't need - as that worked for them. I just don't which ones to delete. I can't add my Heroku logs --tail - SO thinks recognizes it as spam. If needed, I can email it to you. Please see below: Procfile web:gunicorn myquiz.wsgi requirements.txt asgiref==3.3.1 click==7.1.2 dj-database-url==0.5.0 Django==3.1.6 django-cors-headers==3.7.0 django-heroku==0.3.1 django-nested-admin==3.3.3 djangorestframework==3.12.2 Flask==1.1.2 gunicorn==20.0.4 itsdangerous==1.1.0 Jinja2==2.11.3 MarkupSafe==1.1.1 psycopg2==2.7.7 python-decouple==3.4 python-monkey-business==1.0.0 pytz==2021.1 six==1.15.0 sqlparse==0.4.1 Werkzeug==1.0.1 whitenoise==5.2.0 Settings.py import os import django_heroku import dj_database_url from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
Google analytics for Django app only shows root domain instead of page titles
I've got my first Django app in production and would like to setup Google Analytics to see pageviews/timespent/etc by page title for the order flow. I've added the GA javascript to the of my base.html template with the hope that it would track each page with page title. However, when I look at Google Analytics, I only see page views by my root domain 'mysite.com', and I cannot get get page views by '/app/pagetitle1', '/app/pagetitle2', '/app/pagetitle3', etc. 'app' is the Django app that the root domain gets redirected to 'mysite.com/app'. I'm assuming that Google Analytics would show entire path after root domain, if it were to work. It seems like there is probably something simple I've overlooked, and would appreciate any advice. Here's the GA tag I put in base.html right after per GA instructions: <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=XXX"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'XXX'); </script> Each template extends base.html as follows: {% extends "base.html" %} {% block content %} <section class="container container-interior"> etc - rest of <body> -
Issue with updating a dictionary in for loop (not unique)
I have an issue with populating a dictionary from the database. It overwrites or merges values that from my logic should be unique to the given country. country_dict = {'Netherlands': [{'Games': {}, 'Bikes': {}, 'Paint': {}}], 'Belgium': [{'Games': {}, 'Bikes': {}, 'Paint': {}}]} for country, value in country_dict.items(): for key in value: for category in key: for channel in channel_list: if channel in channels: aggr = item_obj.filter( order_fk__order_call_fk__ship_country=country, product__parent__product_category__product_category=category, order_fk__order_call_fk__channel=channel).aggregate(Sum('retail_price')) if aggr['retail_price__sum'] != None: key[category] = {channel: round(aggr['retail_price__sum'], 2)} which gives me if i print out line for line, exactly what i want see: Netherlands Games {'retail_price__sum': None} {} Bikes {'retail_price__sum': Decimal('30.1000000000000')} {'Channel #3': Decimal('30.10')} Paint {'retail_price__sum': Decimal('56.7000000000000')} {'Channel #1': Decimal('56.70')} Belgium Games {'retail_price__sum': None} {} Bikes {'retail_price__sum': Decimal('39.7000000000000')} {'Channel #1': Decimal('39.70')} Paint {'retail_price__sum': Decimal('13.9000000000000')} {'Channel #2': Decimal('13.90')} But when I print the final dictionary it overwrites the unique Netherlands values... { "Netherlands":[ { "Games":{ }, "Bikes":{ "channel #1": "Decimal(""39.70"")" }, "Sprays":{ "channel #2": "Decimal(""13.90"")" } } ], "Belgium":[ { "Games":{ }, "Bikes":{ "channel #1": "Decimal(""39.70"")" }, "Paint":{ "channel #2": "Decimal(""13.90"")" } } ] } if I use update() instead of = if aggr['retail_price__sum'] != None: key[category].update({channel.title+str(country): round(aggr['retail_price__sum'], 2)}) it merges the two together like this: { "Netherlands":[ { "Games":{ … -
Django not showing text after extending
I am learning Django and I was extending two html files. After extending I am getting the color that I wanted but no text. Reference the examples below... base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello</title> </head> <body bgcolor="red"> {% block content %} {% endblock %} </body> </html> home.html {% extends 'base.html' %} {% block conent %} <h1>Hello {{name}}!!!!!!!</h1> {% endblock %} views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request, 'home.html', {'name': 'Bob'}) Before base.html Before base.html After base.html After base.html -
Matching query does not exist. DRF
Okay I have been at this for a while and cannot figure it out. Whenever I make a new job post I get the following error jobs.models.Positions.DoesNotExist: Positions matching query does not exist. Business Model: from django.db import models from django_google_maps import fields as map_fields from django.conf import settings User = settings.AUTH_USER_MODEL Company = settings.COMPANY_USER_MODEL class Business(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) business = models.CharField(max_length=50, unique=True) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) about = models.TextField(max_length=1000, null=True) def __str__(self): return self.business Job Model: from django.db import models from django_google_maps import fields as map_fields import uuid as uuid_lib from django.conf import settings User = settings.AUTH_USER_MODEL class Positions(models.Model): position = models.CharField(max_length=100) def __str__(self): return self.position class Job(models.Model): employer = models.ForeignKey(User, on_delete=models.CASCADE) business = models.ForeignKey('business.Business', related_name='jobs', on_delete=models.CASCADE) position = models.ForeignKey(Positions, on_delete=models.CASCADE) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4, editable=False) job_detail = models.TextField() # TODO: set length full_time = models.BooleanField(default=False) part_time = models.BooleanField(default=False) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address Job Serializer: from rest_framework import serializers, fields from .models import Job, Type, Positions def get_business_model(): return django_apps.get_model(settings.BUSINESS_MODEL, require_ready=False) Business = get_business_model() # Position Serializer class PositionSerializer(serializers.ModelSerializer): class Meta: model = Positions fields = "__all__" class JobSerializer(serializers.ModelSerializer): date_posted = serializers.DateTimeField(read_only=True, … -
I am getting Internal server error when my app is deployed on heroku
I am still a beginner and some errors which appear I do not understand it, thank you for helping me pleaseenter code here i get this error when i run heroku logs --apps myapp 2021-02-04T19:02:55.752352+00:00 app[web.1]: url = self.url(context) 2021-02-04T19:02:55.752352+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/templatetags/static.py", line 103, in url 2021-02-04T19:02:55.752352+00:00 app[web.1]: return self.handle_simple(path) 2021-02-04T19:02:55.752353+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/templatetags/static.py", line 118, in handle_simple 2021-02-04T19:02:55.752353+00:00 app[web.1]: return staticfiles_storage.url(path) 2021-02-04T19:02:55.752353+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 147, in url 2021-02-04T19:02:55.752354+00:00 app[web.1]: return self._url(self.stored_name, name, force) 2021-02-04T19:02:55.752354+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 126, in _url 2021-02-04T19:02:55.752354+00:00 app[web.1]: hashed_name = hashed_name_func(*args) 2021-02-04T19:02:55.752354+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 417, in stored_name 2021-02-04T19:02:55.752355+00:00 app[web.1]: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) 2021-02-04T19:02:55.752355+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'store/css/stylee.css' 2021-02-04T19:02:55.752355+00:00 app[web.1]: 2021-02-04T19:02:55.752356+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2021-02-04T19:02:55.752356+00:00 app[web.1]: 2021-02-04T19:02:55.752356+00:00 app[web.1]: Traceback (most recent call last): 2021-02-04T19:02:55.752357+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner 2021-02-04T19:02:55.752357+00:00 app[web.1]: response = get_response(request) 2021-02-04T19:02:55.752357+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/deprecation.py", line 114, in call 2021-02-04T19:02:55.752358+00:00 app[web.1]: response = response or self.get_response(request) 2021-02-04T19:02:55.752358+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 49, in inner 2021-02-04T19:02:55.752358+00:00 app[web.1]: response = response_for_exception(request, exc) 2021-02-04T19:02:55.752358+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 103, in response_for_exception 2021-02-04T19:02:55.752359+00:00 app[web.1]: response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 2021-02-04T19:02:55.752363+00:00 app[web.1]: File … -
Django-Virtual env
scripts folder is not available in my virtual environment folder.Any one please help me How to activate virtual env ? I did following commonds :- pip3 install virtualenv virtualenv bg cd bg cd scripts shailesh@shailesh:~/Blog/bg$ cd scripts bash: cd: scripts: No such file or directory shailesh@shailesh:~/Blog/bg$ -
Django TabularInline radio button
I have a situation where a person can be added with multiple addresses. But the user should select only which one is the default address. I'm thinking to add a radio button but not sure how. Current UI -
ModuleNotFoundError: No module named '____' - Django
Im trying to import my Django models into another script so I can create extra functions for importing csv data etc. Everything ive seen online suggests I run these lines before importing my models: import os, sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projdir.proj.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from project.app.models import Model But this returns: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'app' Ive also got init.py files in both the project folder and app folder?? Can someone explain what's going on? Thanks -
Users become unvisible in users category when i remove the thick from the boolean field button
When i remove the thick from the 'Referans Kodu Doğrulaması', users become unvisible in admin panel. I've tried almost every parameters of BooleanField but i couldn't change the situation. I thought former migrations result it altough i changed it too but nothing changed. Admin Panel models.py admin.py -
Django-filter: error: Enter a list of values when using the LinkWidget
Perhaps one of you could help me out with “Django-filter”. In my template an error shows up 'Enter a list of values’ when I want to use the LinkWidget. When I use the LinkWidget with django_filters.AllValuesMultipleFilter then in my template it shows the word "all" and the ID’s of te field categories When I use it with the Django Form widget “widget=forms.CheckboxSelectMultiple)” then I’m able to filter the data. What’s wrong with my code? Thanks. Krgds. # file: filters.py from portfolio.models import Project,Category,Client import django_filters from django_filters.widgets import LinkWidget from django import forms # error: Enter a list of values. class ProjectFilter(django_filters.FilterSet): categories = django_filters.ModelMultipleChoiceFilter(queryset=Category.objects.all(),# this a ManyToManyField widget=django_filters.widgets.LinkWidget) class Meta: model = Project fields = ['categories' ] # shows "all" and the ID’s of te field categories class ProjectFilter(django_filters.FilterSet): categories = django_filters.AllValuesMultipleFilter(widget=django_filters.widgets.LinkWidget) class Meta: model = Project fields = ['categories' ] -
not able to understand Django pagination code
related to pagination it is running fine i have mentioned my problem below <nav aria-label="Page navigation example"> <ul class="pagination-sm"> <ul class="pagination"> <li class="page-item"> {% if users.has_previous %} <a class="page-link" href="?page={{ users.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> {% endif %} </a> </li> {% for i in users.paginator.page_range %} {% if users.number == i %} <li class="page-item active"><a class="page-link">{{ i }}</a></li> {% elif i > users.number|add:'-4' and i < users.number|add:'4' %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} <li class="page-item"> {% if users.has_next %} <a class="page-link" href="?page={{ users.next_page_number }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> {% endif %} </a> </li> </ul> i do not understand this line given below....how it can be possible that this condition will true for any value of "i" or for any value of "user.number" please i request to explain this line in detail {% elif i > users.number|add:'-4' and i < users.number|add:'4' %} -
Django tables2, select row and get selected values
I Have a class based view, where I display crispy form and table, so i can use the form, and see the model object in the table. My problem its that i want to select one or more items from the table, and then pass the values of the row to the crispy form. tables.py class ResultCenterTable(tables.Table): selection = tables.CheckBoxColumn(accessor='pk') class Meta: model = ResultCenter row_attrs = { "data-id": lambda record: record.name } fields = [ 'code', 'name', 'year', 'company', ] In my table I use selection to have a checkbox column so I can select, but it don't get the data of the row HTML Template <div class="container-fluid mt-5 align-items-center w-85"> <div class="card shadow align-items-center"> <div class="card-header" style="width: 100%;"> <h2>Centro de resultados</h2> </div> <div class="card-body w-100" > {% crispy form %} </div> </div> <br> <form method='GET'> {{ filter.form }} <input type='submit' value='Buscar' /> <a href='{{ request.path }}' >Limpiar</a> </form> <form method="get"> {% csrf_token %} {% render_table table %} <input type="submit" value="Importar"/> </form> </div> Views.py class ResultCenterList(ListView, FormView): model = ResultCenter form_class = ResultCenterForm success_url = reverse_lazy('maintainers:result_center') success_message = 'Centro importado correctamente' template_name = 'maintainers/user/result_center_list.html' def get_context_data(self, **kwargs): context = super(ResultCenterList, self).get_context_data(**kwargs) filter = CompanyFilter(self.request.GET, queryset=self.object_list) table = ResultCenterTable(filter.qs) django_tables2.RequestConfig(self.request, … -
Django how to set (return) default values for values_list if an object not exists?
I want to set an empty string for each field in specified values_list if the object not exists. Example code 1: data = list(MyClass.objects\ .values( "field_1", "field_2", "field_3")\ .filter(id__in=(1, 2,))\ .values_list( "field_1", "field_2", "field_3")) Example output 1: [('obj_1_val_1', 'obj_1_val_2', 'obj_1_val_3'), ('obj_2_val_1', 'obj_2_val_2', 'obj_2_val_3')] In case 1: The objects with id 1 and 2, both exists. Then we'll to have a list with 2 tuples. Example code 2: data = list(MyClass.objects\ .values( "field_1", "field_2", "field_3")\ .filter(id__in=(1, 3,))\ .values_list( "field_1", "field_2", "field_3")) Example output 2: [('obj_1_val_1', 'obj_1_val_2', 'obj_1_val_3')] In case 2: Just the object with id 1 exists. The object with id 3, NOT exists. Then we'll to have a list with 1 tuple. Then if some object(s) not exists, I want to return like this: [('obj_1_val_1', 'obj_1_val_2', 'obj_1_val_3'), ('', '', '')] -
Reload django variable with ajax
I would like to change the value of a django variable with Ajax from template. View.py def myview(request): myvariable = 'initial' if request.POST: myvariable = 'success' return JsonResponse('OK', safe=False) return render(request, 'template.html') template.html: <div id="variable">{{myvariable}}</div> <input id="button" type="submit" value="click here"/> <script> $("#button").submit(function () { $.ajax({ method:'POST' success: function () { $("#variable").load(location.href+" #variable>*",""); } }); } </script> the POST request is well received by django and the value is change successfully however the value in the template don't change. Any idea ? Strange things, I noticed after the POST request there is two GET request at the same time [05/Feb/2021 18:28:16] "POST /test HTTP/1.1" 200 4 [05/Feb/2021 18:28:16] "GET /test HTTP/1.1" 200 24388 [05/Feb/2021 18:28:16] "GET /test HTTP/1.1" 200 24388 -
django delete_offer() missing 1 required positional argument: 'id'
This is my first django project where I want to implement crud functions. I have an issue when I want to implement the delete function. Any help is appreciated! error: TypeError at /dashboard/ delete_offer() missing 1 required positional argument: 'id' html: <td class="btn column2"><a href = "{% url 'delete' contact.id %}" >Del</a></td> view: def delete_offer(request, id): delete_pon = Contact.objects.get(id = id) delete_pon.delete() return redirect('dashboard') urls: path('dashboard/', delete_offer, name = 'delete'), -
How to make a block to appear on the page after 3 seconds? CSS
I am working on developing a website using Python's Django framework. At the frontend part, I am trying to make a division block to appear 3 seconds after you have accessed the page. I'll share with you my code: .computerScienceContent{ text-align: center; display: block; position: relative; margin-top: 10px; margin-bottom: 50px; width: 700px; margin-left: auto; margin-right: auto; padding: 30px; padding-left: 20px; animation-delay: 2s; animation: 1s linear 1s slideInLeft; } The above cod is used for displaying the block. This code is used to display it from left to right. @keyframes slideInLeft { 0% { transform: translateX(-100%); } 100% { transform: translateX(0); } } This is the django code from the html that I am trying to displaying with delay. <div class="computerScienceContent"> {% for cat in category %} <div class="csDivContent" id="slide"> <div id="slide"> <h4>{{ cat.name }}</h4> <img src="{{ cat.img.url }}" alt="image" class="img"> </div> </div> {% endfor %} </div> Basically, I want the block to be displayed 3 seconds after I access the website, one entry at a time, from left to right (there are only 4 entries). If anybody can help, I will be very happy! Thank you so much for your time ! -
Override Django model save method with many-to-many relations
I tryed to fill automatically field 'final_price' in model Cart but it doesn't change to nessasary value(in Admin) when I save it. But when I save created object again, it works. What should I do to save it immidiately when obj is created? class Cart(models.Model): owner = models.ForeignKey(User, verbose_name='Владелец корзины', on_delete=models.CASCADE) products = models.ManyToManyField(CartProduct, verbose_name='Продукты', blank=True, related_name='related_cart') total_products = models.PositiveIntegerField(default=0, verbose_name='Кол-во продуктов') final_price = models.DecimalField(max_digits=9, decimal_places=2, default=0, verbose_name='Общая цена корзины') def save(self,*args,**kwargs): if not self.id: super(Cart,self).save(*args,**kwargs) self.final_price = sum([fp.final_price for fp in self.products.all()]) super(Cart,self).save(*args,**kwargs) -
Method based admin filter
I would like to filter Events by a number of registered users. So I created method in EventAdmin class, which returns number of registered users. #admin.py @admin.register(Event) class EventAdmin(admin.ModelAdmin): list_display = ('name','registered_users') list_filter = ('registered_users') def registered_users(self, obj): link = reverse("event-users", args=[obj.id]) return format_html('<a href="{}">{}</a>', link, obj.user.all().count()) If I remove property “registered_users”from list_filter project works fine. But when I want to have also filter for registered users and I add “registered_users” to list_filter I get the following error: <class 'web.admin.EventAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'registered_users', which does not refer to a Field. How can I solve this issue?