Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extra User Register Information can't store in database such as phoneno playergameid exclude username,password in django while using Usercreationform
[enter image description here][1]I am a beginner for django,i just finished my django course.so i want to develop mini project.In that project i want to store user register informations in model database table.but i can store only username and password while using UserCreationForm.But i want to store extra and all informations in my django model database table..please help me to solve this.. models.py ```from django.db import models class Playerinfo(models.Model): username = models.CharField(max_length=24) pubg_name= models.CharField(max_length=14) pubg_id = models.PositiveIntegerField() email_id = models.EmailField() phone_no = models.PositiveIntegerField() password1 = models.CharField(max_length=16) password2 = models.CharField(max_length=16)``` forms.py ```from bgmiapp.models import Playerinfo from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms import fields from django.forms.widgets import PasswordInput class RegisterForm(UserCreationForm): username = forms.CharField(max_length=24) pubg_name= forms.CharField(max_length=14) pubg_id = forms.IntegerField() email_id = forms.EmailField() phone_no = forms.IntegerField() password1 = forms.CharField(max_length=16,widget=PasswordInput) password2 = forms.CharField(max_length=16,widget=PasswordInput) class Meta(): model = User fields = ('username','pubg_name','pubg_id','email_id','phone_no','password1','password2')``` views.py ```from django.shortcuts import render,redirect from .forms import RegisterForm from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login # Create your views here. def register(request): form=RegisterForm() if request.method =='POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() username=form.cleaned_data.get('username') raw_password=form.cleaned_data.get('password1') user=authenticate(username=username,password=raw_password) login(request,user) return redirect('login') else: form=RegisterForm() return render(request,'bgmiapp/register.html',{'form':form})``` urls.py ```from django.contrib import admin from django.urls import path from bgmiapp import … -
Extra field from request in django viewset
I am working with django viewsets and i want an extra field from the request for validation. What i want is the extra field role_id which should be coming from the request. The role id if passed, i should convert the employee to user and assign the role_id to the user. Even though i am sending the role_id from request but i am unable to get it in the create or update method. Can someone please help me to know how can i fetch extra field from response serializer.py class EmployeeModelSerializer(serializers.ModelSerializer): """Employee model serializer""" address = EmployeeAddressModelSerializer(required=False) detail = EmployeeDetailModelSerializer(required=False) demographic = EmployeeDemographicModelSerializer(required=False) contact = EmployeeContactModelSerializer(required=False) nok = EmployeeNokModelSerializer(required=False) visa = EmployeeVisaModelSerializer(required=False) dbs = EmployeeDBSModelSerializer(required=False) job_detail = EmployeeJobDetailModelSerializer(required=False) preference = EmployeePreferenceModelSerializer(required=False) skills = EmployeeSkillsModelSerializer(many=True, read_only=True) user = UserModelSerializer(required=False) serializersMap = { "address": EmployeeAddressModelSerializer, "detail": EmployeeDetailModelSerializer, "demographic": EmployeeDemographicModelSerializer, "contact": EmployeeContactModelSerializer, "nok": EmployeeNokModelSerializer, "visa": EmployeeVisaModelSerializer, "dbs": EmployeeDBSModelSerializer, "job_detail": EmployeeJobDetailModelSerializer, "preference": EmployeePreferenceModelSerializer, "user": UserModelSerializer, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.context["gender"] = None self.context["title"] = None self.context["marital_status"] = None self.context["employee_status"] = None def internal_validate(self, data, field): self.context[field] = data if data == None: return data elif data.id: return data.id return data def validate_gender(self, data): return self.internal_validate(data, "gender") def validate_title(self, data): return self.internal_validate(data, … -
Google App Engine custom runtime with xmlsec setup
We are currently hosting our Django application in Google App Engine. We have a flex environment with python runtime and its working perfectly. We are adding saml auth to our application and for that we need the xmlsec package. We've been trying to change the runtime to custom and add a Dockerfile to the same folder. We see that the Dockerfile executes and the xmlsec package is being installed. But when we try to deploy the app.yaml, we get an error that we are not able to wrap our head around: Step #5: Updating service [default] (this may take several minutes)... Step #5: .................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................failed. Step #5: ERROR: (gcloud.app.deploy) Error Response: [9] Flex operation projects/autonomous-tube-234620/regions/us-central1/operations/f08e56d1-aedb-492d-ab66-738e86935bd6 error [FAILED_PRECONDITION]: An internal error occurred while processing task /app-engine-flex/flex_await_healthy/flex_await_healthy>2021-06-10T18:02:14.559Z137991.in.1: [2021-06-10 15:02:21 +0000] [7] [INFO] Starting gunicorn 19.9.0 Step #5: [2021-06-10 15:02:21 +0000] [7] [INFO] Listening at: http://0.0.0.0:8080 (7) Step #5: [2021-06-10 15:02:21 +0000] [7] [INFO] Using worker: sync Step #5: [2021-06-10 15:02:21 +0000] [10] [INFO] Booting worker with pid: 10 Step #5: [2021-06-10 15:02:21 +0000] [10] [ERROR] Exception in worker process Step #5: Traceback (most recent call last): Step #5: File "/opt/python3.7/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker Step #5: worker.init_process() Step #5: File "/opt/python3.7/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, … -
Django runserver no nginx config file
I am using windows and am trying to runserver a django project that I cloned. However, when I py manage.py runserver, it gives an error stating that it found no nginx conf file. I do have the file, but I don't think I have it set up properly. I also don't have sites-enabled. I have never used nginx and have been doing research all day on it, and still am where I began. I talked with a friend about this and was told about re-routing the traffic to not hit the oauth so that it redirects to my machine, but I am not able to figure out how to do that, even after research. I want to py manage.py runserver and view the site as it is, on my localhost, but am also scared that I may possibly deploy to the web. -
Unable to save into Foreign key fields in Django with multiple table
I'm working on a project Hr Management System. I have a model with foreign key fields to office & staff. I'm trying to save staff in user & staff role wise with foreign key office name. my view def post(self, request): if request.method != "POST": messages.error(request, "Invalid Method ") else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') address = request.POST.get('address') phone = request.POST.get('phone') image = "image" office_id=request.POST.get("office") office=Office.objects.get(id=office_id) try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=2) user.staffs.address=address user.staffs.phone=phone user.staffs.image=image user.staffs.office_id=office user.save() messages.success(request, "Staff Added Successfully!") return render(request, 'admin_template/add_staff.html') My models class Staffs(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) address = models.CharField(max_length=255, blank=True) phone = models.CharField(blank=True,max_length=20) image = models.ImageField(upload_to='uploads/user/',blank=True) office_id = models.ForeignKey(Office,on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() @receiver(post_save,sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type == 1: AdminHOD.objects.create(admin=instance) if instance.user_type == 2: Staffs.objects.create(admin=instance) @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance,**kwargs): if instance.user_type == 1: instance.adminhod.save() if instance.user_type == 2: instance.staffs.save() -
How to store private documents in Django on production?
What is the typical scenario of storing private files in Django on production server? I wanted to use the django-storerages package - S3 bucket, but unfortunately after integration it turned out that private files cannot be stored for more than a week. (AWS_QUERYSTRING_EXPIRE - the given X-Amz-Expires must be less than 604800 seconds). But I need to store them for the user indefinitely. How can such files be stored in a remote cloud? -
How to solve the error "Executable path is not absolute, ignoring:"
I'm currently developing an application in Amazon Linux2 using Django, Nginx, Gunicorn, and Postgresql. I have created and configured a system file for Gunicorn to work when the OS boots, But after starting gunicorn I get the following error... Jun 08 18:18:04 ip-172-31-16-86.us-east-2.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.service:10] Executable path is not absolute, ignoring: gunicorn --access-logfile - --workers 3 --bind unix:/home/myname/django_project/django_project.sock ...... Jun 08 18:18:04 ip-172-31-16-86.us-east-2.compute.internal systemd[1]: gunicorn.service lacks both ExecStart= and ExecStop= setting. Refusing. I'm sure the absolute path specified in the file is correct, but I get the error. How could I solve this problem? *NOTE: Amazon Linux2 doesn't include www-data groups, so I created using groupadd command. gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=myname Group=www-data WorkingDirectory=/home/myname/django_project ExecStart=/home/myname/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/myname/django_project/django_project.sock django_project.wsgi:application [Install] WantedBy=multi-user.target Directory structure home │ └─myname │ ├─django_project │ ├─django_project │ ├─manage.py │ └─django_project.sock │ └─venv └─bin └─gunicorn OS Amazon Linux2 gunicorn 20.1.0 boto 2.49.0 Django 3.2.4 django-ses 2.0.0 -
Getting and showing latest posts in base.html sidebar
I am trying to show 3 latest posts in a sidebar in base.html. I found a previous question (Wagtail - display the three latest posts only on the homepage) and tried to follow but the posts don't show up. Would appreciate any hint on how to proceed. Thanks! # blog/models.py from django.db import models from modelcluster.fields import ParentalKey from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase from wagtail.core.models import Page from wagtail.core.fields import StreamField from wagtail.core import blocks from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.images.blocks import ImageChooserBlock from wagtail.snippets.models import register_snippet richtext_features = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', "ol", "ul", "hr", "link", "document-link", "image", "embed", "code", "blockquote", "superscript", "subscript", "strikethrough", ] class BlogListingPage(Page): """Listing page lists all the Blog pages.""" template = "blog/blog_listing_page.html" custom_title = models.CharField( max_length=255, blank=False, null=False, help_text='Overwrites the default title', ) content_panels = Page.content_panels + [ FieldPanel("custom_title"), ] def get_context(self, request, *args, **kwargs): """Adding custom stuff to our context.""" context = super().get_context(request, *args, **kwargs) context["posts"] = BlogPage.objects.live().public().order_by('-date') context["latest_posts"] = context["posts"][:3] if request.GET.get('tag', None): tags = request.GET.get('tag') all_posts = context["posts"].filter(tags__slug__in=[tags]) return context class Meta: verbose_name = "Blog Listing Page" verbose_name_plural = "Blog Listing Pages" @register_snippet class BlogTag(TaggedItemBase): content_object = ParentalKey( 'BlogPage', on_delete=models.CASCADE, ) class Meta: verbose_name … -
DatabaseError at /blog/ No exception message supplied
i am new in django and i need your help, others pages are working well but when i click into blog pages it shows DatabaseError at /blog/ No exception message supplied and i below i have attached the views.py and modeles.py code // Code views.py : from django.shortcuts import render, get_object_or_404 from .models import Blog from django.template.loader import render_to_string from .meta_gen import meta_keywords def indexblog(request): """ Display Blog page **Context** ``indexblog`` An instance of :model:`indexblog.Course` **Templates** :template:`pages/blog.html` """ blogs = Blog.objects.order_by('-list_date').filter(is_published=True) context = { 'blogs': blogs } return render(request, 'pages/blog.html', context) def blog(request, blog_id): """ Display Blog detail page **Context** ``blog`` An instance of :model:`Blog.blog` **Templates** :template:`pages/bloginside.html` """ blogdetails = get_object_or_404(Blog, pk=blog_id) blogs = Blog.objects.all() context = { 'blogdetails': blogdetails, 'blogs': blogs } return render(request, 'pages/bloginside.html', context) this_template = "apptemplate.html" def tabs(request): return render(request, {'title': "Blog", 'keys': meta_keywords(render_to_string(this_template))}) // code models.py from django.db import models from datetime import datetime from django.urls import reverse from pages.img_compression import compressImage class Blog(models.Model): """ Blog Model Fields blog_title blog_tag blog_image blog_describe is_published list_date ....rest """ blog_title = models.CharField(max_length=700) blog_tag = models.CharField(max_length=400) blog_image = models.ImageField( upload_to='photos/%Y/%m/%d', blank=False, max_length=500) author = models.CharField(max_length=200) blog_describe = models.TextField(blank=False) is_published = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.blog_title … -
Why getting django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. while creating CustomUser and CustomUserManager
I am trying to run a django application and got an error mentioned in Title.Django 3.2.3 and Python 3.9.5 are used in my project.I got this error when ever trying to run any of the bellow command :- python manage.py makemigrationspython manage.py migratepython python manage.py runserver setting.py :- """ Django settings for ecommerceproject project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. import loginsignup.models BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-mw$%fa@7r-g_1*w(d$!bd*si_d3sxrx#c@8i&&(h*@&!(oz#%l' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'loginsignup', ] 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 = 'ecommerceproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ecommerceproject.wsgi.application' … -
Django website is not able to render css code in html templates neither is giving any error
I am making a website based on django. I am trying to load some css into the templates but it's not getting loaded neither is it showing any error related to path. I've added STATICFILES_DIRS to settings and {% laod static%} and link rel to base.html file but the CSS is not getting rendered -
Add OR condition in left join using Django ORM
How do I add an OR condition on the first LEFT OUTER JOIN ? something like this: LEFT OUTER JOIN "orders_orderedproductsku" ON ("manual_shipments"."id" = "orders_orderedproductsku"."shipment_id" OR "manual_shipments"."id" = "orders_orderedproductsku"."return_shipment_id") Already tried other workaround but still no hope. Is there a possible that I could add the OR condition properly? Here's my query set: shipment_rebooking = queryset \ .filter(status='BOOKING_CANCELED') \ .annotate(orderedproductsku__shipment_id=F('orderedproductsku__shipment_id'), logistics_shipment__shipment_id=F('logisticsshipments__shipment_id'), orderedproductsku__status=F('orderedproductsku__status'), logistics_shipment__status=F('logisticsshipments__status'), logistics_shipment__id=F('logisticsshipments__id')) \ .filter(Q(logistics_shipment__status='BOOKING_CANCELED') | Q(logistics_shipment__id__isnull=True), orderedproductsku__status__in=['PREPARING_FOR_SHIPMENT', 'SCHEDULED_FOR_RETURN', 'SCHEDULED_FOR_RETURN_NO_REFUND']) \ .order_by('-created_at') \ .distinct()``` the raw query is like this: ```SELECT DISTINCT "manual_shipments"."created_at", "manual_shipments"."updated_at", "manual_shipments"."deleted_at", "manual_shipments"."id", "manual_shipments"."order_reference_number", "manual_shipments"."logistics_provider_id", "manual_shipments"."logistics_provider_shipment_id", "manual_shipments"."logistics_name", "manual_shipments"."tracking_number", "manual_shipments"."tracking_url", "manual_shipments"."shipping_cost", "manual_shipments"."status", "manual_shipments"."shipment_type", "manual_shipments"."seller_id", "manual_shipments"."buyer_id", "manual_shipments"."latest_logistics_shipment_id", "manual_shipments"."latest_status_id", "orders_orderedproductsku"."shipment_id" AS "orderedproductsku__shipment_id", "logistics_shipments"."shipment_id" AS "logistics_shipment__shipment_id", "orders_orderedproductsku"."status" AS "orderedproductsku__status", "logistics_shipments"."status" AS "logistics_shipment__status", "logistics_shipments"."id" AS "logistics_shipment__id" FROM "manual_shipments" LEFT OUTER JOIN "orders_orderedproductsku" ON ("manual_shipments"."id" = "orders_orderedproductsku"."shipment_id") LEFT OUTER JOIN "logistics_shipments" ON ("manual_shipments"."id" = "logistics_shipments"."shipment_id") WHERE ("manual_shipments"."status" = BOOKING_CANCELED AND ("logistics_shipments"."status" = BOOKING_CANCELED OR "logistics_shipments"."id" IS NULL) AND "orders_orderedproductsku"."status" IN (PREPARING_FOR_SHIPMENT, SCHEDULED_FOR_RETURN, SCHEDULED_FOR_RETURN_NO_REFUND)) ORDER BY "manual_shipments"."created_at" DESC``` -
Refresh a django subtemplate with javascript
I'm trying to refresh a subtemplate by calling a view with js. Nothing seems to happen, though the server gets hit and seems to return a response. The goal is to refresh the included part without refreshing the whole page. Minimal example: views.py def ajax_view(request): context = {} context['data'] = 'data' return render(request, "test.html", context)// <-- reaches here, but no rendering test.html {{data}} main.html <script type="text/javascript"> function getQuery() { var request = new XMLHttpRequest(), method = 'GET', url = '/ajax/'; request.open(method, url); request.send(); } </script> {% include "test.html" %} // <-- does not update -
filter access to detailview by a simple field and/or a manytomanyfield
i want to limit the access to detailView of a chatroom to the owner and participants of the room(joiners) model: class PublicChatRoom(models.Model): title = models.CharField(max_length=100, unique=True, blank=False) owner = models.ForeignKey(User,related_name='chatrooms_created',on_delete=models.CASCADE) joiners = models.ManyToManyField(User, blank=True,related_name='chatrooms_joined') view: class JoinerRoomDetailView(DetailView): model = PublicChatRoom template_name = 'detail.html' def get_queryset(self): return PublicChatRoom.objects.filter(Q(joiners__in=[self.request.user]) | Q(owner=self.request.user)) and some rooms give the following error : get() returned more than one PublicChatRoom -- it returned 2! if i use the view like this: class JoinerRoomDetailView(DetailView): model = PublicChatRoom template_name = 'detail.html' def get_queryset(self): return PublicChatRoom.objects.filter(Q(joiners__in=[self.request.user])) #the modified part only if the user that is in participant list have access, wich is correct and if it,s that: class JoinerRoomDetailView(DetailView): model = PublicChatRoom template_name = 'detail.html' def get_queryset(self): return PublicChatRoom.objects.filter(Q(owner=self.request.user)) #the modified part only the creator of room can see it, again correct everything works as expected. but the Goal is to acces rooms that a user own or a part of both, so how can i do that, thanks for help -
RelatedObjectDoesNotExist at /friends/ User has no profile
I am stuck now for a good 3 hours on this bug. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You can now login!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) def friend_list(request): p = request.user.profile friends = p.friends.all() context={ 'friends': friends } return render(request, "users/friend_list.html", context) request.user.profile is not containing an object. What could be the problem? -
How I can use swagger.json from editor.swagger.io in my Django+drf-yasg project?
I integrate drf-yasg in my project, generate json file: python manage.py generate_swagger swagger.json. After that I edit my swagger.json in editor.swagger.io and export it. And now, how i can use this manually created swagger.json file in my project instead autogenerate? Thanks. -
How to save multiple django form in one page with one submit button
i'm new when developing django. I have some question after days by days finding the answer. Here the go. What i want is making ajax form that handle 2 model form, with 1 submit button I can already saved the data in each form, but got problem in foreign key field got None instead Here we go my model: class ModelA(models.Model): name = models.CharField(max_length=100, blank=True) info = models.CharField(max_length=200, blank=True) def __str__(self): return self.name class ModelB(models.Model): xmodel = models.ForeignKey(to=ModelA, on_delete=models.CASCADE, related_name='modelX', blank=True, null=True) no_1 = models.CharField(max_length=150, blank=True) no_2 = models.CharField(max_length=150, blank=True) Form Class: class ModelAForm(forms.ModelForm): class Meta: model = ModelA fields = '__all__' class ModelBForm(forms.ModelForm): class Meta: model = ModelB exclude = ('xmodel',) View class: def AddData(request): tpl = 'add.html' if request.method == 'POST': mdla = ModelAForm(request.POST) mdlb = ModelBForm(request.POST) if mdla.is_valid(): obj = mdla.save() if mdlb.is_valid(): mdlb.save(commit=False) mdlb.xmodel=obj mdlb.save() else: mdla = ModelAForm() mdlb = ModelbForm() In TPL i'm using ajax to send, it can save model a and model b, but in modelb xmodel (foreign key) it got None when check in adminpanel. Which i do wrong, how to make it happen when handling the forms? -
Django web app with Microsoft azure custom vision
Is it possible to integrate Microsoft azure services like Custom vision in the Django app? I want to build a web app where users can upload images and train a model using those images using Custom Vision from Microsoft Azure. -
Django Google App Engine SQL db non-deterministically thinks a row does not exist
I have a Django backend server hosted on Google App Engine that uses a MySQL database. I am using Firebase (via the Pyrebase wrapper) to authenticate users. The following function is what I use to get the User object given a an auth-token that's stored in the request HTTP metadata. def user_from_request(request): refresh_token = request.META.get("HTTP_AUTHORIZATION") fb_user = auth.refresh(refresh_token) # Firebase user information. firebase_id = fb_user.get("userId") potential_user = User.objects.filter(firebase_id=firebase_id) if potential_user.count() == 0: print('auth token', refresh_token) print('firebase id', firebase_id) return None return potential_user.get() For the most part, it works fine, but there are some small cases (from what I can tell, it is non-deterministic which means it's been a pain to debug) when the auth token will exist in Firebase and we are able to get an associated Firebase id, but SQL (specifically the User.objects.filter(firebase_id=firebase_id) line will return an empty query set. The following is what is printed out when that case happens. auth token XXXXXX # changed to protect user information firebase id XXXXXX # changed to protect user information The strange part is is that there does exist a User row in the database where that Firebase id exists. Subsequent requests with the same auth token will successfully grab … -
Django Error refers to model that isn't installed after Updating
This has only come about since I've updated Django. Here is the relevant settings.py # snipped INSTALLED_APPS = [ 'ctf_club', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ctf_club.apps', ] # snipped AUTH_USER_MODEL = "ctf_club.User" And here's the output of finding User in the ctf_club/models.py file. grep 'User' ctf_club/models.py from django.contrib.auth.models import AbstractUser # User model is just here so I can reference it, I use the default model. class User(AbstractUser): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='solves') user = models.ForeignKey('User',on_delete=models.CASCADE) #used = models.ManyToManyField(User) ctf_club/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone from ctf_club.util import jsonify_queryset """ CTFClub Project By Macarthur Inbody <admin-contact@transcendental.us> Licensed AGPLv3 Or later (2020) """ # User model is just here so I can reference it, I use the default model. class User(AbstractUser): points = models.IntegerField(default=0) tfa_enabled = models.BooleanField(default=False) tfa_secret = models.CharField(max_length=32,default=None) def to_dict(self): return {'id':self.id, 'username':self.username, 'email':self.email, 'is_staff':self.is_staff, 'is_superuser':self.is_superuser, 'first_name':self.first_name, 'last_name':self.last_name, 'date_joined':self.date_joined, 'is_active':self.is_active, 'last_login':self.last_login } But I'm getting the standard error of File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/__init__.py", line 165, in get_user_model "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'ctf_club.User' that has not been installed But that makes no sense as this worked fine prior to updating it but now it … -
How to create an extended User Object in Django?
I created a model ExtendedUser to extend the User Django built-in model class using the approach described in the official documentation: https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#extending-the-existing-user-model so that I can benefit from the existing authentication features provided by Django. That works all fine however I wonder now, whenever I want to create a new ExtendedUser, that means for every ExtendedUser, I also need to create an original User to fullfill the one-to-one relationship? Or what else does it mean the following: Assuming an existing Employee Fred Smith who has both a User and Employee model, you can access the related information using Django’s standard related model conventions[...] In a script to create objects, would this mean the following: u1 = User.objects.create_user(username="u_1", email="u_1@abc.com", password="pw_u_1") ext_u_1 = ExtendedUser.objects.create(id=u1.id, user=u1, prop_1="XYZ") where class ExtendedUser(models.Model): user = models.OneToOneField(User, ...) # More properties... -
django saving two model on a oneto many relationship
I have a template that I use to save two models on a one to many relationship. In this template, I have two questions the first question has radio choices and the second question has checkbox choices like what is shown on the image below. What happens is when I select, for instance, choice#1 in question 1 and check checkbox#1 in question 2 the form is saved successfully. But if I select choice#3 in question 1 and check checkbox#1 or checkbox#2 in question 2 then i get an error: CheckChoice matching query does not exist. I am not sure why i am getting this error. class Survey(models.Model): title = models.CharField(max_length=200) created_at = models.DateTimeField(default=timezone.now) archive = models.CharField(max_length=200, default='') def __str__(self): return self.title class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) enter_question = models.CharField(max_length=900) def __str__(self): return self.enter_question class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=100) class CheckChoice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_check = models.CharField(max_length=100) class SurveyAnswer(models.Model): orig_survey = models.ForeignKey(Survey, on_delete=models.CASCADE) class QuestionAnswer(models.Model): answer = models.ForeignKey(Choice, on_delete=models.CASCADE) check_answer = models.ForeignKey(CheckChoice, on_delete=models.CASCADE) survey_answer = models.ForeignKey(SurveyAnswer, on_delete=models.CASCADE) def survey_fill(request): ans = SurveyAnswer() orig_survey = Survey.objects.get(id=request.POST['survey_id']) ans.orig_survey = orig_survey ans.save() questions = orig_survey.question_set.all() for question in questions: qc = request.POST['question' + str(question.id)] qa = QuestionAnswer() qa.answer … -
how to add comments only to authorized users?
Added the ability to add comments, made it so that only authorized users can add comments, but for some reason this does not work, please fix it. And I also added , but for some reason it does not work either, Thanks everyone! post_detail.html {% extends 'base.html' %} {% load static %} {% block content %} <link href="{% static 'css/post_detail.css' %}" rel="stylesheet"> <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body|urlize }}</p> </div> <p><a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a></p> <p><a href="{% url 'post_delete' post.pk %}">+ Delete Blog Post</a></p> {% if post.header_image %} <p><img src="{{post.header_image.url}}"></p> {% else %} <p></p> {% endif %} {% for comm in post.commentpost_set.all%} {{ comm.user }} <br> {{ comm.text }} <br><br> {% endfor %} <br> <hr> <h2>Comments...</h2> {% if not post.comments.all %} No Comments Yet...<a href="{% url 'post_comment' post.pk %}"> Add Comment</a> {% else %} <form method="post"> {% csrf_token %} {{ comment_form.as_p }} {% if request.user.is_authenticated %} <a href="{% url 'post_comment' post.pk %}">Add Comment</a><br><br> {% else %} <a href="{% url 'post_comment' post.pk %}">Add Comment</a><br><br disabled> {% endif %} </form> {% for comment in post.comments.all %} <strong> {{ comment.name }} - {{ comment.date_added }} </strong> <br> {{ comment.body }} <br><br> {% endfor %} {% endif %} {% … -
Django/DRF changing POST requests to GET
Whenever my frontend sends off a POST request to /api/notebooks/, Django automatically converts it to a GET request to /notebooks?name=[whatever I just typed in]. This isn't the case when I make POST requests to /api/notes/. Whenever I do, it creates a Note object and saves it to the database, the way it's supposed to. Did I mess up anything in my config? I'm 100% sure I've been shooting off my POST requests to /api/notebooks/ rather than /notebooks/... notebooks/urls.py from notebooks.views import NoteViewSet, NotebookViewSet from rest_framework import renderers notebook_list = NotebookViewSet.as_view({ 'get': 'list', 'post': 'create', }) notebook_detail = NotebookViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy', 'post': 'create', }) note_detail = NoteViewSet.as_view({ 'get': 'retrieve', 'post': 'create', 'put': 'update', }) core/urls.py from django.contrib import admin from django.urls import path, include from rest_framework.routers import DefaultRouter from notebooks import views router = DefaultRouter() router.register(r'notebooks', views.NotebookViewSet, basename='notebooks') router.register(r'notes', views.NoteViewSet, basename='notes') urlpatterns = [ # auth path('auth/', include('authentication.urls')), # notebook path('admin/', admin.site.urls), path('api/', include(router.urls)), # frontend path('', include('frontend.urls')), path('notebooks/', include('frontend.urls')), path('signup/', include('frontend.urls')), path('login/', include('frontend.urls')), path('notebooks/<slug:notebook_pk>/', include('frontend.urls')), path('notebooks/<slug:notebook_pk>/notes/<slug:note_pk>/', include('frontend.urls')), path('new-note/', include('frontend.urls')), ] notebooks/serializers.py import json from django.core.files.base import ContentFile from rest_framework import serializers from .models import Note, Notebook, User class NoteSerializer(serializers.ModelSerializer): note_id = serializers.SlugField(source='id', read_only=True, required=False) … -
How would I display MediaPipe/OpenCV in Django?
Trying to run a pose estimator in my Django project. How would I get this to run in my browser? I have it set up in an algos.py file. Need it to display the video it is capturing while it is running the calcs. def pose_capture(): cap = cv2.VideoCapture(0) ## Setup mediapipe instance with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose: while cap.isOpened(): ret, frame = cap.read() # Recolor image to RGB image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image.flags.writeable = False # Make detection results = pose.process(image) # Recolor back to BGR image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Extract landmarks try: landmarks = results.pose_landmarks.landmark # Get coordinates shoulder = [landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x,landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].y] elbow = [landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].x,landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].y] wrist = [landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].x,landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].y] # Calculate angle angle = calculate_angle(shoulder, elbow, wrist) # Visualize angle cv2.putText(image, str(angle), tuple(np.multiply(elbow, [640, 480]).astype(int)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA ) except: pass # Render detections mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS, mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=2), mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2) ) cv2.imshow('Mediapipe Feed', image) if cv2.waitKey(10) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() From what I was seeing so far is to run it as a view. Something along the lines of: def video(request): pose_capture() return HttpResponse() Or StreamingHTTPResonse? If this is the route to take, how does that …