Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Kubernetes liveness probe fails when the logs show a 200 response
I am using https://pypi.org/project/django-health-check/ for my health checks in a Django app run through kubernetes_wsgi with the following YAML: livenessProbe: httpGet: path: /ht/ port: 8020 httpHeaders: - name: Host value: pdt-staging.nagyv.com initialDelaySeconds: 5 periodSeconds: 10 successThreshold: 1 failureThreshold: 10 readinessProbe: httpGet: path: /ht/ port: 8020 httpHeaders: - name: Host value: pdt-staging.nagyv.com initialDelaySeconds: 20 timeoutSeconds: 5 The pod logs claim that the probe was successful: INFO:twisted:"-" - - [22/Jul/2022:22:11:07 +0000] "GET /ht/ HTTP/1.1" 200 1411 "-" "kube-probe/1.22" At the same time, the pod events deny this: Liveness probe failed: Get "http://10.2.1.43:8020/ht/": context deadline exceeded (Client.Timeout exceeded while awaiting headers) ... and after a while, the pod regularly restarts. The pod seems to be fully functional. I can reach the /ht/ endpoint as well. Everything seems to work, except for the liveness probes. I read about slow responses causing the issue, but this is pretty fast. Any idea what the issue might be? -
How can I allow large file uploads on Django
I have a website www.theraplounge.co that allows users to upload videos. The problem is our limit on file sizes are to small. How can I increase the file size users are able to upload through my forms.py FileField? By the way I’m currently using Amazon S3. -
Django error handling - "exception" is not accessed - Pylance
I have the following views.py to handle 400, 403 and 404 error requests def handler400(request, exception): return render(request, "400.html", status=400) def handler403(request, exception): return render(request, "403.html", status=403) def handler404(request, exception): return render(request, "404.html", status=404) In my Project's urls.py file I have: handler400 = 'tasks.views.handler400' handler403 = 'tasks.views.handler403' handler404 = 'tasks.views.handler404' handler500 = 'tasks.views.handler500' The app that the views are in is named tasks. DEBUG = False is in my settings.py file. When I purposefully create an error, the error handler does not work. As mentioned, in my views.py file the "exception is not accessed - Pylance." Any help would be greatly appreciated. -
Python Django To save the old request post value and use it later
I want to save the request post value and use it later Do you know how to save the request value in Python and use it later? my_code(error) def send_form(request): if request.method == 'POST': selected_target = request.POST['target'] selected_template = request.POST['template'] -
Reverse for 'updatecategory' with arguments '({'category': <category: category object (1)>},)'
Can anyone help me with this, I try to fix out what is error?. I try to build the CRUD and I am in update now, I try to point the idea of the table and this happen please help I'm new to this I am watching youtube and try to do it Views.py update_category.html urls.py category.html -
DJANGO: NOT NULL constraint failed: courses_comment.lesson_id
I try create comments form add and take error. But I'm not shure that I correctly use lesson = at view.py at def post function. Can You help me? models.py: class Comment(models.Model): text = models.TextField('Comment text') user = models.ForeignKey(User, on_delete=models.CASCADE) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) view.py: class LessonDetailPage(DetailView): .... def post(self, request, *args, **kwargs): lesson = Lesson.objects.filter(slug=self.kwargs['lesson_slug']).first() post = request.POST.copy() post['user'] = request.user post['lesson'] = lesson request.POST = post form = CommentForms(request.POST) if form.is_valid(): form.save() part of urls.py path('course/<slug>/<lesson_slug>', views.LessonDetailPage.as_view(), name='lesson-detail'), forms.py: class CommentForms(forms.ModelForm): text = forms.CharField( label='Text', required=True, widget=forms.Textarea(attrs={'class': 'form-control'}) ) user = forms.CharField( widget=forms.HiddenInput() ) lesson = forms.CharField( widget=forms.HiddenInput() ) class Meta: model = Comment fields = ['text'] comment.html <div class="form-section"> <form method="post"> {% csrf_token %} {{ form }} <button type="submit">ОК</button> </div> And my Error IntegrityError at /course/linux/set-on-linux NOT NULL constraint failed: courses_comment.lesson_id Request Method: POST Request URL: http://127.0.0.1:8000/course/linux/set-on-linux Django Version: 4.0.6 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: courses_comment.lesson_id -
How do I resolve "Host key verification" django error on Heroku deployment?
I deployed to heroku with django, but I get an error. How can this be resolved? 2022-07-23T06:42:33.623380+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2022-07-23T06:42:33.623381+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2022-07-23T06:42:33.623381+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 848, in exec_module 2022-07-23T06:42:33.623381+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2022-07-23T06:42:33.623381+00:00 app[web.1]: File "/app/MovieReview/wsgi.py", line 16, in <module> 2022-07-23T06:42:33.623382+00:00 app[web.1]: application = get_wsgi_application() 2022-07-23T06:42:33.623382+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2022-07-23T06:42:33.623382+00:00 app[web.1]: django.setup(set_prefix=False) 2022-07-23T06:42:33.623383+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 19, in setup 2022-07-23T06:42:33.623383+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2022-07-23T06:42:33.623383+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ 2022-07-23T06:42:33.623383+00:00 app[web.1]: self._setup(name) 2022-07-23T06:42:33.623384+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup 2022-07-23T06:42:33.623384+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2022-07-23T06:42:33.623384+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ 2022-07-23T06:42:33.623384+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2022-07-23T06:42:33.623385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2022-07-23T06:42:33.623385+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-07-23T06:42:33.623385+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2022-07-23T06:42:33.623385+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 848, in exec_module 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "/app/MovieReview/settings.py", line 23, in … -
CustomUser has no field named 'username' django-allauth
I create a custom user model in django to remove username and use email as identifier for authentication purposes using this tutorial https://testdriven.io/blog/django-custom-user-model/ Then I want to use Google as my Authentication for my web-app. After following this tutorial. https://learndjango.com/tutorials/django-allauth-tutorial. When I try to login using my email it's give me an error CustomUser has no field named 'username' Then as I was searching for clues on how to fix this I found this post FieldDoesNotExist at /accounts/signup/, User has no field named 'username'. ACCOUNT_FORMS = {'signup': 'users.forms.UserChangeForm'} but this is for google signup I want users to login with their existing emails stored in my django-admin. this is my home.html {% load socialaccount %} <h1>My Google Login Project</h1> <a href="{% provider_login_url 'google'%}?next=/">Login with Google</a> I'll gladly add the rest of the code if needed. -
How to add comment without refreshing the page itself in django
I was making a blog website, I am new to django and I don't know how to add comment without refreshing the page itself. I was trying to do with the help of tutorial but they are not helping anymore here is my html file <div class="row"> <div class="comment-section col-8"> {% for i in data %} <li>{{i}}</li><br> {% endfor %} </div> <div class="col-4"> <h4 class="m-3">{{comments.count}} Comments...</h4> {% for j in comments %} <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{j.title}}</h5> <h6 class="card-subtitle mb-2 text-muted">{{j.visitor.name}}</h6> <p class="card-text">{{j.description}}</p> </div> </div> {% endfor %} <hr> <h3>Comment here</h3> <form method="post" id="comment-form"> {% csrf_token %} <input type="hidden" id="contentId" name = 'contentId' value="{{ result.id }}"> <div class="form-group"> <input type="hidden" id="name" name="name" class="form-control" value="{{request.session.user.name}}" readonly> </div> <div class="form-group"> <label for="title">Title</label> <input type="text" id="title" name="title" class="form-control"> </div> <div class="form-group"> <label for="description">Description</label> <textarea name="description" id="description" cols="30" rows="5" class="form-control"></textarea> </div> <button type="submit" class="btn btn-secondary">Submit</button> </form> </div> here is my views.py file def addComment(request): if request.method == 'POST': post_id = request.POST['contentId'] title = request.POST['title'] description = request.POST['description'] user = request.session['user']['id'] con = Comment( post_id=post_id, title=title, description=description, visitor_id=user, ) con.save() print() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
row num in Django REST Framework
Is there any way to assign increasing integers to queryset objects ? qs = self.get_queryser() I know that I can use enumerate function like this: for i, obj in enumerate(qs): print(i, obj) but this is not what I need , I want to have something like rownum pseudocolumn for each object of qs, so when I pass obj to any other function, rownum will be passed along with it. for obj in qs: some_func(obj) /* here obj should include rownum */ Thank you in advance -
Calling a django view inside of a playwright scraper function
a. I have a scraper function shown below where I need a captcha input in order to move ahead with the scraping. b. I need the flow to happen as follows: I click a button inside a Django view to start the scraping on a web page. The scraper starts running and reaches the page on the MCA website with the captcha. Playwright captures a screenshot of the captcha as an image and sends the same to a Django view to be rendered as an image on a page while Playwright waits for the input from the user in the Django view. A Django view loads the captcha on a page with a form seeking user input for the captcha. Once the user enters the captcha in the form inside of a Django view and submits it, the user input gets submitted to Playwright which then enters the captcha on the page and continues scraping the MCA website. The data collected by Playwright is returned as a dictionary and saved in a Django model. My question is how do I implement 3. and 4. above. The scraping code is below: """Get profile data from mca.gov.in for a given CIN or … -
Only displaying certain options in django form dropdown
Gday, I am creating a site to manage data for software with django. Users on the site are linked to divisions (regions) in a divisions model through a many to many field. The actual data is all linked to profiles, which are owned by divisions. Division users can edit profiles owned by the division, but not others. My issue is with forms to create profiles. Attached is an image of the form. The division field shows all divisions registered on the site, but I only want it to show ones that the logged in user is a member of. For example, this user is only a member of 'VATPAC' so it should only show that as an option to select. Attached is all the relevant code. Forms.py class ProfileForm(ModelForm): class Meta: model = models.Profile fields = ('division', 'name') widgets = { 'division': forms.Select(attrs={'class':'form-control'}), 'name': forms.TextInput(attrs={'class':'form-control'}) } views.py def AddProfile(request): submitted = False if request.method == "POST": form = forms.ProfileForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('profile?submitted=true') else: form = forms.ProfileForm if 'submitted' in request.GET: submitted = True return render(request,'profiles/create/create_profile.html', {'form': form, 'submitted': submitted}) models.py class Profile(models.Model): division = models.ForeignKey(Division, on_delete=models.CASCADE) name = models.CharField(max_length=255) def __str__(self): return self.name models.py (foreignkey for division) class … -
How to run Django with other non-Django page in same port of localhost in apache?
I am trying to run Django through apache2 (mod_wsgi) on xampp-portable-windows. FILE: xampp/apache2/conf/httpd.confd LoadFile "/Portable_PY/Python_Web/python310.dll" LoadModule wsgi_module "/Portable_PY/Python_Web/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "/Portable_PY/Python_Web" WSGIPythonPath "/Portable_PY/Python_Web/Lib/site-packages" WSGIScriptAlias / "/hung_collections/tempoTest/wsgi.py" FILE: xampp/apache2/conf/extra/httpd-vhosts.conf <VirtualHost *:80> DocumentRoot "/xampp/htdocs" ServerName localhost </VirtualHost> # non Django page <VirtualHost *:80> ServerName testhis.localhost DocumentRoot "/Testinsite" <Directory "/Testinsite"> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted </Directory> </VirtualHost> # Django app <VirtualHost *:80> ServerName heck.localhost <Directory "/hung_collections/tempoTest"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> After adding WSGIScriptAlias in httpd.conf file it runs the django site on heck.localhost, But running just localhost or localhot.test gives 403 forbidden error 403 forbidden error -
How do I dynamically change the value of text in html whenever a python variable is changed using ajax?
I'm using ajax, python, Django, HTML, and javascript for my project. I'd like to know if there is a in my HTML file like, <p class='text_box', id='tbox'> {{ text_variable_from_python }} </p> <input class='input_box', id='ibox', type='text'> Then I'd input some text into the input box, make a simple ajax request with the "text" variable and get an output from the server, which I would update on the views.py as, def main(request): if request.method == 'POST': new_text = request.POST['text'] context = {'text_variable_from_python': new_text} else: context = {'text_variable_from_python': 'You can change me!'} print(context) return render(request, 'Main.html', context=context) My question is, how do I send the data dynamically from the server to appear on client's webpage using ajax and python in between the two? Using my method, I can only see "You can change me!" on the webpage or nothing at all. No matter how many differing prompts I give, further changes do not show on the webpage. -
How can I fill my django form in two different template?
This is my models.py: class Person(models.Model): Person_ID = models.AutoField(blank=False, primary_key=True) p_SSN = models.CharField(blank=False, null=False, max_length=10) p_fName = models.CharField(null=False, blank=False, max_length=15) p_lName = models.CharField(null=False, blank=False, max_length=25) p_phoneNum = models.CharField(null=False, blank=False, max_length=11) p_birthDate = models.DateField(null=False, blank=False) p_Email = models.EmailField(null=False, blank=False, unique=True) p_Password = models.CharField(null=False, blank=False, max_length=20) At step 1 I want to fill my form except p_Email and p_Password. In step 2 (means next template) I want to initial p_Email and p_Password. this is my django form: class PersonForm(forms.ModelForm): p_fName = forms.CharField(max_length=15) p_lName = forms.CharField(max_length=25) p_SSN = forms.CharField(max_length=10) p_phoneNum = forms.CharField(max_length=11) p_birthDate = forms.DateField() p_Email = forms.EmailField(max_length=255) p_Password = forms.CharField(max_length=255) class Meta: model = Person fields = ['p_fName', 'p_lName', 'p_SSN', 'p_phoneNum', 'p_birthDate', 'p_Email', 'p_Password'] This is my views.py: def new_student(request): newStudentForm = PersonForm(request.POST or None) if newStudentForm.is_valid(): newStudentForm.save() return render(request, 'signUp_student.html', {'form': newStudentForm}) And my template for step 1 is : <form action="{% url 'new_student' %}" method="post"> {% csrf_token %} <label for="firstName">First Name</label><br> {{ form.p_fName }}<br> <label for="lastName">Last Name</label><br> {{ form.p_lName }}<br> <label for="firstName">SSN Code</label><br> {{ form.p_SSN }}<br> <label for="birthdate">Birthdate</label><br> {{ form.p_birthDate }}<br> <label for="phoneNumber">Phone Number</label><br> {{ form.p_phoneNum }}<br><br> <button type="submit">Sign up</button> </form> How can I initial my fields of class in different template? Thanks for giving your time to solve my … -
Slug page is not opening
My slug is coming into the url but the page linked with the page is not opening can anyone please help me with this. I have attached the code please see it and tell me the issue. btw it is a blog page. Models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(default=timezone.now()) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse("post_details", kwargs={"slug": self.slug}) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body { font-family: "Roboto", sans-serif; font-size: 18px; } .head_text { color: white; } </style> </head> <body> {% extends "base.html" %} {% block content %} <header class="masthead"> <div class="overlay"></div> <div class="container"> <div class="row"> <div class=" col-md-8 col-md-10 mx-auto"> <div class="site-heading"> <h3 class=" site-heading my-4 mt-3 text-white"> Welcome to my awesome Blog </h3> </p> </div> </div> </div> </div> </header> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for post in post_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p> <p … -
Django: ModuleNotFoundError: No module named 'name_project' after doing refactor
I have initialized a Django project with the help of Pycharm with "name_project" and for several reasons, I decided to refactor the name of the project and directory to "name". I am using Pycharm which to my understanding, if I refactor, automatically every related name with the old name will automatically change to a new name throughout the project. However, when I tried to run python manage.py runserver 8000 I received this error File "C:\Python39\lib\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 'name_project' I tried to go to that latest file that is listed there... I didn't find any name_project stated there. Where could I go wrong? This is my Django directory looks like project ├── project │ ├── aesgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ ├── wsgi.py └── templates │ ├── landing_page.html └── venv └── manage.py └── README.md -
Uncaught TypeError: Waypoint.Infinite is not a constructor at infinite_scroll.js:1:16
I am trying to use Jquery waypoints and infinite scroll on a Django app, but I keep getting this error for some reason. Can anyone tell me why? I already tried the answers from Waypoint.Infinite is not a constructor but they don't help me. Any suggestions? infinite_scroll.js var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], offset: 'bottom-in-view', onBeforePageLoad: function () { }, onAfterPageLoad: function () { } }); -
django-admin dose not create project
I'm running django 2.0.7 on a verual envirment python3 and when i run **django-admin startproject trydjango1 . ** the following error occers can you please help me to solve this problem Traceback (most recent call last): File "C:\Users\TG\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in run_module_as_main return run_code(code, main_globals, None, File "C:\Users\TG\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in run_code exec(code, run_globals) File "D:\django-projects\Test1\Scripts\django-admin.exe_main.py", line 7, in File "D:\django-projects\Test1\lib\site-packages\django\core\management_init.py", line 371, in execute_from_command_line utility.execute() File "D:\django-projects\Test1\lib\site-packages\django\core\management_init.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\django-projects\Test1\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "D:\django-projects\Test1\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "D:\django-projects\Test1\lib\site-packages\django\core\management\commands\startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "D:\django-projects\Test1\lib\site-packages\django\core\management\templates.py", line 117, in handle django.setup() File "D:\django-projects\Test1\lib\site-packages\django_init_.py", line 16, in setup from django.urls import set_script_prefix File "D:\django-projects\Test1\lib\site-packages\django\urls_init_.py", line 1, in from .base import ( File "D:\django-projects\Test1\lib\site-packages\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "D:\django-projects\Test1\lib\site-packages\django\urls\exceptions.py", line 1, in from django.http import Http404 File "D:\django-projects\Test1\lib\site-packages\django\http_init_.py", line 5, in from django.http.response import ( File "D:\django-projects\Test1\lib\site-packages\django\http\response.py", line 13, in from django.core.serializers.json import DjangoJSONEncoder File "D:\django-projects\Test1\lib\site-packages\django\core\serializers_init_.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "D:\django-projects\Test1\lib\site-packages\django\core\serializers\base.py", line 6, in from django.db import models File "D:\django-projects\Test1\lib\site-packages\django\db\models_init_.py", line 3, in from django.db.models.aggregates import * # NOQA File "D:\django-projects\Test1\lib\site-packages\django\db\models\aggregates.py", line 5, in from django.db.models.expressions … -
Dynamic Serialization for related fields
I have the following models: class Country(models.Model): """ Country model """ # With name and isoCode (charfield) ... class State(models.Model): """ State model """ # With name and isoCode (charfield) country = models.ForeignKey(Country, on_delete=models.CASCADE) ... class City(models.Model): """ City model """ name = models.CharField(max_length=32) state = models.ForeignKey(State, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE) ... And UserLocation referenced by: class Location(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="location") country = models.ForeignKey(Country, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) city = models.ForeignKey(City, on_delete=models.CASCADE) How do I build a serializer that creates UserLocation, as well as return the info in JSON? I have tried class LocationSerializer(serializers.ModelSerializer): country = serializers.SlugRelatedField(slug_field="isoCode", queryset=Country.objects.all()) state = serializers.SlugRelatedField(slug_field="isoCode", queryset=State.objects.filter(country__isoCode=country)) city = serializers.SlugRelatedField(slug_field="name", queryset=City.objects.all()) class Meta: model = Location fields = ["user", "country", "state", "city"] But it does not work, it gives the error {"state":["Object with isoCode=BC does not exist."],... How does one create a dynamic linked serializer? Or how does one work around this? -
Django: unsupported operand type(s) for +: 'int' and 'method' when creating function in Django
i am writing a function in my model to get the cart total, but i keep getting this error and i don't seem to know exactly what is going wrong - unsupported operand type(s) for +: 'int' and 'method'. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) transaction_id = models.CharField(max_length=1000, null=True, blank=True) completed = models.BooleanField(default=False) active = models.BooleanField(default=True) date_ordered = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.customer.user.username} - {self.transaction_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 = int(sum([item.quantity for item in orderitems])) return total -
How to combine values from 2 queryset
I do have two queryset both having common field 'month' i want to combine both query set using field 'month' six_months_ago = date.today() + relativedelta(months=-6) ###### Geting number of New Patient registration by month (for last six month) patient_per_month = patientprofile.objects.filter(pat_Registration_Date__gte=six_months_ago)\ .annotate( month=Trunc('pat_Registration_Date', 'month') ) \ .order_by('month') \ .values('month') \ .annotate(patient=Count('month')) print(patient_per_month) ###### Geting number of visit by month (for last six month) visits_per_month = visits.objects.filter(visit_date__gte=six_months_ago)\ .annotate( month=Trunc('visit_date', 'month') ) \ .order_by('month') \ .values('month') \ .annotate(visits=Count('month')) print(visits_per_month) Both printing ad below: <QuerySet [{'month': datetime.date(2022, 2, 1), 'patient': 1}, {'month': datetime.date(2022, 3, 1), 'patient': 1}, {'month': datetime.date(2022, 4, 1), 'patient': 1}, {'month': datetime.date(2022, 5, 1), 'patient': 2}, {'month': datetime.date(2022, 6, 1), 'patient': 2}, {'month': datetime.date(2022, 7, 1), 'patient': 18}]> <QuerySet [{'month': datetime.date(2022, 5, 1), 'visits': 6}, {'month': datetime.date(2022, 6, 1), 'visits': 7}, {'month': datetime.date(2022, 7, 1), 'visits': 12}]> I want combine both of these query set as one by 'month' field something like below. <QuerySet [{'month': datetime.date(2022, 2, 1), 'patient': 1, 'visits': 0}, {'month': datetime.date(2022, 3, 1), 'patient': 1, 'visits': 0}, {'month': datetime.date(2022, 4, 1), 'patient': 1, 'visits': 0}, {'month': datetime.date(2022, 5, 1), 'patient': 2, 'visits': 6}, {'month': datetime.date(2022, 6, 1), 'patient': 2, 'visits': 7}, {'month': datetime.date(2022, 7, 1), 'patient': 18'visits': … -
Django Queryset Design: Filtering out soft-deleted users?
I have a soft-delete user model in Django, where we set is_active to False. But one problem I'm running into is needing to filter out is_active users on every type of content: Item.objects.filter(user__is_active=False, ...) Comment.objects.filter(user__is_active=False, ...) User.objects.filter(is_active=False, ...) And so-on. Is there some type of Django / Pythonic design pattern I can use here to avoid needing to manually filter out all users every time I query something made by a user, or a current list of users? -
How to remove "Currently" tag and link in django filefield
Basically, on the website it says currently: and then its the name of the file that was uploaded and im wondering how to remove the "currently" and the name of the file that was uploaded. ps: sorry if i didn't explain well im not the best at it pfp_url = models.FileField() bg_pfp = models.FileField() Heres a more indepth image -
ModuleNotFoundError: No module named 'django_apscheduler' when I migrate my file with heroku
I want to update my heroku site with this command heroku run python manage.py migrate, but the error appeared: » Warning: heroku update available from 7.53.0 to 7.60.2. Running python manage.py migrate on ⬢ mighty-harbor-18334... up, run.5980 (Free) Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/app/.heroku/python/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/config.py", line 223, in create import_module(entry) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_apscheduler' I installed django_apscheduler with pip install django_apscheduler for sure. My python version is 3.10.2, and in my settings.py, the app module is in INSTALLED_APPS such: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' 'django_apscheduler', ] I am not sure why the ModuleNotFoundError would occured, any help will be appreciated.