Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can an object be deleted if another one is emty?
So, I am a begginer coding an e-commerce project on Django. I've managed to add a "delete item"function to remove items from the cart. However, when the item is removed, the order isn't. OrderItem and Order are 2 sepparate models, I'd like so that when an OrderItem i fully deleted and the cart is empty, for the order itself to be deleted too. I'll attach de code for the models and the functios. Order mode: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total OrderItem model: class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total The function for deleting the items: def eliminaritem(request, id): if request.method == "POST": item = OrderItem.objects.get(product = id) item.delete() return render(request, "store/deletecartitem.html", {'item': item}) if OrderItem.objects.all == None: customer = customer = request.user.customer order = Order.objects.all(customer = customer) order.delete() The first … -
Django ListView filter and orderby with pagination
I'm building a simple e-commerce website. I'm using ListView to represent home page of website that displays items. I want to be able to filter Items by their category and be able to order by some factor (for example price). By default it should show all items. And if there is another page of items of given kind it should keep filter. Also an explanation would be greatly appreciated. My code: views.py from django.views.generic import ListView, from .models import ShopItem class HomeView(ListView): model = ShopItem paginate_by = 2 template_name = "home-page.html" def get_queryset(self): q = self.request.GET.get('filter', '') if not q: return self.model.objects.all() return self.model.objects.filter(category=q) models.py from django.db import models class ShopItem(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) description = models.TextField() category = models.CharField(max_length=15) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) slug = models.SlugField() home-page.html <li class="nav-item active"> <a class="nav-link" href="/">All <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Necklace</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Earrings</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Bracelets</a> </li> {% if is_paginated %} <nav class="d-flex justify-content-center wow fadeIn"> <ul class="pagination pg-blue"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} {% for page in page_obj.paginator.page_range … -
How to I log into the admin panel in django without manually typing url into search bar [closed]
Am a newbie and am wondering how Ill login into the admin panel once am done with the website. my thought was to add redirect in the frontend buh I dont seem to see it done in other sites. What can I do? thanks -
Tag of a Django Template from a variable
I need to do a form with Django which can have both "select" or "input" tags, depending on a variable. Here's how I pass the variable to the html (file: views.py): from django.shortcuts import render, redirect from direzione.models import Jobs, JobType from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.template.defaulttags import register from login import views as lgnwv import json # Create your views here. @register.filter def get_item(dictionary,key): return dictionary.get(key) @login_required(login_url=lgnwv.login) def fattura(request): if request.method =="POST": if request.POST.get('logout') == 'logout': logout(request) return redirect(lgnwv.login) else: datas = JobType.objects.get(jobType=0) dts = json.loads(datas.inputs) job = Jobs.objects.get(id_job=1) jobName = job.nome jobHead = datas.headNome return render(request, 'fattura/fattura.html', {"dts": dts, "inputs":dts["inputs"], "jobName":jobName, "jobHead":jobHead}) So, the variable that contains the string 'input' or 'select' is into the dict inputs (the one that's looped) This is my form: <div class="form" style="height:{{ dts|get_item:'height' }}px"> <div class="title">Crea Fattura</div> <div class="subtitle">Compila tutti i campi correttamente.</div> {% for key, value in inputs.items %} <div class="input-container ic2"> <{{ value|get_item:'tag' }} id="{{ key }}" autocomplete="off" class="input" type="{{ value|get_item:'inputType' }}" placeholder=" " /> <div class="cut" style="width: {{ value|get_item:'cutWidth' }}px"></div> <label for="{{ key }}" autocomplete="off" class="placeholder">{{ value|get_item:'placeholder' }}</label> </div> {% endfor %} <button type="text" class="submit">Invia</button> </div> The line where I have the problem is the … -
I can't start my django project after some code updates. I was revert everything back, but it still not working
I don't think that error in code. I did git reset --hard <commit> to last work version, and it was still broken The error when i'm use runserver command: Traceback (most recent call last): File "/usr/local/lib/python3.9/dist-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/dist-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/usr/local/lib/python3.9/dist-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/dist-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/usr/local/lib/python3.9/dist-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/usr/local/lib/python3.9/dist-packages/django/conf/__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.9/dist-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crm/crm/settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/root/club2/crm/manage.py", line 22, in <module> main() File "/root/club2/crm/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/dist-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/dist-packages/django/core/management/__init__.py", line 440, … -
How to redirect logged-in user to a specific page in Django
Code was not written by me, I am just trying to find a way to redirect a logged-in user if he wants to access a certain page in a Python/Django script. I can actually do it in Templates but as far as I understand this logic should be implemented in Views. Example: Already logged-in user tries to access to signup page by typing the signup page url/path. In this case, I would like to redirect the user to the homepage (/). What I tried with very very basic Python and zero Django knowledge?. Inside the views/auth.py (SignUp class), I try to write a get method and check if user is already authenticated, redirect him to a specific page. And actually it worked for already logged-in users but if a guest/visitor wants to open the sign up page then it returns an error: "views.auth.SignUp didn't return an HttpResponse object. It returned None instead." class SignUp(FormView): form_class = SignUpForm template_name = "xxx/registration/signup.html" # I added def get(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect('/') def form_valid(self, form): user = form.save(commit=False) user.username = form.cleaned_data.get("username").lower() user.theme = get_theme_from_cookie(self.request) user.save() send_email_confirmation(user, user.email) notifications.info( self.request, _( "confirmation message.." ), ) return redirect("login") and here is the … -
How to save screenshot to CloudinaryField in django using chromedriver on Heroku?
When I do driver.save_screenshot, even if return returns true, the file is not there. How do I save the screen_shot to the database? someone teach me... #models.py class UploadedImage(models.Model): image = CloudinaryField('image', blank=True, null=True, folder="media") author = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True ) created_at = models.DateTimeField(auto_now_add=True) token = models.CharField(max_length=256, null=True, blank=True) #views.py options = Options() options.add_argument('--disable-gpu') options.add_argument('--disable-extensions') options.add_argument('--proxy-server="direct://"') options.add_argument('--proxy-bypass-list=*') options.add_argument('--start-maximized') options.add_argument('--headless') options.add_argument('--no-sandbox') driver = webdriver.Chrome(executable_path=driver_path, chrome_options=options) driver.get('https://weather.yahoo.co.jp/weather/') driver.set_window_size(1250, 1036) driver.save_screenshot('/app/a.png') UploadedImage.objects.create(image='/app/a.png') return HttpResponse("Success", request) -
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.