Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django throws MultiValueDictKeyError(key) error while recieving data with POST method
When I tried to pass the data using POST method. Django throws an error. The error is raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'fulldesc' I used postman to send post request. The data I have sent is as below IPHONE: 700 SAMSUNG: 600 ============= WALMART IPHONE: 699 =========== ALIBABA SONY: 500 ======``` The code I used is as below. What is the reason for error? def addData(request): if(request.method =='POST'): fulldesc = str(request.POST['fulldesc']) return HttpResponse('Done') -
Django throws MultiValueDictKeyError(key) error while recieving data with POST method
When I tried to pass the data using POST method. Django throws an error. The error is raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'fulldesc' I used postman to send post request. The data I have sent is as below IPHONE: 700 SAMSUNG: 600 ============= WALMART IPHONE: 699 =========== ALIBABA SONY: 500 ======``` The code I used is as below. What is the reason for error? def addData(request): if(request.method =='POST'): fulldesc = str(request.POST['fulldesc']) return HttpResponse('Done') -
unable to find some .py files of apps in django project
I want to ask about how can I access all ".py files" of all apps in my Django project. Actually, my developer is not responding to me I don't know why the last time he gave me my Django project in zip file. I have installed it successfully in my mac but now he is not responding to me but I have to work on the project by myself so I am worried about my Project. I have taken a screenshot of my project directory structure enter image description here installed apps portion of base.py file of settings looks like this. DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', ] THIRD_PARTY_APPS = [ 'rest_framework', 'polymorphic', #'django_extensions', 'apps.cabinet_extension.apps.CabinetConfig', #'cabinet', 'imagefield', 'easy_thumbnails', 'ckeditor', 'ckeditor_uploader', 'nested_inline', ] PROJECT_APPS = [ 'apps.core', 'apps.blog', 'apps.faq', 'apps.carty', 'apps.cart', 'apps.accounts.apps.UserConfig', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + PROJECT_APPS And the URL pattern of urls.py file of azapp looks like this path('super-admin/', admin.site.urls), path('accounts/login/', auth_views.LoginView.as_view()), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('apps.core.urls')), path('blog/', include('apps.blog.urls')), path('faqs/', include('apps.faq.urls')), path('product/', include('apps.carty.urls')), path('cart/', include('apps.cart.urls')), please help me I am so worried about it Thanking in advance! -
Django unit-Testing authorization for API
I am using Django==3.0.3 djangorestframework==3.11.0 python ==3.6.8 django-oauth-toolkit==1.3.2 I already write my rest APIs . Now I want to write my Unit Test case but while writing test cases it showing unauthorized error Here my code tests.py import unittest from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse # Models imported from django.utils import timezone from end_device.models import Employee from oauth2_provider.models import Application, AccessToken, RefreshToken from rest_framework import status from django.test import Client class MyTestCase(TestCase): def setUp(self): self.client = Client() self.create_employee = Employee.objects.create(EmployeeName="Testcase2", EmployeeCode="1005", Security=0) self.user = User.objects.create_superuser(username="fdp", password="user12345") self.user_staff = User.objects.create_user(username="user", password="user12345") self.application = Application.objects.create( name="Test Application", user=self.user, client_id="123", client_secret="12345abc", client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_PASSWORD, ) self.access_token = AccessToken.objects.create( user=self.user_staff, scope="read write groups", expires=timezone.now() + timezone.timedelta(seconds=3000), token="123efrwasdd", application=self.application ) self.refresh_token = RefreshToken.objects.create( user=self.user_staff, token="refresh_token", application=self.application, access_token=self.access_token ) def test_employee(self): inputData = { "EmployeeName": "TestEmp", "EmployeeCode": "1007", "Security": 0 } header = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + format(self.access_token.token), } url = reverse('employee_entry') resp = self.client.post(url, data=inputData, headers=header) self.assertEqual(resp.status_code, status.HTTP_200_OK) My views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def employee_entry(request): try: login = User.objects.get(pk=request.user.id) validationmsg = '' emp_data = request.data employee = Employee( EmployeeName=emp_data["EmployeeName"].strip(), EmployeeCode=emp_data["EmployeeCode"].strip(), Security=emp_data["Security"], CreatedDate=date.today(), CreatedUser=login, ) employee.save() return Response({"EmployeeId": employee.EmployeeId}, status=status.HTTP_200_OK) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) … -
Paginator in a view function Django
I'm trying to add the paginate option on my posts page from my blog website. I want to implement the paginator on my view function that renders the page and I found this exemple from Django's doc but it doesn't work. Any help ? view function: def blog(request): posts = Post.objects.all().order_by('-date_posted') paginator = Paginator(posts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts, 'page_obj': page_obj, 'title': 'Blog', 'banner_page_title': 'Blog', 'page_location': 'Home / Blog' } return render(request, 'blog/blog.html', context) html rendering <nav class="blog-pagination justify-content-center d-flex"> <ul class="pagination"> {% if is_paginated %} {% if page_obj.has_previous %} <li class="page-item"> <a href="?page={{ page_obj.previous_page_number }}" class="page-link" aria-label="Previous"> <span aria-hidden="true"> <span class="ti-arrow-left"></span> </span> </a> </li> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <li class="page-item active"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <li class="page-item"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"> <a href="?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next"> <span aria-hidden="true"> <span class="ti-arrow-right"></span> </span> </a> </li> {% endif %} {% endif %} </ul> </nav> the url route path('blog/', blog, name='blog'), -
Django createview m2m not saving
Trying to add the creator of team to the members automatically. Team model has a m2m relationship with UserProfile as members, here is the code: class CreateTeamView(generic.CreateView): model = Team template_name = 'team_create.html' fields = ('title', 'code', 'coordinator', 'description', 'members') success_url = '/teams' def form_valid(self, form): instance = form.save(commit=False) if not instance.creator: instance.creator = self.request.user.userprofile instance.save() instance.members.add(instance.creator) form.save_m2m() return super().form_valid(form) But it doesn't work. Team gets created and also the creator is assigned but doesn't get added to members. Please enlighten me. -
Django-admin start project <name> creates old version django project
I created a directory "DjangoProject1" and in it created django project through the terminal with the line $ django-admin startproject project As I was expected, there were created two things in the directory "project": file "manage.py" and another directory "project". The problem is that in that directory "project" there were: {init, setting, urls, wsgi}.py, but there wasn't file "asgi.py". From there I understood that there was created an old version django project. Again! I checked it one more time in "urls.py" file and I saw this: urlpatterns = [ url(r'^admin/', admin.site.urls), ] instead of this: urlpatterns = [ path('admin/', admin.site.urls), ] So it is definitely an old version of django project. I don't know why this problem occurs, as I installed a new version of django, and I was able to create new version django project, though I don't remember how I was doing that. Can anyone help me to liquidate this problem so that only new version django projects would be created? (PS before new version maybe I installed an old version, and probably in my computer now there are both: new and old versions of Django) -
Django Rest Framwork - Put FileField value into response
in my Django Rest Framwork project, I have the following view: class RegistrationView(APIView): def post(self, request, format=None): data = {} # check if email exists ... # check if username exists ... # at this point, we know everything is ok -> the serializer can do its work serializer = RegistrationSerializer(data = request.data) if serializer.is_valid(): account = serializer.save() data['response'] = 'registered new user' data['id'] = account.id data['email'] = account.email data['username'] = account.username data['profile_pic'] = account.profile_pic <--- HERE the problem occurs!! data['date_joined'] = account.date_joined token = Token.objects.get(user=account) data['token'] = token.key else: data = serializer.errors return Response(data) I tried to put the result of the registration process into data dictionary which is then returned as response to the user. But in the line where I have data['profile_pic'] = account.profile_pic an exception occurs stating this: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte The profile_pic field of the Account model is a FileField as you can see in the following: class Account(AbstractBaseUser): ... profile_pic = models.FileField(upload_to='Images/',default='Images/None/placeholder.jpg') How can I get the value of the FileField which basically points to the profile picture of the Account. -
Will there be any performance improvement when accessing objects this way in django ORM?
I have two models which contain ForeignKey from one to another. class M1(models.Model): name = models.TextField() class M2(models.Model): name = models.TextField() parent = models.ForeignKey(M1, related_name='children') I'm refactoring the code to improve performance. Will there be any performance difference between these 2 ORM queries. m1 = M1.objects.get(id=1) children = m1.children.all() and children = M2.objects.filter(parent_id=1) -
Django form with variable type
How would you make a price field in Django form? The input could be either price (float) or value from select (for free, offer, by agreement, etc). In database, it's stored in FloatField (negative values has special meaning). Is there a way to make it through Django form model? -
django passing a csv to another function that downloads this csv
i'm trying to pass a pandas dataframe (changed to csv file) to another fucntion(the download function) in django. the user should push a button and the dataframe(in csv format) should be ready to download for the user. i'm getting a missing 1 required positional argument: 'x' error. i've looked around on Stack but could not find an answer for this question. I think the problem is located in the def export because of the error I've got. but i've no idea how to fix it. views.py def result(request): if request.method =='POST': # some code to create the dataframe def process_file(file): data = file return data.to_csv x = process_file(df) #df for the dataframe created above return render(request, 'results.html', {'somedata':somedata,}), x def export(request, x): csv = x response = HttpResponse(csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="export.csv"' return response -
Django Log to Telegram is not working and not creating model table
So, I have been working on utilizing this package: https://pypi.org/project/django-log-to-telegram/ I went through the exact steps the manual has: pip installing django log to telegram package, Added the telegram bot token after creating the telegram bot LOG_TO_TELEGRAM_BOT_TOKEN = '1489551033:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' And adding LOGGING onto the settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, }, 'handlers': { 'telegram_log': { 'level': 'ERROR', 'filters': [], 'class': 'django_log_to_telegram.log.AdminTelegramHandler', 'bot_token': LOG_TO_TELEGRAM_BOT_TOKEN, }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['telegram_log'], 'level': 'ERROR', 'propagate': True, }, }, } Then I ran 'python manage.py migrate' to create the django-log-to-telegram models. It's supposed to create the django-log-to-telegram table in the database. However, I do not see any new database. -
Exclude by table name - django
I have raw query: select n.nspname as table_schema, c.relname as table_name from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.relkind = 'r' and n.nspname not in ('information_schema','pg_catalog') and c.reltuples = 0 order by table_schema, table_name; which return all empty tables and I saved table names to models array. Now I would like exclude models from queryset: ContentType.objects.all().exclude(table_name__in=models) but I havn't access to table name in queryset. How can I do it? -
use django model's field value inside href tag in template
Here the issue that I am facing. Let's say I have a model with two field. Field1 is a string value and Field2 one contains a url link. I want to render Field1 and the user can click on Field1 and gets redirected to template at Field2 url. Here is what I have been trying: <td>{{class.Class}}<a href="{{ class.extra_details_view }}"></a></td> #class = Field1 #extra_detail_view = Field2 (link) this renders Class values just fine but does not let me click it. I don't know what else to try to get the desired output. -
My code fail to loop the single card on the template but the entire thing works fine
Hi there! this code fail to for loop in </d {% for user in userprofile %} {{ user.userprofile.title}} R{{ user.userprofile.price }} Mobile Phones » Brand {{ user.userprofile.publish_date}} {{ user.userprofile.City }} {% endfor %} my views class ClassifiedsView(ListView): model = UserProfile paginate_by = 10 # if pagination is desired template_name = 'all_classifieds.html' def get_context_data(self): context = super().get_context_data() objects = UserProfile.objects.all() context['object'] = objects return context then temple i call it a temple it work but can't for-loop and on my urlemphasized text class UserProfile(models.Model): user = models.OneToOneField(User, null='True', blank='True',related_name='userprofile' ,on_delete=models.CASCADE) title = models.CharField(max_length=120, blank=True,)path('<all_classifieds>/', ClassifiedsView.as_view(), name='all_classifieds'), any suppurt -
Error with Django Class 'City' has no 'objects' member
I'm learning Django and having a blast, I'm trying to build a weather app using Django and the Open Weather API. I seem to have run into an error that's making my head spin and I can't figure it out, I am trying to return a list of all the data in the database but I get this error Class 'City' has no 'objects' member" Here is my models.py file from django.db import models class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name And here is my views.py file import requests from django.shortcuts import render from .models import City from .forms import CityForm def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q{}&units=imperial&appid=YOUR_API_KEY' if request.method == 'POST': form = CityForm(request.POST) form.save() form = CityForm() cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temperature' : r['main']['temp'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) context = {'weather_data' : weather_data, 'form' : form} return render(request, 'weather/weather.html', context) Any help will be greatly appreciated! -
Django RecursionError: maximum recursion depth exceeded while building a query
I am trying to build complex query this way: q = Q() if contacts: for contact in contacts: q |= Q(phone__icontains=contact) for contact in contacts: q |= Q(email__icontains=contact) if name: q |= Q(full_name__icontains=name) duplicates = Candidate.objects.filter( q ).values_list('pk', flat=True) But I get RecursionError: maximum recursion depth exceeded on this area. Not sure, what part of these code is recursive, and have no idea where to look for answer. -
Where is this self.add_error adds the error to?
I'm having a hard time trying to figure out the following code: from django import forms from django.contrib.auth.hashers import check_password class CheckPasswordForm(forms.Form): password = forms.CharField(label='password_check', widget=forms.PasswordInput( attrs={'class': 'form-control',}), ) def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user def clean(self): cleaned_data = super().clean() password = cleaned_data.get('password') confirm_password = self.user.password if password: if not check_password(password, confirm_password): self.add_error('password', 'password is wrong') here, I don't get the self.add_error('password', 'password is wrong') part. In the documentation, it says that the password here is the field in add_error('field', 'error'). So, is the error being added to the password field? or is it being added to the following part? def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user because if I have to access this error in the html template, I would have to do something like this, {% if password_form.password.errors %} and if it means accessing errors from password field, it should mean that the error is added to the password field... but the self.add_error part confuses me -
I am not able to link pages in Django
I believe I have linked my urls, views and templates very well but I don't why I am getting the error. urls.py from django.urls import path from .views import * urlpatterns = [ path('', home, name='home'), path('legal/', legal, name='legal') ] views.py from django.shortcuts import render # Create your views here. def home(request): return render(request,'base/base.html') template <nav class="nav-menu d-none d-lg-block"> <ul> <li><a href="{% url 'home' %}">Inicio</a></li> <li><a href="{% url 'about' %}">Quienes somos</a></li> </ul> </nav> -
XML error while visiting the localhost:8000/sitemaps.xml | Django
When I visit the localhost:8000/sitemap.xml It shows This XML file does not appear to have any style information associated with it. The document tree is shown below. The tree <urlset> <url> <loc>http://127.0.0.1:8000/en/product/detail/health-and-care/beauty/cream/dcaad0bb-4e30-4166-b447-508e6ad12ddf/</loc> <lastmod>2020-11-16</lastmod> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> </urlset> Where I expected this tree to be more like this <?xml version="1.0" encoding="utf-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://127.0.0.1:8000/en/product/detail/health-and-care/beauty/cream/dcaad0bb-4e30-4166-b447-508e6ad12ddf/</loc> <lastmod>2020-11-16</lastmod> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> </urlset> I have followed the django documentation as well as seen other websites. But every time I get the same result. Can you please help. How can I remove the XML error and show my xml like this <?xml version="1.0" encoding="utf-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://127.0.0.1:8000/en/product/detail/health-and-care/beauty/cream/dcaad0bb-4e30-4166-b447-508e6ad12ddf/</loc> <lastmod>2020-11-16</lastmod> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> </urlset> settings.py INSTALED_APPS = [ # # "django.contrib.sites", "django.contrib.sitemaps", # # ] SITE_ID = 1 sitemaps.py from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse from .models import Product # Inherting the Sitemap class of the sitempas module. class ProductSitemap(Sitemap): # These two attributes indicate the change frequency # and the relevencae in the webiste. changefreq = 'weekly' priority = 0.9 def items(self): # This method return the QuerySet of objects # to include in the sitemap products = Product.objects.all() products = products.prefetch_related('seller_product') return products def lastmod(self, obj): # receives each object returned by … -
GIS plugin in Django is throwing openssl error. undefined symbol: EVP_md2
I am trying to use the Geodjango plugin django.contrib.gis for my project. But as soon as I add it to the INSTALLED_APPS I am getting the following traceback. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/ec2-user/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/admin/__init__.py", line 5, in <module> from django.contrib.gis.admin.options import GeoModelAdmin, OSMGeoAdmin File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/admin/options.py", line 2, in <module> from django.contrib.gis.admin.widgets import OpenLayersWidget File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/admin/widgets.py", line 3, in <module> from django.contrib.gis.gdal import GDALException File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/gdal/__init__.py", line 28, in <module> from django.contrib.gis.gdal.datasource import DataSource File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/gdal/datasource.py", line 39, in <module> from … -
How to implement Search/Filter and Pagination in FBV
I am trying to implement Search Functionality and Pagination for Django based (model) table.1. At a time only one is working please find the views.py and I am not able to figure out how to manage logically in views.py so that both of them work together. Views.py from .filters import ShiftChangeFilter from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def retrieve_view(request): # if not request.user.email.endswith('@apple.com'): # return redirect('/logout') # post_list = ShiftChange.objects.all() # for pagination allgenesys = ShiftChange.objects.all() paginator = Paginator(allgenesys,10) page_number = request.GET.get('page') try: allgenesys = paginator.page(page_number) except PageNotAnInteger: allgenesys = paginator.page(1) except EmptyPage: allgenesys = paginator.page(paginator.num_pages) # allgenesys = ShiftChange.objects.filter(EmailID=request.user.email) #For filtering using 'django_filters', genesys_list = ShiftChange.objects.all() genesys_filter = ShiftChangeFilter(request.GET, queryset=genesys_list) allgenesys = genesys_filter.qs return render(request, 'apple/shift2.html', {'allgenesys': allgenesys,'genesys_filter':genesys_filter}) pagination.html <style> .pagination { float: left; </style> {% if page.has_other_pages %} <ul class="pagination"> {% if page.has_previous %} <li><a href="?page={{ page.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in page.paginator.page_range %} {% if page.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page.has_next %} <li><a href="?page={{ page.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif … -
Custom login using Django user model
I'm trying to make my custom login form using Django's user template. What i'm trying to do is the authentication of a user using username and password. Register works, every user is registered correctly, but when i'm trying to login using the correct fields, my: user = authenticate(request, username=username, password=password) returns None as value. Here is my def login_view in views.py (i'm using logger to know what is going on) def login_view(request): import logging logging.basicConfig(filename='mylog.log', level=logging.DEBUG) logging.debug('start') title = 'LOGIN' form = UserLoginForm() if request.user.is_authenticated: return redirect('board.html') if request.method == 'POST': form = UserLoginForm(request=request, data=request.POST) username= request.POST.get('username') password= request.POST.get('password') print(form.errors) if form.is_valid(): logging.debug('form is valid') logging.debug('called form.save(), result=%s', UserLoginForm) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) user = authenticate(request, username=username, password=password) logging.debug('user, result=%s', user) #### if user is not None: login(request, user) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) messages.info(request, "You are now logged in as {username}") return redirect('board.html') else: messages.error(request, "Invalid username or password.") logging.debug('first else') return redirect('/') #### else: print(form.errors) logging.debug('errore form: , result=%s', form.errors) messages.error(request, "Invalid username or password.") logging.debug('second else') username = request.POST.get('username') password = request.POST.get('password') messages.error(request, "Invalid username or password.") logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) return redirect('/') return render(request=request, template_name="login.html", context={"form": form , "title":title}) And that's … -
i want to count the number of correct answers in jS or jquery
I want to count the number of correct answers and display it.i tried many ways but couldn't go through.will appreciate if anybody can help me .Thanks in advance. {% extends 'base.html' %} {% block title%}Quiz{% endblock title %} {% block content %} <div class=" text-danger mt-5 text-center"> <!-- <h2><b id="count">Timer</b></h2> --> <h3>+++Quiz on Indian Politics+++</h3> <hr> </div> <div class="pt-5"> {% for item in obj %} <table> <tr> <h2>Q{{item.id}}. {{item.question}}</h2><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt1" value="{{item.opt1}}">&nbsp;{{item.opt1}}</input><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt2" value="{{item.op2}}">&nbsp;{{item.opt2}}</input><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt3" value="{{item.opt3}}">&nbsp;{{item.opt3}}</input><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt4" value="{{item.opt4}}">&nbsp;{{item.opt4}}</input><br> </tr> <tr> <label id="lb" class="rd" name="{{item.id}}" value="{{item.cor_ans}}" style='display:none;color:green'><b>The correct answer is: {{item.cor_ans}}</b></label> </tr> <tr> </tr> </table> <hr> {% endfor %} <div class="pt-4"> <button type="submit" class="btn btn-success" id="btn">Submit</button> </div> <div class="pt-3"> <b id="counter"></b> <b id="ans"></b> </div> </div> {% endblock content %} {% block scripts %} <script> const rad = document.getElementsByClassName('rd') const input = document.getElementsByTagName('input') const bt = document.getElementById('btn') const label = document.getElementsByTagName('label') const counter = document.getElementById('counter') var score = 0; bt.onclick = function() {} // JQuery code $(document).ready(function() { $('#btn').click(function() { $('.rd').show(); $('.rd').attr("disabled", true); }); }); // # javascript code bt.addEventListener('click', function() { for (i = 0; i < input.length; … -
Docker-compose with Django, MongoDB using Djongo ERROR - pymongo.errors.ServerSelectionTimeoutError
I want to get a django app running using djongo with mongo, and docker. My setup looks like this: docker-compose.yml version: '3.7' services: webserver: build: context: . ports: - "8000:8000" volumes: - ./webserver:/webserver command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 links: - mongo depends_on: - migration mongo: image: mongo:latest restart: unless-stopped volumes: - ./mongo/data/db:/data/db environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: mongoadmin MONGO_INITDB_DATABASE: raspicam ports: - "27017:27017" migration: build: . image: app command: sh -c "python manage.py migrate" volumes: - ./webserver:/webserver links: - mongo depends_on: - make_migrations make_migrations: build: . image: app command: sh -c "python manage.py makemigrations" volumes: - ./webserver:/webserver links: - mongo depends_on: - mongo Dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" ENV LIBRARY_PATH=/lib:/usr/lib COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers jpeg-dev libjpeg-turbo RUN apk add build-base python3-dev zlib-dev RUN pip install --upgrade pip RUN pip install --no-cache-dir -r /requirements.txt RUN apk add libjpeg RUN apk del .tmp RUN mkdir /webserver COPY ./webserver /webserver WORKDIR /webserver COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/ RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] settings.py DATABASES = { "default": …