Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django: getting data from modal gives <built-in function id> error
I'm trying to get a value from a modal, that gets the value using jQuery from a list. Let's explain. I have a list of objects in an HTML page using a for loop, and in each row, there is a delete button. This delete button launches a confirmation Modal. To get the id of the row and use it in the Modal, I use jQuery: {% for a in objects %} [...] <td><button type="button" class="delete-button" data-name="{{ a.id }}" data-bs-toggle="modal" data-bs-target="#deleteModal">Delete</button></td> [...] {% endfor %} [...] <div class="modal fade" id="deleteModal"> [...] <form action="{% url 'delete_object' %}" method="post"> {% csrf_token %} <input type="hidden" name="object_id" name="object_field" /> <button type="submit">Delete</button> [...] <script> $('.delete-button').click(function() { $('#object_id').html($(this).data('name')) }) </script> Without explaining the urls.py part, let's get straight to the view, which is quite simple: def cancel_request(request): _id = request.POST.get("object_id") obj = Object.objects.get(id=id) obj.status = "Annulé" obj.save() return redirect("home") When I run the modal, I make sure I can see the id value getting in the modal, but when I try to put it in an input, I cannot see it anymore. If I put it in an h5 tag for example: <h5 class="modal-title" id="request_id" name="requestid_kw"></h5>, it shows on the modal, but still does not get … -
Post_save method in django
I've have stuck in a problem where if both the person follows the each other only then it should make them friends. I'm planning to use Django signal's post save method for this. But I'm not able to make any progression in it .Please help me on this .Thanks in advance and do refer the code below and sorry for bad coding. Models.py: class Follow(models.Model): Follower=models.ForeignKey(User, models.SET_NULL,null=True,related_name='from_user_followers',blank=True) Followe=models.ForeignKey(User,models.SET_NULL,null=True,related_name='to_user_followers',blank=True) created=models.DateTimeField(default=now) @receiver(post_save, sender=Follow) def create_friend(sender, instance, created, **kwargs): if created: see_followe_is_following_back = Follow.objects.filter(Followe=instance.Follower, Follower=instance.Followe) see_follower_is_following_back = Follow.objects.filter(Follower=instance.Followe, Followe=instance.Follower) try: if str(instance.Follower) == str(see_follower_is_following_back) and str(instance.Followe) == str(see_followe_is_following_back): create_friends= Friends.objects.update_or_create(from_user=instance.Followe , to_user=instance.Follower) return create_friends else: pass except Exception as e: return str(e) else: pass class Friends(models.Model): from_user=models.ForeignKey(User, models.SET_NULL,null=True,related_name='from_user_friends',blank=True) to_user=models.ForeignKey(User,models.SET_NULL,null=True,related_name='to_user_friends',blank=True) created=models.DateTimeField(default=now) -
In Heroku , python setup.py egg_info did not run successfully. error in troposphere setup command: use_2to3 is invalid
So, I am trying to deploy this django project on the Heroku platform and while making all the requirements running on the local server while this code is added to Heroku and it installs it on its server, It throws an error and didn't resolved, Even after lot of tries. Problem is with the setup.py installation and troposphere. I tried commands like:- pip install --upgrade setuptools. But this also didn't worked it gave the same error. For reference dropping my requirements:- argcomplete==1.12.3 asgiref==3.4.1 autopep8==1.5.7 awsebcli==3.20.3 boltons==21.0.0 boto3==1.18.16 botocore==1.23.54 cachetools==4.2.2 cement==2.8.2 certifi==2021.5.30 cfn-flip==1.2.3 charset-normalizer==2.0.4 click==8.0.1 colorama==0.4.3 dj-database-url==1.0.0 Django==3.2.6 django-cors-headers==3.7.0 djangorestframework==3.12.4 durationpy==0.5 factory-boy==3.2.0 Faker==8.11.0 future==0.16.0 google-api-core==2.0.1 google-auth==2.0.2 google-cloud-language==2.2.2 google-cloud-vision==2.4.2 googleapis-common-protos==1.53.0 grpcio==1.39.0 gunicorn==20.1.0 hjson==3.0.2 idna==3.2 jmespath==0.10.0 joblib==1.0.1 kappa==0.6.0 packaging==21.0 pathspec==0.9.0 pep517==0.11.0 pip-tools==6.2.0 placebo==0.9.0 proto-plus==1.19.0 protobuf==3.17.3 psycopg2==2.9.5 psycopg2-binary==2.8.4 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.7.0 pycountry==20.7.3 PyJWT==1.7.1 pyparsing==2.4.7 pypiwin32==223 python-dateutil==2.8.2 python-http-client==3.3.2 python-slugify==5.0.2 pytz==2021.1 pywin32==305 PyYAML==5.4.1 regex==2021.8.28 requests==2.26.0 rsa==4.7.2 s3transfer==0.5.0 semantic-version==2.8.5 sendgrid==6.8.1 sentry-sdk==1.10.1 six==1.14.0 sqlparse==0.4.1 starkbank-ecdsa==1.1.1 termcolor==1.1.0 text-unidecode==1.3 toml==0.10.2 tomli==1.2.1 tqdm==4.62.0 troposphere==2.7.1 twilio==6.63.1 urllib3==1.26.12 wcwidth==0.1.9 Werkzeug==0.16.1 whitenoise==6.2.0 wsgi-request-logger==0.4.6 zappa==0.53.0 -
Integrating a Django project with FreeRADIUS and Coovachilli
How do I integrate a django project with FreeRADIUS and Coovachilli? I have looked for any documentation that can help, but I can only find PHP guides. I also have checked out OpenWisp, but it does not fit my requirements (too complex). So is there any guide on integrating a django project with FreeRadius and Coovachilli? -
can't open file 'manager.py': [Errno 2] No such file or directory
I'm trying to creat an aplication usign python and django, but this error keeps happening. What I've already tried: put python path and script in environment variables reinstall python reinstall django close and open vscode (I thought it was an update issue) run the server inside setup - the application folder If anyone can help me, very much. -
Django redirect /D/<anything> to /d/<anything>
I'm looking for a way to redirect any url that start with /D/ to the same URL with lowercased /d/. /D/<anything_including_url_params> to /d/<anything_including_url_params> I literally only want to redirect urls that start with /D/ - not /DABC/ etc... The suffix can also be empty, eg. /D/ > /d/ Is there a way to do that in Django? It is for a third-party app with urls included in projects urls. The alternative is to use re_path and change: path("d/", include(...)) to re_path(r"^[dD]/$", include(...)) but I'd rather do a redirect instead of this. -
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
I'm trying to deploy it on Railway. This error is coming. raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) Image of the error coming -
Django images not showing up in template
I've spent the whole day trying to find a solution for showing the images in the template but I couldn't find any solution to my case. This is my settings STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'DataCallGuide/static') ] My model class TroubleshootingSteps(models.Model): box_header = models.CharField(blank=True, null=True, max_length=250) box_content = models.CharField(blank=True, null=True, max_length=250) box_botton = models.CharField(blank=True, null=True, max_length=250) header = models.TextField(blank=True, null=True) sub_header = models.TextField(blank=True, null=True) text1 = models.TextField(blank=True, null=True) image1 = models.ImageField(blank=True, null=True, upload_to="images/") and the template {% extends 'base.html' %} {% load static %} {% block content %} <div class="container overflow-hidden"> <div class="text-center"> <h4 class="mt-5 mb-5">{{data.header}}</h4> </div> <h3 dir="rtl" class="rtlss">{{data.sub_header}}</h3> <img src="{{ data.image1.url }}"> </div> {% endblock%} Also when I click on the image link in admin pages it doesn't show the image and display page not found error with the below link http://127.0.0.1:8000/media/images/IMG-20220901-WA0009.jpg What is wrong please? -
Django IO bound performance drop with gunicorn + gevent
I have been working on an IO bound (only simple queries to database for getting info or updating it) application written in Django. As application is mostly db and redis queries, I decided to use gunicorn with async gevent worker class, but the weird part is that eventhough I'm running gunicorn with gevent (also monkey patched db for that purpose), I'm not seeing any performance gain by it, in fact, both requests/s and response time has dropped. Steps taken To do so, I have done the following: Installed greenlet, gevent & psycogreen as instructed in official docs. Patched postgres with psycogreen.gevent.patch_psycopg (tried wsgi.py, settings.py and post_fork in gunicorn) but to no avail. Tried running gevent's monkey.patch_all manually, also no use. This is my gunicorn.config.py: import gunicorn gunicorn.SERVER_SOFTWARE = "" gunicorn.SERVER = "" bind = "0.0.0.0:8000" worker_class = 'gevent' worker_connections = 1000 # Tested with different values keepalive = 2 # Tested with different values workers = 10 # Tested with different values loglevel = 'info' access_log_format = 'sport %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' def post_fork(server, worker): # also tried pre_fork and on_starting from psycogreen.gevent import patch_psycopg patch_psycopg() Result But the app only got slower, also note … -
django background longrunning tasks without celery
when writing the django-backend, we abandoned the use of Celery in favor of Process because we failed to cancel already running tasks but now we have to schedule long-runnning tasks that should be executed every 5 minutes or every 5 hours or every 3 hours (it's not necessary to be able to cancel them, of course, but I REALLY don't want to use celery) everywhere I saw that periodic tasks from celery were used to solve this problem, I want to find out what alternatives there are, it is important that it is performant and works on both windows and linux now we use such a code, we are satisfied with everything, except for a potentially bad performance # in tasks/management/commands/work class Command(BaseCommand): def handle(self, *args, **options): while(True): do_work() # work executed every 3 hours time.sleep(60 * 60 * 3) # sleep 3 hours # in tasks/management/commands/another_work class Command(BaseCommand): def handle(self, *args, **options): while(True): do_another_work() # work executed every 5 hours time.sleep(60 * 60 * 5) # sleep 5 hours how terrible is it to have several such tasks with while(True) + sleep in terms of performance? i wonder what code to solve this problem is at the heart of … -
Django - ForeignKey Filter Choices
I'd like to filter the choices that a user can choose in my ForeignKey Field. I basically have a ForeignKey for the subject of the Test and the actual topic of the Test. These topics come from a different model and are linked to a subject. Now I'd like to filter the choices to only include the topics that are linked to the currently selected subject. Is that possible and if so, how? models.py class Test(models.Model): student = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) thema = models.ForeignKey(Thema, on_delete=models.CASCADE, blank=True, null=True) school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, blank=True, null=True) grade = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(6)], blank=True, null=True) date = models.DateField(default=datetime.date.today) def save(self, *args, **kwargs): if not self.school_class and self.student: self.school_class = self.student.klasse return super().save(*args, **kwargs) class Thema(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) thema = models.CharField(max_length=50) -
Send a dict from js to views: return querydict who bursts my dict
I have a dict that I would like to send but I receive it in the form of a querydict whose content is no longer in the same form as the dict sent. How can i have an object that i can manipulate simply ? I would like to add the elements in a database so I should do a for loop and add by index (key1, key2) but I can't get the real length when i do len(request.POST) it return 5. .js function sendData(event){ const res = { 0:{"val1": 1, "val2":2}, 1:{"val1": 3, "val2":4}} ... $.ajax({ ... data: { "result": res, }, dataType: "json", ... }) } views.py def view1(request): print(request.POST) $ <QueryDict: {'csrfmiddlewaretoken': ['...'], 'result[0][val1]': ['1'], 'result[0][val2]': ['2'], 'result[1][val1]': ['3'], 'result[1][val2]': ['4']}> -
Set default values in Django form based on user's id/instance
I have created a customUser, then the foreign key of model class AddressBook (models.Model) is customUser.Id. Model Employer inherited from customUser. The other two models are class employee(CustomUser) and class Job(models.Model) Employer and Staff user could create a job. Now I would like to set fields of Employer and AddressBook in job form to be corresponding employer_org name and employer address if login user is employer. i.e. if employer 1 login, the job form will automatically show employer 1 org name and employer1 address. If employer 2 login, the fields will be employer2 org name and employer2 address. When Staff users sign in, they can select or type employer org name and employer address. Now my problem is even I sign in as employer 1, I can create a job for employer 2 when click the selection field. Here is my models: class AddressBook(models.Model): user=models.ForeignKey(get_user_model(),on_delete=models.CASCADE) street = models.CharField(max_length=64,blank=False) alt_line = models.CharField(max_length=64, blank=True) postcode= models.CharField(max_length=5, validators=[RegexValidator('^[0-9]{5}$', _('Invalid postal code'))], blank=False) city = models.CharField(max_length=64, blank=False) country = models.CharField(max_length=64, default="some name") class Meta: verbose_name = 'AddressBook' def __str__(self): return '{} {}, {}, {}'.format(self.street, self.alt_line, self.postcode, self.city) class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=250, blank=False) last_name = models.CharField(max_length=250, blank=False) email = models.EmailField(('email address'), unique=True) phone … -
How to access the value of a foreign key in a table in django?
I've 2 tables in a database on phpmyadmin that are connected by a foreign key. The table "bulle" contains the foreign key of the table "site". In enghlish : one "site" can contain some "bulles" (or not) and a "bulle" is always linked to a "site". class Bulles(models.Model): id_bulle = models.AutoField(primary_key=True) num_bulle = models.CharField(max_length=20) type_bulle = models.CharField(max_length=20) colories = models.CharField(max_length=20) latitude = models.FloatField() longitude = models.FloatField() date_vidange = models.DateField( db_column="date_vidange" ) id_depot = models.ForeignKey( "Depot", on_delete=models.CASCADE, db_column="id_depot" ) id_site = models.ForeignKey( "Site",related_name='bul', on_delete=models.CASCADE, db_column="Id_site" ) class Meta: db_table = "bulles" class Site(models.Model): id_site = models.AutoField( db_column="Id_site", primary_key=True ) nom = models.CharField( db_column="Nom", max_length=100 ) vitesse_b = models.FloatField(db_column="Vitesse_b") # Field name made lowercase. vitesse_c = models.FloatField(db_column="Vitesse_c") # Field name made lowercase. ecart_type_b = models.FloatField( db_column="Ecart_type_b" ) ecart_type_c = models.FloatField( db_column="Ecart_type_c" ) type_site = models.CharField( db_column="Type_site", max_length=20 ) longitude = models.FloatField(db_column="Longitude") latitude = models.FloatField(db_column="Latitude") Nombre_bulles = models.IntegerField(db_column="Nombre_bulles") date_vidange = models.DateField( db_column="Date_vidange") class Meta: db_table = "site" I've created a request to delete a row in "bulle" selected by the id_bulle (primary key). I'd like to get the "id_site" from this selected bulle that I delete in this request. Then, I need to count every "bulles" of the table that have this id_site. … -
Django formtools gets caught in a loop
I'm working on a multistep form using django-formtools lib, and I'm facing a flow problem. In a specific step (fotoFormulaMedica) I have two buttons where basically the user choose his pathway. Either "take photo" or "choose a file". If he choose to take photo, it'll take him to the step called foto and then, once he clicks in continue, it'll continue the rest of the steps. So the next step will be avisoDireccion. If he choose to "choose an image", it'll take stay in the current step, he'll select an image from his pc and then, once he clicks in continue will continue the rest of the steps. So the next step will be avisoDireccion. It works great!, however, when all the steps are filled, instead of take to the done.html, he goes back to fotoFormulaMedica and the user gets caught in a loop. This is the repo https://github.com/Alfareiza/logifarma-radicar-domicilio/tree/1.configurando-cargar-y-tomar-foto Also you can check here my : views.py https://github.com/Alfareiza/logifarma-radicar-domicilio/blob/1.configurando-cargar-y-tomar-foto/core/apps/base/views.py forms.py https://github.com/Alfareiza/logifarma-radicar-domicilio/blob/1.configurando-cargar-y-tomar-foto/core/apps/base/forms.py I'll appreciate your help. I've tried to make the flow not including one of the pathways. I mean, if I exclude the take photo feature or select file feature. The flow works as I expected. -
making form filters interact with each other django
So I have a page in django that have a couple of forms that work as content filters. self.fields["brand"] = forms.ChoiceField( label="Brand", choices=self.__get_brand_choice(), widget=forms.Select(attrs={"class": "form-select",'onchange': 'submit();'}), required=False, ) def __get_brand_choice(self): products_id = ( SalesView.objects.filter(business_unit=self.business_unit).values_list("brand", flat=True).distinct() ) products_brand = Brand.objects.filter( id__in=products_id ).values_list("id", "name").order_by("name") return [ (None, "TODAS"), *products_brand, ] this for example is the two parts of the brand filterb (but all of them are basicaly the same), I have other to related to product type and sales volume. At the moment, when I select one option on of them the others it filters the page content but it doesn't filter the options of the other so I can only choose valid options. That's what I want to change, I want them to interact. For example, if I want to filter bread on the page I also want the brand filter to only show brands that have bread, and if I choose I certain brand I want the product type filter to only show products type related to this brand. I know that basically i have to pass this other parameter(s) in the orm query that quet the product list, but am not sure how to get these parameters from the … -
I'm facing issues in sql fetch data in django ? It returns None
This is test.py from django.http import HttpResponse import mysql.connector MySQLdb = mysql.connector host = 'xxxxxx' username = 'xxxx' db = 'xxxx' port = '3306' password = 'xxxxxx' class sql: def __int__(self): pass def mysql_connection(self): try: mysql_conn = mysql.connector.connect(host=host, user=username, database=db, password=password, port=port, ssl_disabled=True) print("Connection Successfully Established...") return mysql_conn except Exception as e: print("mysql connection error".format(e)) exit(0) def update_approval(self, que): d = self.mysql_connection() cursor = d.cursor() cursor.execute(que) result = cursor.fetchone() return result This is my views.py from django.shortcuts import render, redirect from .forms import InputForm, TestForm from django.core.mail import send_mail from .test import sql import mysql.connector MySQLdb = mysql.connector def index(request): if request.method == "POST": form = InputForm(request.POST) # ids = form["git_Id"].value() # print(ids) # query = f'SELECT request_id FROM request_form_mymodel where git_Id={ids};' # # p = obj.update_approval(query) obj = sql() # git_id = 5666 ids = form.data["git_Id"] print(ids) # query = "SELECT request_id FROM request_form_db.request_form_mymodel where git_Id='%s'" % ids q = "SELECT request_id FROM request_form_db.request_form_mymodel where git_Id={}".format(ids) p = obj.update_approval(q) print(p) approve_url = f"http://my_url_path/test?request_id={p}" if form.is_valid(): send_mail( 'KSA Test Activation', approve_url, 'my_sender_email_id', ['receiver_id'], fail_silently=False, ) form.save() form = InputForm() else: form = InputForm() return render(request, 'home.html', {'form': form}) This is forms.py ` from django import forms from .models import MyModel, … -
Everytime i try to install Django using "pip install django" on my command prompt why does this come up?
pip install Django 'pip' is not recognized as an internal or external command, operable program or batch file. -
Django: Retrieve a list of one model property for all distinct values of another property
I’d like to use the Django ORM to give me a list values of a model property for the subset of objects that have a distinct value of another property. Consider a simple model like: class Result(models.Model): color = models.CharField() score = models.IntegerField() And imagine that I have four results: results = [ Result(color="blue", score=5), Result(color="blue", score=3), Result(color="red", score=10), Result(color="red", score=8), ] What I'd like to get is something like the following: { {"color”: "blue", "scores": [5, 3]}, {"color": "red", "scores": [10, 8]}, } I think it's possible to get there in one shot using Django's aggregation and annotation features, but I'm struggling to figure it out. I know I can get the average score with the following: results.values("color").annotate(avg_score=Avg("score")) If that's possible, then getting the list used to generate the average must also be possible, right? -
How to store important queries in Djando models itself?
there are couple of queries which are important and used several times in different part of application. I wounder it would be great to have a method in the Model itself to retrieve requested data as needed. tried Classmethod and instance method but as the Manager is called in the query I got below error: AttributeError: Manager isn't accessible via ... instances code is look like below: class XDL(models.Model): name = models.CharField(max_length = 20) Order_Code_Description = models.CharField(max_length = 355) Status = models.CharField(max_length = 20) Supplier = models.CharField(max_length = 100) @classmethod def get_count_xdls(cls): return cls.objects.all() #query example def get_all_supps(self): return self.objects.all() #query example explained in Django documentation below: Managers are accessible only via model classes, rather than from model instances, to enforce a separation between “table-level” operations and “record-level” operations Is there a best practice to store important queries in a method somewhere in Model (or other parts)? as these queries run several time and also writing it as a method help the documentation as well. -
Django: only CSS is not served by Nginx
I deployed my Django app on a VPS with Nginx and I want Nginx to handle the statics. The strange thing right now is that all the images are rendered properly, but the CSS is not working at all... Django setting: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') Nginx configure: location /static/{ alias /home/xxx/App/django_app/static_root/; } In html template: <link rel="stylesheet" href="{% static 'app1/css/style.css' %}" type="text/css" media="all"> <img src="{% static 'app1/images/page1_img1.jpg' %}" alt=""> I've run python manage.py collectstatic, set Debug = False (everything works fine when Debug is true). I can confirm that all images are located in /home/xxx/App/django_app/static_root/app1/images, while all css files are under /home/xxx/App/django_app/static_root/app1/css. I'm able to access the css file with the url https://myserver/static/app1/css/style.css, also there is no error message in Nginx log. I've tried different browsers, cleared cache, restarted the server and Nginx several times with no luck, really running out of idea... Any suggestion would be appreciated. -
Django - ForeignKey Add Users Value As Default
I'd like to implement a grading model into my Django WebApp. This Grade Model has 3 ForeignKeys being a student, a subject and the schoolclass of the student. Is there a way to default the value of that field to student.klasse (which is already a field in the student model). models.py class Person(AbstractUser): # called the model Person since they can be teacher or student klasse = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, blank=True, null=True) class Test(models.Model): student = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, default=student.klasse_id, blank=True, null=True) It throws this Error when trying to make the migration: school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, default=student.klasse_id, blank=True, null=True) AttributeError: 'ForeignKey' object has no attribute 'klasse_id' -
TypeError: translation() got an unexpected keyword argument 'codeset'
I'm following a Python tutorial on youtube and need to create a django website, however I am unable to start, because when I enter "python manage.py runserver" I get the "TypeError: translation() got an unexpected keyword argument 'codeset'" message. I've run back the video like 20 times to see if I've missed anything, but no, because it's just the beginning of the django website tutorial. I've also tried typing python3 instead of python and some other options I saw on Stack Overflow, but none are really exactly relevant to the error message I'm getting. Perhaps someone knows how to fix this? I tried to start a development server by typing in "python manage.py runserver" which was supposed to start a django webserver at 127.0.0.1:8000 or something, but instead I got the error message specified in the title code: PS C:\Users\kaspa\PycharmProjects\PyShop> python manage.py runserver Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x00000145784C1F80> Traceback (most recent call last): File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, … -
How to 'add' QuerySet in Django?
I have written the below code. for number in numbers: booking_list = Booking.objects.filter(rooms=number) Here, numbers is a list of numbers. The problem with this code is that booking_list will only contain the QuerySet of the last number as the previous QuerySets will be overwritten but I want booking_list to contain all the QuerySets. Moreover, I want the QuerySets to be unique. In other words I want a union of the QuerySets. The reason as to why the QuerySet may have repeated vaues is because rooms is a list of numbers. Edit: The actual problem is complex. models.py class Booking(models. Model): customer_name = models.CharField(max_length=30) check_in_date = models.DateField() check_in_time = models.TimeField() check_out_time = models.TimeField() room_numbers = models.CharField(validators=[validate_comma_separated_integer_list], max_length=4000) ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ('King', 'King'), ('Queen', 'Queen'), ) category = models.CharField(max_length=9, choices=ROOM_CATEGORIES) PERSON = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) person = models.PositiveSmallIntegerField(choices=PERSON, default=1) no_of_rooms = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], default=1 ) room_numbers can have values like [4, 21, 62, 50, 2, 12]. views.py for room_number in room_numbers: regex = rf"\b{room_number}\b" keys = ['room_numbers__iregex', 'customer_name', 'check_in_date', 'check_in_time', 'check_out_time', 'category__in', 'person__in', 'no_of_rooms'] values = [regex, customer_name, check_in_date, check_in_time, check_out_time, category, person, no_of_rooms] parameters = {} for … -
How to create a user specific home page
I'm busy learning Django. My current home page displays the posts, or posted passwords, for all users that have an account. I want the login page to display data unique to the logged in user. I've looked all over for a solution to this ... It seems straightforward, but I can't figure it out. I already have a detailed view for all posts created by a single user, but I don't know how to adapt that to serve as the actual home page once a user has logged in. Here's some of the code I've experimented with so far. I guess I'm trying to merge the functionality of UserPasswordListView class with the index view ... but I'm just not sure how to do so. views.py def index(request): context = { 'sites': SitePassword.objects.all() } return render(request, 'core/index.html', context) class PasswordListView(ListView): model = SitePassword template_name = 'core/index.html' context_object_name = 'sites' class UserPasswordListView(ListView): model = SitePassword template_name = 'core/user_sitepassword.html' context_object_name = 'sites' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return SitePassword.objects.filter(user=user) class PasswordDetailView(DetailView): model = SitePassword models.py class SitePassword(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) password = models.CharField(max_length=200) email = models.CharField(max_length=200) logo = models.CharField(max_length=300) def __str__(self): return self.name def get_absolute_url(self): return reverse('sitepassword-detail', kwargs={'pk': …