Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HttpResponse object. It returned None instead
The view main.views.add_venue didn't return an HttpResponse object. It returned None instead. -- Value Error error error appeared after creating views.py views.py def add_venue(request): if request.method == "POST": form = VenueForm(request.POST) if form.is_valid(): form.save() return redirect('/add_venue?submitted=True') else: form = VenueForm() if 'submitted' in request.GET: submitted = True else: return HttpResponseRedirect('/add_venue?submitted=True') return render(request, 'main/add_venue.html', {'form': form, 'submitted':submitted}) models.py, HTML, admin.py and forms.py works correctly. If I delete return HttpResponseRedirect(/add_venue?submitted=True) error won't (when going to the page) appear until I fill out the form -
zappa : Failed to manage IAM roles
Im trying to deploy a django app with zappa. I have set the region and everything in the zappa init. Now when i try to do zappa deploy I have this error: "Error: Failed to manage IAM roles!" Exception reported by AWS:An error occurred (InvalidClientTokenId) when calling the CreateRole operation: The security token included in the request is invalid. I've created a user under Iam in aws console and I have attached IAMFullAccess and PowerUserAccess Iam predefined policies/strategies. I dont know what to do Thank you Best, -
ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields'
Can anyone please help me? I am getting this error from a week. I really need HELP THE Django Server is not working and i am getting this error when I enter Previously i was using python another version and now I installed python v10 so what should i do now? py manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management_init_.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django_filters_init_.py", line 7, in from .filterset import FilterSet … -
I'm getting a TemplateSyntaxError in my local django server at my template html file regarding the block tag that I used
"Invalid block tag on line 2: 'endblock'. Did you forget to register or load this tag?" This is the error I'm getting and the following is my code in my index.html file in vs code which for some reason keeps getting aligned into one line after saving despite saving each block as a different line after one another: {% extends 'base.html' %} {% block body %} This is body block {% endblock body %} -
Django "NoReverseMatch: Reverse for 'ads.views.AdListView' not found" while doing Test
I implemented some tests to check the status code of some pages, but this one with the reverse function throws me the error: django.urls.exceptions.NoReverseMatch: Reverse for 'ads.views.AdListView' not found. 'ads.views.AdListView' is not a valid view function or pattern name. Reading the documentation and some answers on stackoverflow I'm supposed to use either the view function name or the pattern name inside the parenthesis of the reverse function, but none of them seems to work. Here's my code: ads/tests/test_urls.py from django.test import TestCase from django.urls import reverse class SimpleTests(TestCase): def test_detail_view_url_by_name(self): resp = self.client.get(reverse('ad_detail')) # I've also tried: resp = self.client.get(reverse('ads/ad_detail')) self.assertEqual(resp.status_code, 200) ... ads\urls.py from django.urls import path, reverse_lazy from . import views app_name='ads' urlpatterns = [ path('', views.AdListView.as_view(), name='all'), path('ad/<int:pk>', views.AdDetailView.as_view(), name='ad_detail'), ... ] mysite/urls.py from django.urls import path, include urlpatterns = [ path('', include('home.urls')), # Change to ads.urls path('ads/', include('ads.urls')), ... ] ads/views.py class AdDetailView(OwnerDetailView): model = Ad template_name = 'ads/ad_detail.html' def get(self, request, pk) : retrieved_ad = Ad.objects.get(id=pk) comments = Comment.objects.filter(ad=retrieved_ad).order_by('-updated_at') comment_form = CommentForm() context = { 'ad' : retrieved_ad, 'comments': comments, 'comment_form': comment_form } return render(request, self.template_name, context) I'm a newbie with Django, so I don't really understand what's going on. Any idea of what is … -
How to configure a server on raspian with django, apache2, mariasql, vhosts, pipenv
I am trying to set up a webserver, and have made some steps towards setting it up but I have hit a hurdle that maybe some one can help me with. I am getting the following error "This site can't be reached". Checking the connection Checking the proxy and the firewall. I have only done this setup once before and it was ages ago, but have exhausted my documentation at the time that I did it. And any scraps for information would be most helpful. Heres my setup and steps so far, some steps are for later e.g. certbot etc. What I am currently trying to do is show domain.co.uk in the browser after setting the /etc/hosts file. So nothing over the internet for now, just everything on the local machine. Equipment: Raspberry Pi 3 Model B V1.2 16 GB MICRO SD CARD Keyboard Mouse 4K HDMI Monitor Power Cable HDMI Cable WIFI Access Power Supply Software: SD Memory Card Formatter Raspberry Pi OS with desktop (bullseye) MD5 & SHA Checksum Utility Raspberry Pi Imager PassMark ImageUSB Chromium apache2 libapache2-mod-php Process: Download “SD Memory Card Formatter”. Format “16 GB MICRO SD CARD” with “SD Memory Card Formatter”. Download “Raspberry Pi … -
Setting up VS Code for use with Django, Apache, virtualenv on a remote server
we have a django project on a development server which is running within a virtual environment. I was hoping to be able to use VS Code for development from my local PC, but I am not sure if I am able to or not. It seems like something that would make sense to do! I think I have managed to set the interpreter as the virtualenv on the server using UNC paths and have activated it, but when I try to run manage.py to create a new app, I get No module named 'django' which perhaps suggested the virtualenv hasn't activate properly? Is it possible to use VS Code in this way? thanks, Phil -
ajax request in django
My ajax code $.ajax({ type: "get", url: "", statusCode: { 500: function() { alert("error"); }}, data: { "map":JSON.stringify(jsonmap), "road":JSON.stringify(sourceGoal), "line":JSON.stringify(straightLineToDestination) }, success: function(response){ alert("success") } }); my views.py code : import json from telnetlib import STATUS from urllib import request from django.shortcuts import render from django.http import HttpResponse import os from django.views.generic import View from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt,csrf_protect from .algocode import a_star import pprint @csrf_exempt def home_view(request): if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': if request.method == 'Get': straight_line=json.loads(request.Get.get('line')) SourceandGoal=json.loads(request.Get.get('road')) Graph=json.loads(request.Get.get('map')) heuristic, cost, optimal_path = a_star(SourceandGoal["start"], SourceandGoal["end"],Graph,straight_line) result=' -> '.join(city for city in optimal_path) print(result) print(heuristic) print(cost) return JsonResponse({"heuristic":heuristic,"cost":cost,"result":result}) return render(request,'index.html') My URLS.py : urlpatterns = [ path('admin/', admin.site.urls), path('',home_view), ] my problems are : When ajax type was "post" I had a "500 eternal server error" but the data is passed and I can access it and use it as I want in my views.py I changed ajax type to "get " there was no errors put now I get the data in a wrong format and I cant use it in my project "GET /?map=%22%7B%5C%22City1%5C%22%3A%7B%5C%22City2%5C%22%3A123%7D%2C%5C%22City2%5C%22%3A%7B%5C%22City1%5C%22%3A12%7D%7D%22&road=%7B%22start%22%3A%22City1%22%2C%22end%22%3A%22City2%22%7D&line=%7B%22City2%22%3A32%2C%22City1%22%3A222%7D HTTP/1.1" 200 1247 when ajax type was "post" the data I receive comes like this even with the server Erorr : { … -
Django:TypeError: serve() got an unexpected keyword argument 'Document_root'
hello I am facing some issues with my code. this is the error that I am getting TypeError: serve() got an unexpected keyword argument 'Document_root' this is my settings.py STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto- field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' here is my url.py from xml.dom.minidom import Document from django.conf import settings from django.contrib import admin from django.urls import path from django.conf.urls.static import static from customer.views import Index, About, Order urlpatterns = [ path('admin/', admin.site.urls), path('', Index.as_view(), name='index'), path('about/', About.as_view(), name='about'), path('order/', Order.as_view(), name='order'), ] + static(settings.MEDIA_URL, Document_root=settings.MEDIA_ROOT) and here is my Html file <button type="button" class="btn btn-dark" data-toggle="modal" data-target="#submitModal" > Submit Order! </button> <!-- <button class="btn btn-dark mt-5">Place Order!</button> --> <!-- Modal --> <div class="modal fade" id="submitModal" tabindex="-1" role="dialog" aria-labelledby="submitModalLabel" aria-hidden="true" > <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="submitModalLabel"> Submit Your Order! </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" data-dismiss="modal" > Go Back </button> <button type="submit" class="btn btn-dark">Place Order! </button> </div> </div> </div> </div> </form> What should I do to stop getting this error. I have been struggling from 2 days. and yes the app … -
Django multiple update Task at once
I have my Django website where i can have tasks created and subtasks under tasks i have mark complete option which is working fine i need them to be completed in batch like selecting multiple tasks at once and complete them. serializers.py: class TaskCompleteSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ( 'is_done', ) def update(self, instance, validated_data): person = self.context['request'].user.person task_is_done = validated_data.get('is_done', False) if task_is_done: instance.subtasks.update(is_done=True) instance.is_done = task_is_done instance.done_by.set([person]) instance.save() return instance views.py: class TaskUpdateAPIView(UpdateAPIView): permission_classes = " " serializer_class = TaskCompleteSerializer queryset = Task.objects.all() model = Task lookup_url_kwarg = 'task_id' urls.py path('<int:task_id>/complete/',views.TaskUpdateAPIView.as_view(), name='task_update'), models.py class Task(BaseModel): name = models.CharField(max_length=255) done_by = models.ManyToManyField( User, related_name='tasks_completed', blank=True, ) is_done = models.BooleanField(default=False) class Subtask(models.Model): name = models.CharField(max_length=255) subtask_of = models.ForeignKey( Task, related_name='subtasks', blank=True, null=True, on_delete=models.CASCADE, ) -
Min distance of one point to set of points Django ORM
I am trying to calculate minimum distances of one point to set of points. For example if there are 3 places A, B, C in the set and the wanted place is D, I want min(dist(A, D), dist(B, D), dist(C, D). Here is my place model: class Place(models.Model): latitude = models.FloatField(blank=False) longitude = models.FloatField(blank=False) Here is my query which seems not to work: places_with_distance = Place.objects.annotate( distance=( Subquery(places_set.annotate( distance_to_place_in_set=( Min( (F('latitude') - OuterRef('latitude')) * (F('latitude') - OuterRef('latitude')) + (F('longitude') - OuterRef('longitude')) * (F('longitude') - OuterRef('longitude')) ) ) ).values('distance_to_place_in_set')))).order_by('distance') The problem is that the distance gets calculated only for the first item of the places_set(e.g. only dist(A, D) but not dist(B, D), ...). Thanks! -
Using urls path with slug returns Page not found (404) No profile found matching the query
I'm trying to create user Profile for my django project, I'm using UpdateView to allow user to edit Profile model when they want to create profile for their account but it return an error every time I click on create profile url in the profile template. Profile Template: <div class="container"> <div class="row justify-content-center"> {% for profile in profiles %} <div class="col"> <a href="{{profile.website}}">{{profile.website}}</a> <a href="{{profile.twitter}}">{{profile.website}}</a> </div> {% endfor %} </div> </div> <br> <div class="container"> <div class="row"> <a href="{% url 'editProfile' user.id %}" class="btn btn-primary">Create Profile</a> </div> </div> My model: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_image = models.ImageField(upload_to="avatars/") stories = models.TextField(max_length=500,blank=True, null=True) website = models.URLField(max_length=250, blank=True, null=True) twitter = models.URLField(max_length=250, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) slug = models.SlugField(blank=True, null=True) my urls: path('editprofile/<slug:slug>/edit', views.EditProfileView.as_view(), name='editProfile'), my views: @login_required(login_url='login') def profile(request, pk): profiles = Profile.objects.filter(user=request.user) questions = Question.objects.filter(user=request.user) context = {'questions':questions, 'profiles':profiles} return render(request, 'profile.html', context) class EditProfileView(UpdateView): model = Profile fields = ['profile_image', 'stories', 'website', 'twitter', 'location'] template_name = 'edit_profile.html' success_url = reverse_lazy('index') def save(self, *args, **kwargs): self.slug = slugify(self.user) super(Creator, self).save(*args, **kwargs) -
Django filter logic
I am trying to filter based on a parent having assigned user_roles or not and cant quite work out how to achieve the below in the most efficient way. What i need to do is, if the parent has no user_roles assigned then i want all parent objects (essentially ignore the filter). But if it has some user_roles I want to filter based the Child object user_role also being in the Parent user_roles. class UserRole(models.Model): name = charfield() class Parent(models.Model): ... user_roles = m2m(UserRole) ... class Child(models.Model): user_role = FK(UserRole) Something like: filter = Q(Q(parent__user_roles=Child.user_role) | Q(Ignore if parent__user_roles==None)) -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.CustomUser' that has not been installed
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.CustomUser' that has not been installed I am getting this error .. My settings.py """ Django settings for core project. Generated by 'django-admin startproject' using Django 4.0.4. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+k2v!nn#f*qirqz1&4=de+eb&(f0hgvjd2)&^rg3i(w9z2=9dc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'users', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] AUTH_USER_MODEL = 'users.CustomUser' 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', ] ROOT_URLCONF = 'core.urls' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'core.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Assign view's method result to view's variable - Django Rest Framework
In the view I've defined method do() which returns list class LessonsViewSet(ModelViewSet): def do(self): lst = [] lessons = self.filter_queryset(self.get_queryset()) for l in lessons: /* do something */ lst.append(l) return lst result_list = do() I want to assign do() method result to result_list variable. Tried different versions but none of them worked. How can I do this? thank you in advance -
get() returned more than one OrderProduct -- it returned 3
My error: MultipleObjectsReturned at /process/ get() returned more than one OrderProduct -- it returned 3! Request Method: POST Request URL: http://127.0.0.1:8000/process/ Django Version: 4.0.4 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one OrderProduct -- it returned 3! Exception Location: C:\Users\User\AppData\Roaming\Python\Python310\site-packages\django\db\models\query.py, line 499, in get Python Executable: C:\Program Files\Python310\python.exe Python Version: 3.10.4 Python Path: ['D:\Online_Shop_Django', 'C:\Program Files\Python310\python310.zip', 'C:\Program Files\Python310\DLLs', 'C:\Program Files\Python310\lib', 'C:\Program Files\Python310', 'C:\Users\User\AppData\Roaming\Python\Python310\site-packages', 'C:\Program Files\Python310\lib\site-packages'] Server time: Thu, 26 May 2022 16:57:38 +0500 My views: if not request.user.is_authenticated: session = request.session cart = session.get(settings.CART_SESSION_ID) del session['cart'] else: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) order_product, created = OrderProduct.objects.get_or_create( order=order, ) order.save() messages.success(request, 'Заказ успешно оформлен. Проверьте свою электронную почту!!!') return redirect('product_list') how can I solve that problem? pls help meee -
Django - include another html file from different location
I have two htmls a.html and b.html. a.html is located in the template folder by default. b.html is located in appname/static/images/b.html, because it's a model calculation result in html format. In a.html, I am trying to include b.html but it's not working, unless b.html is in the same template folder. <body> {% include 'appname/static/images/b.html' %} </body> questions: how to include b.html? how to include b.html dynamically if it's in different folder, e.g. images/username/b.html where username is different. -
Changes are not reflecting in django
I am having some issues like I made a site but when ever i upload a new post, post gets uploaded but I it doesn't show in the page. I need to signout and signin again then only it show me that post.Any body can help me with this issue... -
Django - 'dict' object has no attribute 'email'
I'm unable to change the object value This is the whole function def registration(request): errors = { 'username' : None, 'email' : None, 'password' : None, 'confirm_password' : None } if request.method == "POST": username = request.POST.get("username") email = request.POST.get("email") password = request.POST.get("password") confirm_password = request.POST.get("confirm_password") if(solve(email) != 1): errors.update({'email':'Please enter valid email'}) #errors.update(email='Please enter valid email') #errors['email'] = 'Please enter valid email' #errors.email = 'Please enter valid email' #setattr(errors, 'email', 'Please enter valid email') return HttpResponse("<h2>Hello, {0}</h2>".format(errors.email)) return render(request, "auth/successFullRegistration.html", { 'username' : username, 'email' : email, 'password' : password, 'confirm_password' : confirm_password }) else: userform = UserForm() return render(request, "auth/sign_up.html", {"form": userform}) I have already tried: errors.update({'email':'Please enter valid email'}) Also errors.update(email='Please enter valid email') Also errors['email'] = 'Please enter valid email' Also errors.email = 'Please enter valid email' Also setattr(errors, 'email', 'Please enter valid email') And everytime I get the same error message AttributeError at /registration 'dict' object has no attribute 'email' Request Method: POST Request URL: http://127.0.0.1:8000/registration Django Version: 4.0.3 Exception Type: AttributeError Exception Value: 'dict' object has no attribute 'email' Exception Location: D:\Django\gtunews\registration\views.py, line 29, in registration Python Executable: C:\Python310\python.exe Python Version: 3.10.3 Python Path: ['D:\Django\gtunews', 'C:\Python310\python310.zip', 'C:\Python310\DLLs', 'C:\Python310\lib', 'C:\Python310', 'C:\Python310\lib\site-packages'] Server time: Thu, 26 … -
I am getting duplicate responses in joined contest. I want only single response for every contest
i have worked very hard on this.Please help me out as this is very important. I am not able to find why is it happening. models.py class JoinContestlist(models.Model): user = models.ForeignKey(User,null=True,on_delete=models.CASCADE) contest_no = models.CharField(max_length=100,null=True, blank=True) match_id = models.CharField(max_length=100,null=True, blank=True) spots = models.IntegerField(null=True, blank=True) entry_fee = models.IntegerField(null=True, blank=True) price_pool = models.IntegerField(null=True, blank=True) level = models.JSONField(null=True, blank=True) no_of_team = models.IntegerField(null=True, blank=True) remaining_spots = models.IntegerField(null=True, blank=True) remaining_team = models.IntegerField(null=True, blank=True) views.py POST Function @api_view(['POST']) def post_join_contest_list(request, id, contest_no, match_id): try: if request.method == 'POST': user = User.objects.get(id=id) qs = Contest.objects.get(contest_no=contest_no) cs = MatchList.objects.get(match_id=match_id) serializer = JoinContestlistserializer(qs, data=request.data) ks = JoinContestlist.objects.filter(user=user, contest_no=qs.contest_no, match_id=match_id) if len(ks) < qs.no_of_team: js = JoinContestlist.objects.create(user=user, spots=qs.spots, entry_fee=qs.entry_fee, price_pool=qs.price_pool, level=qs.level, no_of_team=qs.no_of_team, contest_no=qs.contest_no, match_id=cs.match_id) js.save() return JsonResponse({"status": True, "message": "success"}) return JsonResponse({"status": False, "message": "Contest is full"}) except: return JsonResponse({"status": False, "message": "Service temporarily unavailable, try again later"}) GET Function @api_view(['GET']) def get_join_contest_list(request, id, match_id): try: if request.method == 'GET': # import pdb # pdb.set_trace() user = User.objects.get(id=id) cs = JoinContestlist.objects.filter(user=user, match_id=match_id) json_data_2 = [] json_data_4 = [] json_data_1 = [] for k in cs: qs = JoinContestlist.objects.filter(match_id=k.match_id, contest_no=k.contest_no) ds = JoinContestlist.objects.filter(user=user, match_id=k.match_id, contest_no=k.contest_no) a = len(qs) b = len(ds) remaining_spots = k.spots - a remaining_team = k.no_of_team - b json_data_1.append({ … -
I can't render page in Django
As in subject I have a problem when I try to open register page. I am trying to add registration with google. I get following Error: Error during template rendering In template C:\Users\Łukasz\PycharmProjects\Home_Concept\hc_web\HTML\registration\register.html, error at line 13 Some helpfull information about error. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/register/ Django Version: 4.0.4 Python Version: 3.10.4 Installed Applications: ['database', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google'] 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'] Template error: In template C:\Users\Łukasz\PycharmProjects\Home_Concept\hc_web\HTML\registration\register.html, error at line 13 Google 3 : {% block content %} 4 : 5 : {% load socialaccount %} 6 : {% load static %} 7 : 8 : <div class="container mx-5"> 9 : 10 : 11 : <div class=" signin text-center"> 12 : 13 : <a href=" {% provider_login_url 'Google' %} " class="text-dark"> <img src="{% static 'btn_google_signin_light_normal_web@2x.png' %}" style="width:14rem; height:auto"></a> 14 : </div> 15 : 16 : <br><br> 17 : 18 : <div style="width: 100%; height: 15px; border-bottom: 1px solid lightgray; text-align: center"> 19 : <span class="text-muted" style="margin-top:-15% !important; font-size: 11px; background-color: white; padding: 0px 10px;"> 20 : OR 21 : </span> 22 : </div> 23 : Traceback (most recent call last): File "C:\Users\Łukasz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\exception.py", line 55, … -
What is more flexible way to organize User authentication model in Django?
I've started working on a new project and I would like to know what is more flexible and changable (improvable) way to work with User model? At first I want to make my project oriented towards employees of the company to allow them manage products and other entities. And then I want to expand the project by letting customers to register in the system and buy stuff. But of course I want employees and customers to have different fields and restrict customers from having access to certain parts of the system. Django offers two ways of dealing with Users: it's either Substituting a custom User model or Extending the existing (default) User model. I can't decide what way to go to have two kinds of users in the future. -
My Django code (forms and models) works just fine, but It's definitely a bad choice for large amounts of data. Would appreciate suggestions
this code works just fine when registering users and adding them to the database. With additional code in the template, it also shows the users that their chosen username/email already exists pretty well. However I am mostly certain that this code's quality is very bad, since It woudn't work well with large databases, since I search for all the users and their usernames/email. Then again, I don't know how to add better validation. I decided to add these validators(passwords excluded) because, unique=True in models have no effect on the forms. What I mean is, before these codes, if I registered with the same username and email over and over, if the passwords matched, the last password that I entered got added to the database(user number stayed the same), but form was considered valid (I think) and It didn't show any errors to the user. This is the best I came up with, but I'm pretty sure it's a bad one. I am taking any suggestions, what other kind of validation can I add to fix the mentioned problem. I thought unique=True would fix things, but apparently it's not enough. Note that I am also a beginner and if this question … -
How to create a class in django which will be deleted when the element in another class is deleted
I am new to python and django please help me with this doubt .How to create a class in django which will be deleted when the element in other class is deleted ? -
why css is not working correctly in download template
I am trying to use free templates for my website using Django, but it's working correctly.