Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
psycopg2-binary fails to install when installing it with pipenv
I am having trouble installing psycopg2-binary (A postgreSQL backend dependecy) in my django project when i use the pipenv utility. However, it installs without any problems if i manually create a virtual environment and use pip install to install it. Here is what I am getting in the terminal (django-project-FDld66dG) chilusoft@vortex:~/PycharmProjects/django-project$ pipenv install -r requirements.txt Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. Requirements file provided! Importing into Pipfile… Pipfile.lock (9e16cc) out of date, updating to (79ab59)… Locking [dev-packages] dependencies… Locking [packages] dependencies… lf.repository.get_dependencies(ireq) File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 174, in get_dependencies legacy_results = self.get_legacy_dependencies(ireq) File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 222, in get_legacy_dependencies result = reqset._prepare_file(self.finder, ireq, ignore_requires_python=True) File "/usr/lib/python3/dist-packages/pipenv/patched/notpip/req/req_set.py", line 644, in _prepare_file abstract_dist.prep_for_dist() File "/usr/lib/python3/dist-packages/pipenv/patched/notpip/req/req_set.py", line 134, in prep_for_dist self.req_to_install.run_egg_info() File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/req/req_install.py", line 435, in run_egg_info call_subprocess( File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/utils/__init__.py", line 705, in call_subprocess raise InstallationError( pip9.exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in /tmp/tmpbix8dadtbuild/psycopg2-binary/ I do not want to use pip, but would rather use pipenv, what can I do in order to sort this out? -
Couldn't implement real-time user-to-user chat app in Django REST framework
I am newbie in web development and I working on one project and in this project i have to create real-time user-to-user chat application using django rest framework. I have implemented this in django itself using channels package (created consumers, routing, templates, js files and some other stuff), but I am stuck now, don't know what to do. The goal is that I have to make an API in DRF and Flutter devs should link it. Here is my models.py class Thread(models.Model): first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person') second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_second_person') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() class Meta: unique_together = ['first_person', 'second_person'] class ChatMessage(models.Model): thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.CASCADE, related_name='chatmessage_thread') user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) consumers.py import json from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from django.contrib.auth import get_user_model from chat.models import Thread, ChatMessage User = get_user_model() class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) user = self.scope['user'] chat_room = f'user_chatroom_{user.id}' self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ 'type': 'websocket.accept' }) async def websocket_receive(self, event): print('receive', event) received_data = json.loads(event['text']) msg = received_data.get('message') sent_by_id = received_data.get('sent_by') send_to_id = received_data.get('send_to') thread_id = … -
Run a function on server exit Django
I have a Django Server which runs some background jobs on startup. Code provided below- class ApiConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api' def ready(self): run_once = os.environ.get('CMDLINERUNNER_RUN_ONCE') if run_once is not None: return os.environ['CMDLINERUNNER_RUN_ONCE'] = 'True' from . import bgJobs stop_run_continuously = bgJobs.run_continuously() and the background Job looks something like this def run_threaded(job_func,*args,**kwargs): job_thread = threading.Thread(target=job_func,args=args,kwargs=kwargs) job_thread.start() def run_continuously(interval=1): cease_continuous_run = threading.Event() class ScheduleThread(threading.Thread): @classmethod def run(cls): while not cease_continuous_run.is_set(): schedule.run_pending() time.sleep(interval) continuous_thread = ScheduleThread() continuous_thread.start() return cease_continuous_run def printTest(Text): time.sleep(10) schedule.every(10).seconds.do(run_threaded,printTest,Text="Texts") The bgJob is a demo one. Question:-The background jobs run even after I close the server. I have to run the stop_run_continuously.set() when the server exits to stop it but couldn't find some way to do this. My preference is to do this in django only. Note:- If there is a better way of running the job then you can also provide that -
Can't login after changing base user model to custom one
I have recently changed my user model to a custom one and can't login to both admin (with superusers) and website (wit normal users) anymore. I use the email field for authentication. I guess there's something I didn't consider but since there are no errors I dont know where to search. Note: When I try to login (admin or website) the login form just refreshes with empty inputs, so I guess the form is not valid? If so, why? # models.py from django.core.mail import send_mail from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager): """ Manager for user profiles """ def create_user(self, email, name, password=None): """ Create a new user profile """ if not email: raise ValueError('User must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): """ Create a new superuser profile """ user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser, PermissionsMixin): """ Database model for users in the system """ email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_staff … -
Django Apscheduler scheduler.start()
i am working with slack api's and in some point of my project i am adding some schedules by django apscheduler..but when ever i call scheduler.start() in my apiview then the codes after this line never actually executes # seting scheduler freshly scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( lunch_reminder,args=(channel,other_channel,user), trigger=CronTrigger( hour=f"{required_back_time_hour}",minute=f"{required_back_time_minute}" ), id="lunch_reminder", #unique id max_instances=1000, replace_existing=False, ) # starting the scheduler scheduler.start() ======> return Response(status=status.HTTP_200_OK) ===> this line never runs -
Any Alternatives to Heroku? [closed]
Heroku just announced that they will cancel all free plans from November. I current deployed my Django app to Heroku, does anyone know any alternatives to Heroku? -
Why other model name treated as field name in filter in django during joining two table?
I am new at django.I stuck in a strange problem is that during joining two table foreign model name is treated as field name even i am using __ underscore and i am getting error. This is my two model :- class TD_FD(models.Model): id = models.BigAutoField(primary_key=True,db_index=True) identity=models.CharField(max_length=25,unique=True,db_index=True) del_status=models.CharField(max_length=6,default='na',db_index=True) status=models.CharField(max_length=16,db_index=True) primary_id=models.ForeignKey('all_scheme',to_field='identity', db_column='primary_id' ,on_delete=models.PROTECT,max_length=25, db_index=True) def __str__(self): return self class all_scheme(models.Model): id = models.BigAutoField(primary_key=True,db_index=True) identity=models.CharField(max_length=25,unique=True,db_index=True) del_status=models.CharField(max_length=6,default='na',db_index=True) status=models.CharField(max_length=16,db_index=True) scheme_name=models.CharField(max_length=150,db_index=True) branch_id=models.CharField(max_length=25,db_index=True) def __str__(self): return self ``` This is my query `deposit_data=TD_FD.objects.filter(all_scheme__branch_id=branch_id).values()` But .filter('all_scheme__branch_id' treated as field name.Why? -
How to render the emoji API in Django template
I'm having a hard time trying to figure out how to get the emoji to render in django app as i have tried to follow the example from the emoji API Docs, but somehow it wouldn't render the Emoji after loading all the template tags to my project, I'm wondering if anyone has experience of ever using the emoji library and can help me out with it! I have a comment form that i would like to add up the emoji so that when someone comment they can be able to add an emoji to their comment! which i had installed this emoji library https://pypi.org/project/django-emoji/ rather than creating one from scratch! but some how am not able to see the emoji's in my form after i loaded the template tags! {% load emoji_tags %} {% emoji_load %} {% for comment in post.comments.all %} <form for="id_comment" action="{% url 'feed:post-detail' post.pk %}" method="POST"> {% csrf_token %} <div class="bg-gray-100 rounded-full relative dark:bg-gray-800 border-t" for="id_comment" > <input placeholder="Add your Comment.." name="comment" id="id_comment" class="bg-transparent max-h-10 shadow-none px-5"> <div class="-m-0.5 absolute bottom-0 flex items-center right-3 text-xl"> <a href='Emoji.setDataUrl('{% url 'emoji:list.json' %}').load()'> <ion-icon name="happy-outline" class="hover:bg-gray-200 p-1.5 rounded-full">{{ comment|emoji_replace }}{</ion-icon> </a> <a href="#"> <ion-icon name="image-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon> … -
React JS cant post data to django
I am writing this app that implements the crud operations. Whenever I fetch, I get the data successful from backend however when I try to update or add an object. I get 405 error through the console. The code is clean. -
Cant Access Django development server with 0.0.0.0:8000
I am trying to run my Django app on a windows system with python manage.py runserver 0.0.0.0:8000. But it doesnt runs in other systems. Following steps I have already followed: App runs in local system ALLOWED_HOSTS = ['*'] I have disabled firewall completely I open incomming and outgoing connection for port 8000. Tried with python manage.py runserver 192.xx.xx.xx:8000 Please suggest where am I missing. Additional Note: I already tried and run the similar app in an ubuntu server and it works perfectly fine. -
Error 101 sending email with mailgun on django heroku
My settings.py: EMAIL_HOST = "smtp.mailgun.org" MAIL_PORT = 587 EMAIL_HOST_USER = os.environ["MAILGUN_SMTP_LOGIN"] EMAIL_HOST_PASSWORD = os.environ["MAILGUN_SMTP_PASSWORD"] EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' My views.py: import re import os from django.http import HttpResponse from django.template import loader from django.contrib.auth.hashers import make_password import time import secrets from .models import User from .models import EmailConfirmation from django.core.mail import send_mail from threading import Thread import threading noReply = re.sub(".*@", "noreply@", os.environ["MAILGUN_SMTP_LOGIN"]) def threadingSendMail(subject, message, from_email, recipientList): send_mail( subject=subject, message=message, from_email=from_email, recipient_list=recipientList ) def wait(request): if request.method == "POST": password = request.POST["password"] email = request.POST["email"] if not re.match(r"[^@]+@[^@]+\.[^@]+", email): return HttpResponse("Email not valid") else: if User.objects.filter(email=email).exists(): return HttpResponse("Email already exists") else: theUser = User.objects.create(email=email, password=make_password(password), confirmed=False) hashKey = secrets.token_hex(16) EmailConfirmation.objects.create(email=theUser,emailHash=hashKey) verificationLink = request.get_host() + "/" + str(hashKey) threading.Thread(target=threadingSendMail, args=("Email conf", verificationLink,noReply,[email],)).start() return HttpResponse("pass") else: return HttpResponse("hello") My error in heroku logs: 2022-08-27T10:55:15.473726+00:00 app[web.1]: Exception in thread Thread-1 (threadingSendMail): 2022-08-27T10:55:15.473737+00:00 app[web.1]: Traceback (most recent call last): 2022-08-27T10:55:15.473738+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/threading.py", line 1016, in _bootstrap_inner 2022-08-27T10:55:15.473739+00:00 app[web.1]: self.run() 2022-08-27T10:55:15.473739+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/threading.py", line 953, in run 2022-08-27T10:55:15.473810+00:00 app[web.1]: self._target(*self._args, **self._kwargs) 2022-08-27T10:55:15.473820+00:00 app[web.1]: File "/app/djangocode/stocks/views.py", line 21, in threadingSendMail 2022-08-27T10:55:15.473912+00:00 app[web.1]: send_mail( 2022-08-27T10:55:15.473921+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/mail/__init__.py", line 87, in send_mail 2022-08-27T10:55:15.474010+00:00 app[web.1]: return mail.send() 2022-08-27T10:55:15.474018+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/mail/message.py", line 298, … -
djongo' isn't an available database backend or couldn't be imported. Check the above exception
enter image description here enter image description here enter image description here enter image description here enter image description here -
Django gettext <br> tag
Thank you for checking my question. I try to use gettext and serve my django website in another languages. I want to add a class to the br tag. As shown in ↓, an error does not occur if there is only a br tag, {% trans "I am a student. <br> I am a man."%} But as shown below, if you add a class, an error will occur. {% trans "I am a student. <br class="aaaa"> I am a man."%} Could you teach me is there any good solution? -
Drf serializer of childmodel for both nested ListAPIView and CreateAPIView
I have these models class myModel(models.Model): username = models.CharField(max_length=150, unique=True) o2=models.CharField(max_length=150, default='lllss') class myModel2(models.Model): owner=models.ForeignKey(myModel,on_delete=models.CASCADE) o2=models.CharField(max_length=150, default='lllss2') model2 has owner of myModel and these serializers class mySer(serializers.ModelSerializer): class Meta: model = my.myModel fields = ['username', 'o2'] class mySer2(serializers.ModelSerializer): class Meta: model = my.myModel2 fields = ['owner', 'o2'] depth=1 # to have nested in listviews note I have added depth=1to have nested in listviews so with from rest_framework import generics class myView(generics.CreateAPIView): queryset = my.myModel2.objects.all() serializer_class = my2.mySer2 class myView2(generics.ListAPIView): queryset = my.myModel2.objects.all() serializer_class = my2.mySer2 I can get nested info of owner, but in CreateAPIView there is no dropdown menu for owner in HTML form. better said nothing enables us to send owner. but when I delete depth=1 I have not that problem but I lose the nested views. I could have created 2 serializers but is there any way of doing this in a single serializer? -
return Invalid address; only example1@gmail.com could be parsed from "example1@gmail.com, example@gmail.com
any way around this i'm trying to send multiple mail through ajax in a textarea area i got this in return Invalid address; only example1@gmail.com could be parsed from "example1@gmail.com, example@gmail.com, this is my code below def post(self, request, *args, **kwargs): studentcourse = request.POST.get('studentcourse') from_email = request.user.email subject = Courses.objects.get(id=studentcourse) emails = request.POST.get('email') message = request.POST.get('message') notify_email = EmailMultiAlternatives(subject, message, from_email,[emails]) notify_email.send() return Invalid address; only example1@gmail.com could be parsed from "example1@gmail.com, example@gmail.com -
Django DRF login only superuser
I want to implement login with Django drf. I want only superuser (is_staff permission in my user model) to be able to log in. Until now I used rest_framework_simplejwt for generating a token for every user that trying to log in. How can I implement that only superuser will be able to log in? Views.py: calling the serializer class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer Serializer.py: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): user = CustomUser.objects.get(email=user.email) print(colored(user, "yellow")) token = super().get_token(user) # Add custom claims token['username'] = user.clinic_name token['email'] = user.email # ... return token In serializer.py when I'm trying to retrieve user user = CustomUser.objects.get(email=user.email) I get only the email filed back. I'm using email to retrieve user because email is a unique field. urls.py: urlpatterns = [ path('token/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('register/', views.ClinicRegistration, name='auth_register'), path('users/', views.ClinicListView.as_view(), name='users_list'), path('users/<pk>/', views.ClinicDetailView.as_view(), name='get_user'), path('users/<pk>/update/', views.ClinicUpdate, name='update_user'), path('users/<pk>/delete/', views.ClinicDeleteView.as_view(), name='delete_user'), path('', views.getRoutes), path('test/', views.testEndPoint, name='test') ] In the frontend I'm using react I make an Axios.post request with the: username, password, and email fields. This is my CustomUserModel: class CustomUser(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(_('email address'), unique=True) clinic_name = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) fb_projectId … -
File import issue - python Django
I have a file in my management/commands folder and I am trying to import my models into the report.py folder. However, I get the following error. Traceback (most recent call last): File "c:\Users\Timmeh\source\Python\Django Projects\env\topxgym\members\management\commands\report.py", line 2, in <module> from members.models import ActiveMember ModuleNotFoundError: No module named 'members' I have a active.py file in that same folder with the same import and it works. However, the active.py is run from python manage.py active. The report.py I am just compiling/running it (not running it from python manage.py). That is the only difference. the file structure. -
How do I print the query that Python uses to call the database?
How do I print to the terminal the query used by a specific line of python code? see below notifications = user.get_notifications(max_id=max_id, types=types).order_by('-created')[:count] -
Nginx can't find bundles js file
I am trying this for a long time. I would really appreciate the help. In local, application is working, but in nginx, main.js resource is not found I have a django application with react on the save server served with webpacker and babel URL / will render frontend/index.html Index.html code: Nginx.conf file Settings.py In local, its working But in nginx server, its not project structure -
Errow while working with django, psycopg file shifting to mac (I WOULD ANSWER MYSELF, IT MAY HELP SOMEONE) [duplicate]
I recently shifted to MAC M2 MONTEREY & one project involved django & my dev env from older system isn't setup here. I got error while installing "psycopg" like this: Using cached psycopg2-2.8.5.tar.gz (380 kB) ERROR: Command errored out with exit status 1: command: /opt/homebrew/opt/python@3.9/bin/python3.9 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-install-9wiqe2nr/psycopg2_97efcf6747c249769acdc8430ba4238f/setup.py'"'"'; __file__='"'"'/private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-install-9wiqe2nr/psycopg2_97efcf6747c249769acdc8430ba4238f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r cwd: /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-install-9wiqe2nr/psycopg2_97efcf6747c249769acdc8430ba4238f/ Complete output (23 lines): running egg_info creating /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info writing /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/PKG-INFO writing dependency_links to /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/dependency_links.txt writing top-level names to /private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/top_level.txt writing manifest file '/private/var/folders/m5/vhnyyjg16gd352x6wdhpjysh0000gn/T/pip-pip-egg-info-ap2am61r/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ============================================================================== Its beginning of the error, After that its tried to install each previous version of Psycopg ============================================================================== Searching out for solution, a few things helped me out so here's the answer from my side thinking it may help someone else … -
Apache + Python (Django): Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
I'm trying to host my Django Rest Framework project using Xampp & Apache on my Windows server but I'm getting the following error. Does anyone have an idea what causes it? I installed Python, mod_wsgi and all the requirements for my app. Full stacktrace below Current thread 0x00000e94 (most recent call first): <no Python frame> [Sat Aug 27 11:05:43.581446 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00428: Parent: child process 5104 exited with status 1 -- Restarting. [Sat Aug 27 11:05:43.741583 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00455: Apache/2.4.53 (Win64) PHP/8.1.6 mod_wsgi/4.9.3 Python/3.10 configured -- resuming normal operations [Sat Aug 27 11:05:43.741583 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00456: Apache Lounge VS16 Server built: Mar 16 2022 11:26:15 [Sat Aug 27 11:05:43.741583 2022] [core:notice] [pid 2484:tid 332] AH00094: Command line: 'C:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache' [Sat Aug 27 11:05:43.757121 2022] [mpm_winnt:notice] [pid 2484:tid 332] AH00418: Parent: Created child process 2976 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\xampp\\apache\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.base_exec_prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.platlibdir = 'lib' sys.executable = 'C:\\xampp\\apache\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.exec_prefix = 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310' sys.path = [ 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', '.\\DLLs', '.\\lib', … -
Django replace text in template
In my project i can filter products with queryset. How can i change a h1 element to the filter name? I tried to change with javascript, but when i filtered the products the page reloaded and the text didn't change models.py TYPE = ( (0, "monitor"), (1, "pc"), (2, "phone"), ) class Product(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) image = models.ImageField(upload_to='images/') description = models.TextField() price = models.CharField(max_length=12, unique=True) type = models.IntegerField(choices=TYPE, default=0) def __str__(self): return self.name views.py class ProductList(generic.ListView): template_name = 'products.html' def get_queryset(self): queryset = Product.objects.all() type_query = self.request.GET.get("type", None) if type_query == 'monitor': queryset = Product.objects.filter(type=0) elif type_query == 'pc': queryset = Product.objects.filter(type=1) elif type_query == 'phone': queryset = Product.objects.filter(type=2) elif type_query == 'all': queryset = Product.objects.all() return queryset products.html <form onsubmit="return setTypeText()" id="type-form"> <input type="radio" id="all-radio" name="type" value="all"> <input type="radio" id="monitor-radio" name="type" value="monitor"> <input type="radio" id="pc-radio" name="type" value="pc"> <input type="radio" id="phone-radio" name="type" value="phone"> <input type="submit" value="Filter"> </form> <h1 id="type-text">All product</h1> #<---I need to change this I need to change the h1 to the input value Javascript function setTypeText(){ var elements = document.getElementsByName('type'); var type_name; for(i = 0; i < elements.length; i++) { if(elements[i].checked) type_name = elements[i].value; } document.getElementById("type-text").innerHTML = type_name; return true; } When … -
Show only users that don't yet exist in the through table
Inside of the __init__ method of a form ProjectUserCreateForm(forms.ModelForm) to add Users to a Project (Project model has a users = models.ManyToManyField(...)) I have self.fields['users'].queryset = User.objects.filter(company=self.request.user.company) This way I'm able to show only the users to be added to the Project that belong to the company of the user requesting the page. This form can be found in path('<int:pk>/users/create/', views.ProjectUserCreateView.as_view(), name='project-user-create'), where the <int:pk> is the PK of the Project, and ProjectUserCreateView is a CBV CreateView. How can I show only the users that belong to the company of the logged in user (this part already works) AND that don't yet exist in the through table (the table based on the ManyToManyField)? -
Django messages not displaying message
I'm trying to use django messages to notify user if form was submitted successfully or not. But nothing pops up when I submit the form no matter what. I've gone through the views.py code and template and I don't seem to anything wrong. I've even tried changing the default messages backend storage to session yet nothing. MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' views.py: from django.shortcuts import render, HttpResponse, HttpResponseRedirect, redirect from django.contrib import messages from .forms import MyUserCreationForm import bcrypt def register(request): if request.method == "POST": # Populate form using submitted data form = MyUserCreationForm(request.POST) if form.is_valid(): # Clone form model user = form.save(commit=False) password = user.password # Validate password length if len(password) > 25: messages.error( request, "PASSWORD MUST BE LESS THAN OR EQUAL TO 25 CHARACTER LENGTH") # Hash user password bytes = password.encode('utf-8') salt = bcrypt.gensalt() hash = bcrypt.hashpw(bytes, salt) # Save modified form to database user.password = hash user.save() messages.success(request, "ACCOUNT CREATED SUCCESSFULLY!") messages.add_message(request, messages.INFO, 'Thanks for reaching out! We will be in contact soon!', extra_tags='ex-tag') return redirect('register') # Create empty form form = MyUserCreationForm() return render(request, 'register.html', {'form': form}) templates/register.html: {% extends "layout.html" %} {% block title %} Testing Registration {% endblock %} {% load static %} {% load … -
How to connect two django projects on two different servers
Problem: I am having a website which has various apps (Accounts, Community, Company, Payments, Main_project_app). What I want is to set up a google type similar architecture where the userbase is on one server and other apps such as Gmail, drive, etc. serve the specific services on different servers based on the user authentication from the main Google userbase server i.e. Accounts app which have information about the user such as username, email, password, etc must remain on one server and using the REST API's or something we connect accounts app with another server to take the user from sign-in page to dashboard and serve them other services by using all other apps. I am a newbie so please if I have done some mistakes to explain or something do correct me.