Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django template get a list item using a template variable as index
Supposing a list0 with elements ['a','b','c','d'], I need to get the nth element depending on a template variable like forloop.counter0 or any other integer available from the template. So far the better way I found was to create a custom tag as explained here or here and in the django doc. Once defined you can write something like : {% for elm in list0 %} {{ elm }} {{ list1|index:forloop.counter0 }} {% endfor %} The example assumes there's another list list1, with elements ['A','B','C','D']. index is the name of the custom filter, it uses the forloop counter as an index to get each list1 element : list1[0], list1[1], list1[2], list1[3] So this generates : a A b B c C d D But what if you only want to use builtin filters ? (Or have spare time for recreative stuff ?) After some research and tests the only way I found is this odd thing : {% for elm in list0 %} {% with sl0=forloop.counter0|make_list sl1=forloop.counter|make_list %} {% with header_id=sl0.0|add:":"|add:sl1.0 %} {{ elm }} {{ list1|slice:header_id|join:"" }} {% endwith %} {% endwith %} {% endfor %} what it does : I hope I missed something in the documentation because the … -
Django forms not appearing due to Model as a field?
I am trying to make a file management system using Django but not clear how to make Model forms when there is a foreignkey in the model. Everything I have tried so far did not work. Models.py: from django.db import models from django.contrib.auth.models import User class Files(models.Model): name = models.TextField(max_length=144) contet = models.FileField(null=False) class UserFolder (models.Model): folderName = models.TextField(blank=False) files = models.ForeignKey(Files, on_delete=models.CASCADE) class UserProfile (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='pictures/%y/%m/%d/', max_length=255, null=True, blank=True) folder = models.ForeignKey(UserFolder, on_delete=models.CASCADE, blank=True) file = models.ForeignKey(Files, on_delete=models.CASCADE) Created User model where user can have folders and files. Folder model where folder contains files and at last a model for files. Forms.py: class NewFolderForm(forms.ModelForm): class Meta: model = UserFolder fields = ['folderName', 'files'] widgets = { 'folderName': forms.Textarea(attrs={'class': 'field', 'placeholder': 'folder name...'}), 'files': forms.FileInput(attrs={'class': 'field input'}) } I think the main issue lies here as i'm trying to define the files field as an file input field as files is a reference to file model; but i don't know any workarounds to this issue. Views.py: def makeFolder(request): form = NewFolderForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') context = {form: 'form'} return render(request, 'makefolder.html', context) Just saving the form if it's valid. HTML Code: … -
How I can invoke js script from django view?
In a view I have a condition that should invoke js script declared in template. Is there any way to do it? -
How do I remove the "Account" section from the Django Admin Page
I would like to remove the "Account" section from the Django Admin page. I can't figure out what model I would need to unregister(). -
Unable to open Zip file downloaded using Django
I am converting a directory and all its contents into a zip file and downloading it but when I try to open the downloaded zip file I am getting the error:- C:\Users\user1\Downloads\directory1.zip: Unexpected end of archive Here is my function for zipping and downloading the directory as a zip file in Django:- def download(request): body = request.body #fetching directory name from request body directory = body['directory'] #dir_name contains path of the directory to be converted into zip dir_name = BASE_DIR + '\\downloads\\' +"\\{0}".format(directory) #zip_file_name is the full path of the zip file which will contain the directory as a zip zip_file_name = dir + '.zip' ###Creating Zip File zipf = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED) path = dir_name ziph = zipf # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(path, '..'))) zipf.close() #Define the full file path filepath = zip_file_name #filename is the name to be given to the downloaded zip file filename = directory + '.zip' ###Download section # Open the zip file for reading content path = open(filepath, 'r', errors="ignore") # Set the mime type mime_type, _ = mimetypes.guess_type(filepath) # Set the return value of the HttpResponse response = … -
Forwarding a local port to a remote machine
I'm using Winscp trying to do a local port forwarding to a remote machine. In one putty window I run the django project on 127.0.0.1:8000, in another putty window I run the forward command ssh -L 8000:127.0.0.1:8000 -C -N -l <username> <ip> But I can't access through the browser on windows 10 at 127.0.0.1:8000 or localhost:8000. But if I try to open on mac os everything works. I tried disabling the firewall on windows 10, but it didn't help -
Django crispy-forms show all error messages on top of form
I use Django crispy-forms with tabs and bootstrap4 and everything works well. Except when I try to submit the form and there is an error on another tab: The user does not see the error and there is no visual hint that there is a validation error somewhere else on another tab. To work around this issue, I thought it would be easiest to just show all errors also on top of the form. But I didn't find any help on that so far... can someone point me in the right direction? I use Formhelper with Layout, TabHolder and Tab classes to create the tabs: form.helper = FormHelper() form.helper.layout = Layout( TabHolder( Tab( 'Basic', 'number', 'name', 'name_additional', ... -
Applying custom font to a Django email template
I'm styling a Django email template using inlinecss, but my custom font is not being applied to the email. In the css file (included using {% load inlinecss %} {% inlinecss "css/styles.css" %} in the html file), I have the following: @font-face { font-family: 'my-font'; src: url("../fonts/my-font.woff2") format("woff2"), url("../fonts/my-font.woff") format("woff"); } Any idea how I can get my custom font to get applied to the email? Thanks. -
Django unittest in Docker container : ModuleNotFoundError: No module named 'code.x'; 'code' is not a package
this is my first project with Django and also my first time using Docker. So far I'm really enjoying both of them but I'm facing a problem I couldn't resolve after a week. I followed this tutorial to build my project : https://medium.com/swlh/setting-up-a-secure-django-project-repository-with-docker-and-django-environ-4af72ce037f0 So far, my project structure looks like like this : MyProject ├── backend # Django "app" │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── permissions.py │ ├── serializers.py │ ├── tests.py │ └── views.py │ ├── config # Django "project" │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── docker # Docker configuration files, content close to the source link above │ └── ... │ ├── frontend # independent angular project │ └── ... │ ├── .gitignore └── manage.py My project is up and running fine inside the containers and everything is working as expected. Well, almost everything.. I wrote some simple tests and tried to run them from inside the "web" container (which contains the web app) and whenever i run python manage.py test i get the following errors : root@web:/code# python manage.py test System check identified no issues (0 silenced). EE … -
Django how to test model functions with validator
My models.py is looking like this: def validate_yearofbirth(value): text = str(value) if len(text) < 4 or len(text) > 4 or value < 1900: raise ValidationError('Please insert your year of birth!') class Personal(models.Model): firstname = models.CharField(max_length = 100) lastname = models.CharField(max_length = 100) yearofbirth = models.PositiveIntegerField(validators = [validate_yearofbirth], null = True) @property def fullname(self): return '{}, {}'.format(self.lastname, self.firstname) def __str__(self): return self.fullname @property def age(self): year = datetime.now().year age = year - self.yearofbirth return age Anyone know how to write a test for def validate_yearofbirth and for def age? I only managed to write a test for def fullname, but I haven't figured out how to write a test for a function which is not def __str__(self). My test_models.py file for this class is looking like this: class TestModel(TestCase): def test_personal_str(self): fullname = Personal.objects.create(nachname = 'Last Name', vorname = 'First Name') self.assertEqual(str(fullname), 'Personal Test Nachname, Personal Test Vorname') Also you can ignore the fact that return age doesn't always return the "real" age - this isn't important for my class. -
can not deploy site to heroku , showing error app not compatibe
added requirement.txt, Procfile, receving error while deploying site to heroku what could be wrong with this Enumerating objects: 110, done. Counting objects: 100% (110/110), done. Delta compression using up to 8 threads Compressing objects: 100% (106/106), done. Writing objects: 100% (110/110), 13.54 MiB | 1.30 MiB/s, done. Total 110 (delta 35), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> *App not compatible with buildpack: https://buildpack- registry.s3.amazonaws.com/buildpacks/heroku/python.tgz* remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to covidcms. remote: To https://git.heroku.com/covidcms.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/covidcms.git' -
Django POST request data object wraps string values in array
When I print the POST request object in a standard django view, the values are wrapped in an array and I don't understand why. Weird thing is if I do a GET for all objects using postman, they are not wrapped in array and appear as strings. FYI model fields are TextField NOT list. class JiraDataViewSet(BaseModelViewSet): queryset = JiraData.objects.all().order_by("-id") serializer_class = JiraDataSerializer permission_classes = [ IsAdmin, ] lookup_field = "uuid" @action(detail=False, methods=["post"]) def test_connection(self, request, *args, **kwargs): print(f'is request {request.data}') result = False if request.data: Print looks like: <QueryDict: {'jira_instance': ['https://uk-hairloom.atlassian.net/'], 'jira_board': ['TEST- board'], 'username': ['paul.macleod@uk-hairloom.net'], 'password': ['5G8K2iVx4xLp9BkpXDfx45R0'], 'ip_address': ['poc.sec-1.com', '129.0.2.3'], 'jira_prefix': ['bug'], 'customer_name': ['Example Inc.']}> Any advice much appreciated. -
Django - How to use Subquery and count
I'm trying to achive an annotated query and here's my code. # models.py STATUS_CHOICES = ( ("submitted", "제출됨"), ("in-review", "검토중"), ("rejected", "반려됨"), ("approved", "승인됨"), ) class ClassReview(models.Model): class = models.ForeignKey("class.Class", on_delete=models.PROTECT) status = models.CharField(max_length=10, choices=STATUS_CODE, default="submitted") class ClassReviewVote(models.Model): target = models.ForeignKey("class.ClassReview", on_delete=models.PROTECT) vote = models.BooleanField(null=True) # selectors.py def get_classreview_set(class_id): review_set = ClassReview.objects.filter(class_id=class_id, status="approved") review_Set = review_set.annotate( vote_up_count=Subquery( ClassReviewVote.objects.filter(target_id=OuterRef("pk"), vote=True) .values("target") .annotate(count=Count("target")) .values("count"), output_field=IntegerField(), ) ) return review_set # serializers.py def classreview_serializer(classreview): data = dict() ... data["vote_up_count"] = classreview.vote_up_count ... return data # views.py class ClassDetailView(TemplateView): ... def get(self, request, *args, **kwargs): class_id = request.kwargs.get("class_id") review_set = get_classreview_set(class_id) context = { review_list = classreview_serializer(review_set) } ... ... I want to annotate vote up count of each review. But it keeps raising Error "more than one row returned by a subquery used as an expression". When logged in user and someone else voted up. What is happening? -
Local time zone is not showing time
I am building a BlogApp and I am trying to accessing Local Time of the User , I have followed steps according to the documentation. BUT after it , it is not showing the local time of the user. settings.py MIDDLEWARE = [ 'app.middleware.TimezoneMiddleware', ] TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True middleware.py import pytz from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) views.py def set_timezone(request): if request.method == 'POST': request.session['django_timezone'] = request.POST['timezone'] return redirect('/') else: return render(request, 'template.html', {'timezones': pytz.common_timezones}) template.html {% load tz %} {% localtime on %} {{ value }} {% endlocaltime %} {% localtime off %} {{ value }} {% endlocaltime %} {% timezone "Europe/Paris" %} Paris time: {{ value }} {% endtimezone %} {% timezone None %} Server time: {{ value }} {% endtimezone %} {{ value|localtime }} I have seen answer like THIS and THIS, BUT still not showing the local time. Any help would be Appreciated. Thank You in Advance -
Get list of data on each available date in django
I am trying to build a Django app, where a user will enter daily reports. For example, on 13 April 2020, 4 Reports were made, on 14 April 2020, 6 Reports were made. The list of all reports will be divided into sub-lists based on the report date. So I want to get the list of reports in this following matter list_of_reports = { "14/04/2020": [<Report 1>, <Report 2>, <Report 3>], "15/04/2020": [<Report 4>, <Report 5>, <Report 6>], } And on my HTML view, I want to show my report in this following matter <div> <p>Date: 14/04/2020</p> <ul> <li>Report 1</li> <li>Report 2</li> <li>Report 3</li> </ul> </div> <div> <p>Date: 15/04/2020</p> <ul> <li>Report 4</li> <li>Report 5</li> <li>Report 6</li> </ul> </div> My Model class DailyReport(models.Model): report = models.CharField(max_length=500) created_at = models.DateTimeField(auto_add_now=True) @property def creation_date(self): return self.created_at.strftime('%Y:%m:%d') My Template View class DailyReportView(TemplateView): template_name = "Report/report_list.html" def get_context_data(self): context = super().get_context_data() report_list = # Here I will get the desired Report List that I want based on date context["reports"] = report_list return context -
How to run an url in views in Django?
I have a PDF uploading form. When a user sends this form I want to trigger a URL in my views. I want the invoked URL address to be opened only once in the backend. The user cannot view this page. The reason I want this is that the API I call from here enables me to do another process. How can I run an URL in my views backend? views.py def upload_pdf(request, id): if request.method == 'POST': customer = get_object_or_404(Customer, id=id) form = PdfForm(request.POST, request.FILES) if form.is_valid(): new_pdf = form.save(commit=False) new_pdf.owner = customer new_pdf.save() name = new_pdf.pdf.name.replace(".pdf", "") url = 'https://api..../perform/{0}'.format(name) return redirect('ocr', id=new_pdf.id) else: form = PdfForm() customer = get_object_or_404(Customer, id=id) return render(request, 'upload_pdf.html', {'form': form, 'customer': customer}) -
How to add custom Header in Authlib on Django
I would need some of your help adapting Authlib with Django. I'm trying to develop a Django app using OpenId and Authlib to connect my users and facing an issue with the access token, the issue invalid_client occurs. Using Postman I found out that the OpenId provider needs some parameters in the Header like 'Content-Length' or 'Host'. When the Header param is defined in client.py, it works like a charm. However, I'd like to pass the custom header from views.py (mostly to avoid defining the Host directly in the package), but authorize_access_token doesn't allow multiple arguments, def auth(request): token = oauth.customprovider.authorize_access_token(request) Maybe the "Compliance Fix for non Standard" feature might help, but I wasn't able to adapt it for Django and the Header parameter https://docs.authlib.org/en/stable/client/oauth2.html#compliance-fix-oauth2 from authlib.common.urls import add_params_to_uri, url_decode def _non_compliant_param_name(url, headers, data): params = {'site': 'stackoverflow'} url = add_params_to_uri(url, params) return url, headers, body def _fix_token_response(resp): data = dict(url_decode(resp.text)) data['token_type'] = 'Bearer' data['expires_in'] = int(data['expires']) resp.json = lambda: data return resp session.register_compliance_hook( 'protected_request', _non_compliant_param_name) session.register_compliance_hook( 'access_token_response', _fix_token_response) Does anyone know a way to pass a custom Header to Authlib or defining it using the Compliance Fix and Django? Thank in advance ! -
Selenium automated testing error: selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
I am using Selenuium to test a Django website. When I run my test, I get the following error: TypeError: 'WebElement' object is not callable Here are the relevant snippets of my code: base.py import os import sys from pathlib import Path from selenium import webdriver from selenium.webdriver.remote.remote_connection import LOGGER as SELENIUM_LOGGER, logging as selenium_logging from webdriver_manager.chrome import ChromeDriverManager sys.path.insert(0, str(Path(os.path.dirname(__file__)).parent.absolute()) ) from django.urls import reverse from django.test import TestCase from django.contrib.auth import get_user_model User = get_user_model() TESTING_URL_ROOT = os.environ.get('TESTING_URL_ROOT', 'http://127.0.0.1:8000') # https://stackoverflow.com/questions/23407142/how-do-i-reduce-the-verbosity-of-chromedriver-logs-when-running-it-under-seleniu SELENIUM_LOGGER.setLevel(selenium_logging.WARNING) # https://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class class BaseTestCases: class BaseTest(TestCase): def setUp(self): chrome_options = webdriver.ChromeOptions() chrome_options.headless = True chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("disable-infobars"); # disabling infobars chrome_options.add_argument("--disable-extensions"); # disabling extensions chrome_options.add_argument("--disable-gpu"); # applicable to windows os only chrome_options.add_argument("--disable-dev-shm-usage"); # overcome limited resource problems chrome_options.add_argument(f"user-data-dir={str(Path.home())}") # https://stackoverflow.com/questions/31062789/how-to-load-default-pro chrome_options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36") self.browser = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options) # ... def tearDown(self): self.browser.quit() # For Django client object, which can work with relative URLs def get_relative_url_from_route_name(self, route_name): route_name = route_name.strip() return f"{reverse(route_name)}" # for selenium, which requires FULL URL def get_full_url_from_route_name(self, route_name): route_name = route_name.strip() if not route_name: return TESTING_URL_ROOT else: return f"{TESTING_URL_ROOT}{reverse(route_name)}" # Default is set to True, because Selenium provides better UI testing # e.g. Javascript … -
Issue with static files when deploying Django app to Heroku
My project folder looks this: ├── Procfile ├── core │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ └── views.cpython-39.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── inspirationSources.txt ├── manage.py ├── package-lock.json ├── package.json ├── react-frontend │ ├── README.md │ ├── build │ │ ├── asset-manifest.json │ │ ├── favicon.ico │ │ ├── index.html │ │ ├── logo192.png │ │ ├── logo512.png │ │ ├── manifest.json │ │ ├── robots.txt │ │ └── static │ ├── package-lock.json │ ├── package.json │ ├── public │ │ ├── favicon.ico │ │ ├── index.html │ │ ├── logo192.png │ │ ├── logo512.png │ │ ├── manifest.json │ │ └── robots.txt │ └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── assets │ ├── components │ ├── hooks │ ├── index.css │ └── index.js ├── requirements.txt ├── spotify │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── admin.cpython-39.pyc │ │ ├── apps.cpython-39.pyc │ │ ├── cluster.cpython-39.pyc │ │ ├── credentials.cpython-39.pyc │ │ ├── models.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ ├── util.cpython-39.pyc │ │ └── … -
Django File Based Caching
In Django File Based Caching, if I create an entry, does it create individual entries for each individual process? I am creating the entry from settings.py file. Thank you -
Selenium automated testing error: TypeError: 'WebElement' object is not callable
I am using Selenuium to test a Django website. When I run my test, I get the following error: TypeError: 'WebElement' object is not callable Here are the relevant snippets of my code: base.py import os import sys from pathlib import Path from selenium import webdriver from selenium.webdriver.remote.remote_connection import LOGGER as SELENIUM_LOGGER, logging as selenium_logging from webdriver_manager.chrome import ChromeDriverManager sys.path.insert(0, str(Path(os.path.dirname(__file__)).parent.absolute()) ) from django.urls import reverse from django.test import TestCase from django.contrib.auth import get_user_model User = get_user_model() TESTING_URL_ROOT = os.environ.get('TESTING_URL_ROOT', 'http://127.0.0.1:8000') # https://stackoverflow.com/questions/23407142/how-do-i-reduce-the-verbosity-of-chromedriver-logs-when-running-it-under-seleniu SELENIUM_LOGGER.setLevel(selenium_logging.WARNING) # https://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class class BaseTestCases: class BaseTest(TestCase): def setUp(self): chrome_options = webdriver.ChromeOptions() chrome_options.headless = True chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("disable-infobars"); # disabling infobars chrome_options.add_argument("--disable-extensions"); # disabling extensions chrome_options.add_argument("--disable-gpu"); # applicable to windows os only chrome_options.add_argument("--disable-dev-shm-usage"); # overcome limited resource problems chrome_options.add_argument(f"user-data-dir={str(Path.home())}") # https://stackoverflow.com/questions/31062789/how-to-load-default-pro chrome_options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36") self.browser = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options) # ... def tearDown(self): self.browser.quit() # For Django client object, which can work with relative URLs def get_relative_url_from_route_name(self, route_name): route_name = route_name.strip() return f"{reverse(route_name)}" # for selenium, which requires FULL URL def get_full_url_from_route_name(self, route_name): route_name = route_name.strip() if not route_name: return TESTING_URL_ROOT else: return f"{TESTING_URL_ROOT}{reverse(route_name)}" # Default is set to True, because Selenium provides better UI testing # e.g. Javascript … -
Django-Channels: dictionary update sequence element #0 has length 0; 2 is required
I am working on a Django project who uses Django channels for notifications and private messages. Everything works perfectly fine when a user is connected. But when no user is connected (login and register page) I get this error: dictionary update sequence element #0 has length 0; 2 is required There is no sockets code on the anonymous page (register/login). Does anyone know the issue? Environment: Request Method: GET Request URL: http://127.0.0.1:8000/users/login/ Django Version: 3.1.5 Python Version: 3.7.3 Installed Applications: ['wall.apps.WallConfig', 'users.apps.UsersConfig', 'notifications.apps.NotificationsConfig', 'sockets', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'channels'] 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 "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 339, in thread_handler raise exc_info[1] File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 38, in inner response = await get_response(request) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 263, in _get_response_async response = await sync_to_async(response.render, thread_sensitive=True)() File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 304, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\asyncio\tasks.py", line 388, in wait_for return await fut File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\concurrent\futures\thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 343, in thread_handler return func(*args, **kwargs) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\jerem\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) … -
Initialise and increment counter with pagination notb working in django
I have a set of results that I fetch from the database and I use pagination to display 3 per page. I want the results to be formatted in a table where I get the post saying number 1 per row. Then when I hit next, it should be number 4, 5 and 6 listed in the table. However, it is not working if I use a counter. Can you guys help please? Thank youu xoxo Here is my code snippet for the template: {% with count=1 % } {% for internship, skills, emp_steps in posts %} <tr style="background-color: #F0F8FF"> <td>{{ count|add:"1" }}</td> <td>{{internship.internship_title}}</td> <td>{{ internship.posted_date }}</td> <td align="center" > <a href="{% url 'edit_internship' internship.id %}" class="btn btn-success btn- sm">Edit <i class="fa fa-pencil" aria-hidden="true"></i></a>&nbsp;&nbsp;</td> </tr> {% endfor %} {% endwith %} -
Is there a way to display the extra forms at the top when using django InlineModelAdmin instead of the bottom after all the existing forms?
Am using inlines(InlineModelAdmin) in my django Admin interface to make it easier to edit the models of the Parent model. However, by default, the extra forms for models appear at the bottom. The problem is that there may be a lot of previous records such that you have to scroll to the bottom to add a new record. Is there a way to change this default behavior such that the new extra forms appear at the top? -
user_id = getattr(user, api_settings.USER_ID_FIELD) AttributeError: 'str' object has no attribute 'id
I am trying to authenticate a user through their email using DRF but so far it's only errors i've been getting. This is the class that handles the email verification class VerifyEmail(GenericAPIView): def get(self, request): token = request.GET.get('token') try: payload = jwt.decode(token, settings.SECRET_KEY) # Decodes the user token and the secret key to get the user ID print(payload) user = User.objects.get(id=payload['user_id']) # Gotten the user ID if not user.is_verified: # Runs an if statement to see if the user has been verified already user.is_verified = True user.save() data = {"confirmation_message": "Your account has been verified"} return Response(data, status=status.HTTP_200_OK) except jwt.ExpiredSignatureError as identifier: error = {"expired_activation_link": "The activation link has expired"} return Response(error, status=status.HTTP_400_BAD_REQUEST) except jwt.DecodeError as identifier: error = {"invalid_token": "The token is invalid request a new one"} return Response(error, status=status.HTTP_400_BAD_REQUEST) and this is the error i keep getting Internal Server Error: /auth/register Traceback (most recent call last): File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 469, …