Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to implement ci/cd for a django project on awslightsail from bitbucket
I'm following the instructions given on Using AWS CodeDeploy and AWS CodePipeline to Deploy Applications to Amazon Lightsail to implement ci/cd for my Django project. my project is currently published on AWS lightsail. on the last step (on Fork the GitHub Repo section), this tutorial uses GitHub, instead of GitHub, I want to use bitbucket, where my project is stored now. All I could find on bitbucket docs was Python with Bitbucket Pipelines. But, I'm stuck and I don't know where to use the bitbucket-pipelines.yml file, and how to connect these two tutorials. any clue is really appreciated. -
Anybody see the problem? #Bootoast script
Trying to get Bootoast to work on my website, where I try to pass a message. You can see the code below. Using Django-bootstrap for front-end. BASE.HTML <script srs="https://unpkg.com/bootoast@1.0.1/dist/bootoast.min.js"></script> <link rel="stylesheet" href="https://unpkg.com/bootoast@1.0.1/dist/bootoast.min.css"> <script> function toast(message, type) { bootoast.toast({ position: 'bottom-center', message, type, }); } {% if messages %} {% for message in messages %} toast('{{ message }}', '{{ message.tags }}') {% endfor %} {% endif %} </script> VIEWS.PY @login_required(login_url="/sign-in/?next=/customer/") def profile_page(request): user_form = forms.BasicUserForm(instance=request.user) customer_form = forms.BasicCustomerForm(instance=request.user.customer) if request.method == "POST": user_form = forms.BasicUserForm(request.POST, instance=request.user) customer_form = forms.BasicCustomerForm(request.POST, request.FILES, instance=request.user.customer) if user_form.is_valid() and customer_form.is_valid(): user_form.save() customer_form.save() messages.success(request, 'Your profile has been updated') return redirect(reverse('customer:profile')) return render(request, 'customer/profile.html', { "user_form": user_form, "customer_form": customer_form }) So the message I want to get passed is in views.py. -
Unable to deploy my django based API on Heroku
I tried to deploy my django based api to heroku, however I have been getting the same error for the past few lifetimes Error logs: *2021-01-31T11:42:30.163925+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=hospagoapi.herokuapp.com request_id=ba1f93a1-50ec-492e-b637-a3df4a1ab8d0 fwd="42.110.150.136" dyno= connect= service= status=503 bytes= protocol=https 2021-01-31T11:42:35.081501+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=hospagoapi.herokuapp.com request_id=abbd9954-86b9-41a6-b895-a9261ac12082 fwd="42.110.150.136" dyno= connect= service= status=503 bytes= protocol=https 2021-01-31T11:42:39.924144+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/api/v1/users" host=hospagoapi.herokuapp.com request_id=32eddcbd-7b44-49ef-9d1f-244f29681f05 fwd="42.110.150.136" dyno= connect= service= status=503 bytes= protocol=https 2021-01-31T11:42:41.717524+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=hospagoapi.herokuapp.com request_id=79c677cd-4a6c-4c7e-9ea5-db60a2732f2f fwd="42.110.150.136" dyno= connect= service= status=503 bytes= protocol=https* Hospagoapi is my app name My production git repo: https://github.com/RachitKumar205/hospago I apologize for any errors in my question in advance, this is my first time posting -
It is possible to run celery on gpu?
The question is - It is possible to run celery on gpu? Currently in my project I have settings like below: celery -A projectname worker -l error --concurrency=8 --autoscale=16,8 --max-tasks-per-child=1 --prefetch-multiplier=1 --without-gossip --without-mingle --without-heartbeat This is django project. One single task take around 12 s to execute (large insert to postgresql). What I want to achive is multiply workers as many as possible. -
how to add search bar in django leaflet
I'm trying to use a map on my website and for that, I'm using the Django leaflet library and I need to add a search bar to my map but I don't know how to do it help me pls my map -
plotly dash: click to enlarge table
I am fairly new to plotly dash and I am working with a data table. I would like to learn how it is possible to display like the first n rows on screen and have a "click to enlarg" button on the last row of the table that would enlarg the table to full screen and show all rows. I have not found a way to do this with plotly and dash yet, so I am wondering if this is possible and if yes, how? An link to resource, tuto, is welcomed! -
twitter:image meta tag problem in Django Blog
Twitter needs the hardcoded path in his metatags in order to render the image in the social media. I use the hardcoded path in my article_details.html, which is the main html for articles, but I need to switch to a new image path every time I publish new articles. I'm not using a single page for every article. Does any1 know a way to have a dynamic path for this metatag? -
Django TemplateDoesNotExist error in production but not in development
I am trying to release my website to a staging environment but I keep get TemplateDoesNotExist error. My website consists of multiple apps that will extend a base app for common elements. When I view the website in a development environment it works as expected, however when I try to view it in my staging environment it errors out. All of the templates in the apps, other than the base templates, contains {% extends "main/index.html "%} at the top of them. file structure: ├── manage.py ├── assets ├── base │ ├── templates │ │ ├── main │ │ │ ├── index.html │ ├── urls.py │ ├── views.py │ ├── ... ├── dashboard ├── inventory │ ├── templates │ │ ├── main │ │ │ ├── inventory.html │ ├── urls.py │ ├── views.py │ ├── ... ├── magic │ ├── templates │ │ ├── main │ │ │ ├── sets.html │ │ │ ├── cards.html │ ├── urls.py │ ├── views.py │ ├── ... ├── website │ ├── settings │ │ ├── base.py │ │ ├── staging.py │ │ └── production.py │ ├── asgi.py │ ├── urls.py │ └── wsgi.py settings/base.py: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent SECRET_KEY … -
Not able to install argon2 in windows 10
Argon2 lib is not getting installed in windows 10.Getting the following error. pip3 install argon2 Running setup.py install for argon2 ... error ERROR: Command errored out with exit status 1: package init file 'phc-winner-argon2_init_.py' not found (or not a regular file). I have installed Miscrosoft Visual Studio Build tools as well.And using Python 3.9.1 -
django query: grouped min and max that max is twice and newer of min
I need queryset that result contains rows from following model BuyerPower, that for each symbol contains maximum ibp and minimum ibp and ct columns of these two records, where maximum_ibp is more than twice minimum_ibp and newer. result table would look like this: | symbol(unique) | max_ibp | min_ibp | max_ibp_ct | min_ibp_ct | models: class BuyerPower(models.Model): symbol = models.ForeignKey('Symbol', null=True, on_delete=models.PROTECT) ct = models.DateTimeField(auto_now_add=True) ibp = models.FloatField() I've tried using values() and annotate() but I can not find how to filter and join max's that are newer of min min_ibps = IndividualBuyerPower.objects.filter().values('symbol', 'ct').annotate(min_ibp=Min('ibp')) max_ibps = IndividualBuyerPower.objects.filter().values('symbol', 'ct').annotate(max_ibp=Max('ibp')) -
Django forcing async database operation
raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. is thrown with following code if object_query.exists(): object_query is object_query = Example.objects.filter( name='test', ) -
Running celerybeat in production (Ubuntu)
I need to run celerybeat in production. Currently while development, I use to run while being in the directory i.e /Users/driftking9987/Documents/Django_Projects/inlog_p_v2 celery -A inlog_p_v2 worker -l info -B I have gone through the https://docs.celeryproject.org/en/stable/userguide/daemonizing.html link where it says how to run the celery beat as daemon onto the server. In the location, /etc/init.d , I have copied the sample init script from GitHub for celerybeat. As written in the documentation, I created a configuration file at location /etc/default whose contents are as follows: # Absolute or relative path to the 'celery' command: CELERY_BIN="/opt/anaconda/envs/django_env/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="inlog_p_v2" # or fully qualified: #CELERY_APP="proj.tasks:app" # Where to chdir at start. CELERYBEAT_CHDIR="/opt/inlog_p_v2" # Extra arguments to celerybeat # CELERYBEAT_OPTS="--schedule=/var/run/celery/celerybeat-schedule" #export DJANGO_SETTINGS_MODULE="inlog_p_v2.settings" CELERYD_CHDIR="/opt/inlog_p_v2" Below is the error which I get when I try to run (base) root@ip-172-31-2-63:/etc/default# /etc/init.d/celerybeat start celery init v10.1. Using configuration: , /etc/default/celerybeat Starting celerybeat... Usage: celery [OPTIONS] COMMAND [ARGS]... Error: Invalid value for '-A' / '--app': Unable to load celery application. The module inlog_p_v2 was not found. I have been trying all the things which are written in so many threads over here, but nothing seems to … -
How to send value in session with forms in django
I have a favourite block, which is created using Session, I retrieved data from Session and displayed it in my template. In this favourite block I have a form that will send filled information to admin. I want to send with this form my received data from session, how to do that? This is my view: def favourites(request): fav = request.session.get('favourites') if not fav: return render(request, 'Main/favourites_empty.html', context={}) if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): # product = form.cleaned_data['product'] # print(product) form.save() return HttpResponseRedirect(reverse('index_urls')) else: form = RequestForm() commodities = Commodity.objects.filter(id__in=(x['id'] for x in fav )) context = { 'favourites': commodities, 'form': form } # for com in commodities: # print(com.id) # print(com.title) return render(request, 'Main/favourites.html', context) This is my template: <form method="post"> {% csrf_token %} <div class="form-item"> <!-- <input type="text" placeholder="Ваше имя"> --> {{ form.name }} </div> <div class="form-item"> <!-- <input type="text" value="{{form.phone}}" placeholder="Ваш телефон"> --> {{ form.phone }} </div> <div class="form-item"> <!-- <input type="text" value="{{form.email}}" placeholder="Ваш email"> --> {{ form.email }} </div> <div class="form-item"> <!-- <textarea placeholder="Комментарий"></textarea> --> {{ form.message }} </div> <button type="submit" class="bt">оставить заявку</button> </form> -
Can you correct the html pogo-slider code?
There seems to be some problems with the following code I downloaded from a free website template. Instead of showing my pictures, there is only white text on white background. I can only see the text if I mark it with the mouse. Is there something wrong with the code? <!-- Start Banner --> <div class="ulockd-home-slider"> <div class="container-fluid"> <div class="row"> <div class="pogoSlider" id="js-main-slider"> <div class="pogoSlider-slide" style="background-image:url(images/sladd_ur.jpg);"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="slide_text white_fonts"> <h3>Progress & Success<br><strong>Currency</strong></h3> <br> <a class="start_exchange_bt" href="exchange.html">Start Exchange ></a> </div> </div> </div> </div> </div> <div class="pogoSlider-slide" style="background-image:url(images/sladd_i.jpg);"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="slide_text white_fonts"> <h3>Progress & Success<br><strong>Currency</strong></h3> <br> <a class="start_exchange_bt" href="exchange.html">Start Exchange ></a> </div> </div> </div> </div> </div> </div> <!-- .pogoSlider --> </div> </div> </div> <!-- End Banner --> -
Does Django's models.TextField() provide much security when not used with Django's form validation?
I have a Django App that accepts user input in a free text field. In the model I have the following validation rule for the field: body = models.TextField(blank=True, null=True) If I decide not to validate input in the front end and I don't use Django forms, am I leaving a big gaping security hole, or does models.TextField() provide quite a lot of protection? For context, I'm sending data via AJAX and in this case I think it would be easier to not use a Django Form, that's very possibly because I don't know Django well enough, but I think the question still stands. -
How do i write a function to list replies and a option to create replies in comments details page Django RestFramework
I want to add a function to to show all the replies of a Parent Comment and option to add new replies to parent comments in Django RestFramework. How do i approach? Here's my code: Models.py class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='Comments') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='Replies') conversation = models.TextField() created_on = models.DateTimeField(default=timezone.now) approved_comments = models.BooleanField(default=False) def __str__(self): return self.article.title[:50] + ' | ' + 'Comments by {}' .format(self.user.username) def approved_comments(self): self.approved_comments = True self.save() def children(self): # Return replies of a comment. return Comment.objects.filter(parent=self) @property def is_parent(self): # Return `True` if instance is a parent if self.parent is not None: return False return True Serializers.py class CommentDetailSerializer(ModelSerializer): url_to_commentUpdate = comment_update_url url_to_commentDelete = comment_delete_url user = SerializerMethodField() class Meta: model = Comment fields = ['id', 'article', 'conversation', 'created_on', 'user', 'url_to_commentUpdate', 'url_to_commentDelete' ] def get_user(self, obj): return str(obj.user.username) # Need To Display replies in Comments Detail Page # Need To add function to add new replies class CommentCreateUpdateSerializer(ModelSerializer): class Meta: model = Comment fields = ['article', 'conversation'] Views.py class CommentDetailAPIView(RetrieveAPIView): queryset = Comment.objects.all() serializer_class = CommentDetailSerializer permission_classes = [AllowAny] -
Is it okay to copy a class method and test its behavior by mocking the class and dependencies in unit tests?
Or I need mock all other methods and dependencies(huge amount) in the class by using @patch, and test through a class call(call method cls.execute() in my service)? I'm new to testing. So copying the method and testing it separately, checking the desired changes in the mocked class seems like a good idea to me. But is it really so? -
How to protect Malicious attack on django website
My company's site is hosted on AWS. I have 3 months experience so I don't know what is: Not Found: //admin/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //api/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //backup/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //beta/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //blog/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //cms/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //demo/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //dev/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //laravel/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php The problem is the server automatically stopped running. I thought possible reason can be that the code is going inside some loop so I decided to check logs. What I found is: Not Found: //admin/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //api/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //backup/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //beta/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //blog/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //cms/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //demo/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //dev/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //laravel/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //lib/phpunit/Util/PHP/eval-stdin.php Not Found: //lib/phpunit/phpunit/Util/PHP/eval-stdin.php Not Found: //lib/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //lib/phpunit/src/Util/PHP/eval-stdin.php Not Found: //new/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //old/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //panel/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //phpunit/Util/PHP/eval-stdin.php I don't know what is this and how to deal with it. I already searched on google I found that it is some kind of malicious attack, I am not sure. I want to know what is this. The site is Django web framework. -
Subtract time in django Models.py
I tried subtracting two times in models.py but I got error. Here is my model That I have been working. class Schedule(BaseModel): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) travel_date_time = models.DateTimeField() and BusCompanyRoute have journey length. class BusCompanyRoute(BaseModel): journey_length = models.TimeField(null=True) Now I tried subtracting these times in using @property decorator in following way @property def journey_end_time(self): return self.travel_date_time.time()+self.bus_company_route.journey_length but end up getting following error warning as: Class 'time' does not define '__add__', so the '+' operator cannot be used on its instances How can I solve it? -
Why is the rating selected in the form not inster to the database?
So this is my code: models.py: class Company(models.Model): class Meta: verbose_name_plural = 'Companies' COMPANY_STATUS_CHOICES = ( ('Active', 'Active'), ('Dissolved', 'Dissolved'), ) COMPANY_SIZE_CHOICES = ( ('Small', 'Small'), ('Medium', 'Medium'), ('Large', 'Large'), ) company_name = models.CharField(max_length=150, null=True) company_number = models.CharField(max_length=15, null=True) company_vat_number = models.CharField(max_length=20, null=True) company_status = models.CharField(choices=COMPANY_STATUS_CHOICES, max_length=20, default='Active', null=True) company_size = models.CharField(choices=COMPANY_SIZE_CHOICES, max_length=20, default='Small', null=True) company_rating = models.ForeignKey(Company_rating, on_delete=models.SET_NULL, null=True) def __str__(self): return self.company_name views.py: def suppliers_create(request): form = SuppliersForm() if request.method == 'POST': form = SuppliersForm(request.POST) if form.is_valid(): company_name = form.cleaned_data['company_name'] company_number = form.cleaned_data['company_number'] company_vat_number = form.cleaned_data['company_vat_number'] company_status = form.cleaned_data['company_status'] company_size = form.cleaned_data['company_size'] company_rating = form.cleaned_data['company_rating'] Company.objects.create( company_name=company_name, company_number=company_number, company_vat_number=company_vat_number, company_status=company_status, company_size=company_size, company_rating=company_rating, ) return redirect('/suppliers') context = { 'form': SuppliersForm() } return render(request, 'suppliers/suppliers_create.html', context) forms.py: class SuppliersForm(forms.Form): COMPANY_STATUS_CHOICES = ( ('Active', 'Active'), ('Dissolved', 'Dissolved'), ) COMPANY_SIZE_CHOICES = ( ('Small', 'Small'), ('Medium', 'Medium'), ('Large', 'Large'), ) COMPANY_RATING_CHOICES = ( ('Perfect', 'Perfect'), ('Average', 'Average'), ('Bad', 'Bad'), ) company_name = forms.CharField() company_number = forms.CharField() company_vat_number = forms.CharField() company_status = forms.ChoiceField(choices=COMPANY_STATUS_CHOICES, label='Company Status') company_size = forms.ChoiceField(choices=COMPANY_SIZE_CHOICES, label='Company Size') company_rating = forms.ChoiceField(choices=COMPANY_RATING_CHOICES, label='Company Rating') The company_rating field on the form is displayed, but unfortunately what I selected is not inserted into the database, I don't see what I chose on admin. I … -
All my rows are still visible eventhough i am filtering
THis my first time using the django filter and i am trying to filter my all my records are still show even do my url says it is filtering the my records- any help will be appreciated This my filter File class Clientsearch(django_filters.FilterSet): class Meta: model = client fields ='__all__' exclude = ['Companyemail','Telephone','address','Postcode','RegNom','UTRno','PAYE','VAT','pensionusername','pensionpassword','companyfilling','authenticationcode','gatewayonlineuserid','gatewayonlinepassword', 'finacialdate', 'confirmationdate', 'agreedfees','updated_at','created_at','datejoined'] This my view.py def manage_client(request): clients=client.objects.all() myFilter = Clientsearch(request.GET,queryset = clients) context = {'myFilter':myFilter,'clients':clients} clients = myFilter.qs return render(request,"admintemplate/manage_client_template.html",context) This the Html Code for my Table - All the rows are still show but i can see in the url it is filtering <br> <div class="row"> <div class="col"> <div class="card card-body"> <form method ="get"> {{myFilter.form}} <button class="btn btn-primary" type ="submit">Search</button> </form> </div> </div> </div> <br> <div class="row"> <div class="col-md"> <div class="card card-body"> <table class="table table-sm"> <tr> <th>ID</th> <th>Company Name</th> <th>Company Email</th> <th>Sector</th> <th>Employee Assigned</th> <th>Edit</th> <th>Delete</th> </tr> {% for client in clients %} <tr> <td>{{client.id}}</td> <td>{{client.Companyname}}</td> <td>{{client.Companyemail}}</td> <td>{{client.sector}}</td> <td>{{client.username}}</td> <td><a href="/edit_client/{{ client.id}}" class ="btn btn-success">Edit</a></td> <td><a href="/delete_client/{{ client.id}}" class ="btn btn-success">delete</a></td> {% endfor %} </table> </div> </div> </div> -
update onetoone using django CreateView
I am using CreateView to update my Person model. That model has a onetoone relation with Adress. When trying to update my Person model I cannot update the Adress model at the same time. It just gives me a list of existing addresses, but no way to add an new address. I can see that this is possible in admin. is it possible to this in th CreateView? model.py: class Person(Model): fname=CharField(default="missing",max_length=100) lname=CharField(default="missing",max_length=100) mobil=PhoneField(default='9999999999') mail=EmailField(default='contact@gmail.com') padress=OneToOneField(Adress,on_delete=CASCADE,primary_key=True) def __str__(self): return self.fname class Meta: ordering=('fname','lname') class Adress(Model): street=CharField(default='missing',max_length=100) snumb=CharField(default='missing',max_length=15) town=CharField(default='missing',max_length=100) postn=CharField(default='99999',max_length=5,validators=[postnvali]) def __str__(self): return self.town class Meta: ordering=('street','town') view.py class PCreate(CreateView): template_name='kammem/create.html' model=Person fields=['fname','lname','mobil','mail','padress'] success_url=reverse_lazy('forl') url.py path('pcreate/',PCreate.as_view(),name='pcreate'), template: {% extends 'edit2.html' %} {% block add %} <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock %} any suggestions? -
How to allow http djnaog heroku
I tried this MIDDLEWARE = [ # SecurityMiddleware must be listed before other middleware 'django.middleware.security.SecurityMiddleware', # ... ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True but still didn't change anything I tried this package [django-sslify][1] and added its middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'sslify.middleware.SSLifyMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', but it gives me this error TypeError: SSLifyMiddleware() takes no arguments error traceback: System check identified 2 issues (0 silenced). January 31, 2021 - 09:14:56 Django version 3.1.5, using settings 'dashboard.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 138, in inner_run handler = self.get_handler(*args, **options) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 65, in get_handler return get_internal_wsgi_application() File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/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 986, in … -
Django- distinct doesn't work on order by
I have 2 models as follows: class Chat(models.Model): name = models.CharField(max_length=20) class ChatMessage(models.Model): chat = models.ForeingKey(Chat, related_name="messages") text = models.TextField() created = models.DateTimeField(auto_now_add=True) I want to get all chats order by last message created datetime. Some chats may not have messages, so I want to be at the end of the list. I tested following ways: 1- chats = Chat.objects.all().order_by(F('messages__created').desc(nulls_last=True)).distinct() 2- chats = Chat.objects.all().order_by('-messages__created').distinct() 3- chats = Chat.objects.all().annotate(last_message=Max("messages__created").order_by("-last_message") ways 1 and 2 return duplicate values. way 3 return non-duplicate date but chats with no message are on the top of the list. I want to be at the end of the list. -
Django search returns an empty value
def book(request): books = Library.objects.all() form = ChoiceFilterForm(data=request.GET or None) if form.is_valid(): filter_choice = form.cleaned_data['filter_choice'] books = books.filter(category=filter_choice) if filter_choice == 'null': books = Library.objects.all() query = request.GET.get('search') if query and query != '': result = Library.objects.filter(Q(title__icontains=query)).distinct() else: result = Library.objects.all() context = {'books': books, 'form': form, 'result': result, 'query': query} return render(request, 'book.html', context) I am new to django and I want to make a search bar. Program doesn't return an error message but the search bar shows nothing. What is my mistake here?