Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model conditional default value based on other field
There is two tables Company and Template_message each company can have desired template messages for each message messages have 3 types ( invitation,rejection,Job_offer) now i want to set a default text for each template_message which the company can change it later on but i dont know how to set the default value for each template message , based on their type the model i designed is bellow : class TemplateMessage(models.Model): TEMPLATE_TYPE_CHOICES = ( ('1', 'invitation'), ('2', 'Rejecting'), ('3', 'Job_offer_acceptance'), ) type = models.CharField(max_length=4, choices=TEMPLATE_TYPE_CHOICES, default='1') def subject_initials(type): match type: case 1: return "[jobName] skills test invitation from [companyName]" case 2: return "Thank you from [companyName]" case 3: return "Job offer letter from [companyName]" subject = models.CharField(max_length=256, default=subject_initials(type)) company = models.ForeignKey('Company', on_delete=models.CASCADE) class Meta: unique_together = ("company", "type") def __str__(self): return self.type but it does not not work and when i go to admin panel the subject text is not set to any default value -
Nested Models in Serializer django
I cannot get the last measurement for each device based on the device's ID from the measurement. If someone can advise me on how to implement this? Models class Devices(models.Model): deviceid = models.AutoField(db_column='deviceId', primary_key=True) # Field name made lowercase. devicename = models.CharField(db_column='deviceName', unique=True, max_length=128) # Field name made lowercase devicestatus = models.IntegerField(db_column='deviceStatus') # Field name made lowercase. Class Meta: managed = False db_table = 'devices' class Measurements(models.Model): measurementid = models.AutoField(db_column='measurementId', primary_key=True) # Field name made lowercase. deviceid = models.ForeignKey(Devices, models.DO_NOTHING, related_name="measurment_details", db_column='deviceId') # Field name made lowercase. measurement = models.CharField(max_length=64, blank=True, null=True) class Meta: managed = False get_latest_by = 'measurementtime' db_table = 'measurements' Serializer class MeasurmentsSerializer(serializers.ModelSerializer): class Meta: model = Measurements fields = ('measurementid','measurement') class DeviceSerializer(serializers.ModelSerializer): latestmeasurment = serializers.SerializerMethodField() count = 0 def get_latestmeasurment(self, obj): qs = Measurements.objects.using('@@@').last() serializer = MeasurmentsSerializer(instance=qs, many=False) self.count = 1 + self.count print(self.count , serializer.data ) return serializer.data class Meta: model = Devices fields = ("devicename", 'latestmeasurment') Views class RetrieveAllDevicesView(viewsets.ModelViewSet): http_method_names = ['get'] permission_classes = [permissions.IsAuthenticated] serializer_class = DeviceSerializer queryset = Devices.objects.using('@@@') In serializer, you can see the count for primitive debug: 1 {'measurementid': 2942080, 'measurement': '35.0'} 2 {'measurementid': 2942080, 'measurement': '35.0'} 3 {'measurementid': 2942080, 'measurement': '35.0'} 4 {'measurementid': 2942080, 'measurement': '35.0'} 5 {'measurementid': 2942080, … -
How to fix RuntimeWarning: DateTimeField Question.date_time received a naive datetime?
I want to delete 60 seconds old records but I am getting this error RuntimeWarning: DateTimeField Question.date_time received a naive datetime (2022-08-27 16:09:30.659947) while time zone support is active. def delete(self,request): expiry_date_time = datetime.now() - timedelta(seconds=60) print('Expiry time = ',expiry_date_time) count = Question.objects.filter(date_time__gte = expiry_date_time).delete() User.objects.all().update(total_question_added=0) resp = {'resp' : 'All questions deleted.','Total question deleted':len(count)} return Response(resp) -
Have some errors when I try to migrate to a database in django
I try to migrate my django models, but I get 4 Errors: auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'products.Customer.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'products.Customer.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'auth.User.user_permissions' clashes with reverse accessor for 'products.Customer.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'products.Customer.user_permissions'. products.Customer.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'products.Customer.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'products.Customer.groups' or 'auth.User.groups'. products.Customer.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'products.Customer.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'products.Customer.user_permissions' or 'auth.User.user_permissions'. I am not sure what it is about, because I have changed all related_names in Foreign_Keys. Maybe someone can help me out with this, please. Thank you in advance :) Here is my models.py file: class Product(models.Model): product_id = models.UUIDField("A Product id", default=uuid.uuid4, editable=False) name = models.CharField(max_length=30, null=False, blank=False) description = models.CharField(max_length=500, null=True, default='') price = models.DecimalField('A price', null=False, blank=False, max_digits=4, decimal_places=2) image = models.ImageField(verbose_name='An image of the product', upload_to="img/") date_created = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return '/products/' def __repr__(self): return … -
Apache + Django ModuleNotFoundError: No module named 'project'
I'm having an issue with hosting my Django project with Apache on Windows. The website shows Internal Server Error and I'm getting the following stacktrace after visiting it: ModuleNotFoundError: No module named 'project'\r [Sat Aug 27 15:27:15.461267 2022] [wsgi:error] [pid 4664:tid 1944] [client 85.111.111.230:49768] mod_wsgi (pid=4664): Failed to exec Python script file 'C:/Users/Administrator/Desktop/vi_backend/project/wsgi.py'., referer: http://85.111.111.230:8000/ [Sat Aug 27 15:27:15.461267 2022] [wsgi:error] [pid 4664:tid 1944] [client 85.111.111.230:49768] mod_wsgi (pid=4664): Exception occurred processing WSGI script 'C:/Users/Administrator/Desktop/vi_backend/project/wsgi.py'., referer: http://85.111.111.230:8000/ vi_backend is the project root, it contains manage.py etc. Within that folder we have "venv" (virtual environment) and "project" which contains wsgi.py. Not sure why it is saying there's no module project, as project is not a module. httpd.conf tail LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" WSGIScriptAlias / "c:/users/administrator/Desktop/vi_backend/project/wsgi.py" WSGIPythonPath "C:/Users/Administrator/Desktop/vi_backend/venv/Lib/site-packages" <VirtualHost _default_:8000> <Directory "c:/users/administrator/Desktop/vi_backend/project"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "c:/users/administrator/Desktop/vi_backend/static/" <Directory "c:/users/administrator/Desktop/vi_backend/static/"> Require all granted </Directory> ErrorLog logs/anyFile-error.log CustomLog logs/anyFile-access.log common </VirtualHost> wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = get_wsgi_application() -
Seperate a field in the serializer response
This is my serializer and my problem is with the average_rating field. It's repeated in all the instances class ReviewSerializer(serializers.ModelSerializer): average_rating = serializers.SerializerMethodField(read_only=True) reviewer = serializers.SerializerMethodField(read_only=True) book = serializers.SlugRelatedField(slug_field='title', read_only=True) def get_average_rating(self, review): book_id = self.context['book_id'] return Review.objects.filter(book_id=book_id).aggregate(average_rating=Avg('rating')) class Meta: model = Review fields = ["id", "book", "reviewer", "description", 'rating', 'average_rating', ] what I get is this: [ { "id": 1, "book": "Clean Code: A Handbook of Agile Software Craftsmanship", "reviewer": "user1", "description": "aaaa", "rating": 5, "average_rating": { "average_rating": 4.5 } }, { "id": 2, "book": "Clean Code: A Handbook of Agile Software Craftsmanship", "reviewer": "user2", "description": "bbbb", "rating": 5, "average_rating": { "average_rating": 4.5 } }, ] but I need this: I don't want average_rating to repeat for all instances and make extra queries. what can I do here? [ "average_rating": { "average_rating": 4.5 }, { "id": 1, "book": "Clean Code: A Handbook of Agile Software Craftsmanship", "reviewer": "user1", "description": "aaaa", "rating": 5, }, { "id": 2, "book": "Clean Code: A Handbook of Agile Software Craftsmanship", "reviewer": "user2", "description": "bbbb", "rating": 5, }, ] -
ERROR: Could not build wheels for backports.zoneinfo, Error while installing django
I'm new to python development and I was trying using django but I'm facing this error while installing django using pip3 install django~=4.0. I tried few solution but none of them worked. I already tried Upgrading pip to latest version pip install backports.zoneinfo but that too failed. pip install --upgrade pip wheel I'm using Python 3.8.9 and mac M1 Collecting django~=4.0 Using cached Django-4.1-py3-none-any.whl (8.1 MB) Collecting backports.zoneinfo Using cached backports.zoneinfo-0.2.1.tar.gz (74 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB) Collecting asgiref<4,>=3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [41 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.14-arm64-cpython-38 creating build/lib.macosx-10.14-arm64-cpython-38/backports copying src/backports/__init__.py -> build/lib.macosx-10.14-arm64-cpython-38/backports creating build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template … -
Django model formset, "(Hidden field id) This field is required."
I'm trying to use a modelformset to update existing objcts, but cannot get the form to submit because (i'm assuming) the id associated with each object is not being passed by the form.I see "(Hidden field id) This field is required." in the template. My code models.py: class FoodItem(models.Model): name = models.CharField(max_length = 100) views.py: def edit(request): FormSet = modelformset_factory(FoodItem, include = ('name',)) if request.method == 'POST': formset = FormSet(request.POST) if formset.is_valid(): formset.save() else: formset = FormSet(queryset=FoodItem.objects.all()) return render(request, 'core/edit.html', {'formset': formset}) and the template: <form class="" action="." method="post" enctype="multipart/form-data"> {{ formset.management_data }} {% csrf_token %} {{ formset.as_p }} <input type="submit" name="" value="Update"> </form> I have aslo tried rendering each one individually and including hidden_fields: <form class="" action="." method="post" enctype="multipart/form-data"> {{ formset.management_data }} {% csrf_token %} {% for form in formset %} {{form.as_p}} {{form.hidden_fields}} {% endfor %} <input type="submit" name="" value="Update"> </form> but this didn't work. Thanks for any help with this. -
Hello am getting error in django Email send
ConnectionRefusedError at /contact/ [WinError 10061] No connection could be made because the target machine actively refused it Program are running normally when i open this page this error are Seenenter image description here {% csrf_token %} <div class="row" > <div class="col" style="margin-top: 50px;"> <input type="text" class="form-control" placeholder="First name" style="height: 50px;" name="fistname"> </div> <div class="col"style="margin-top: 50px;"> <input type="text" class="form-control" placeholder="Last name" style="height: 50px;" name="lastname""> </div> </div> <div class="form-group"style="margin-top: 50px;"> <input type="email" class="form-control"id="exampleFormControlInput1" placeholder="Enter Your Mail id " style="height: 50px;" name="email" > </div> <div class="form-group" style="margin-top: 50px;"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Please enter Your Messages here" style="height: 200px;" name="msg"></textarea> </div> <div class="text-center"> <button type="submit" class="btn btn-secondary btn-lg" style="margin-top: 50px;">Send Now</button> </div> </form> view.py def contact(request): if request.method == "POST": firstname = request.POST['firstname'] lastname = request.POST['lastname'] email = request.POST['email'] msg = request.POST['msg'] send_mail( 'Please check it', 'msg', 'settings.EMAIL_HOST_USER', ['email'], fail_silently=False, ) return render(request,'core/contact.html') setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com " EMAIL_PORT = 587 EMAIL_HOST_USER = "absc@gmail.com" EMAIL_HOST_PASSWORD ="kiubgwnoo" EMAIL_USE_TLS = True -
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 …