Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to inherit a model from 2 classes that are being inherited from same parent class django?
I have the following models: class Grade(models.Model): grade = models.CharField(max_length=255, unique=True) class Student(models.Model): class Meta: unique_together = ("rollno", "grade") name = models.CharField(max_length=255) grade = models.ForeignKey(Grade,related_name='StudentList', on_delete=models.CASCADE) rollno = models.BigIntegerField(unique = True) class GradeTotal(models.Model): grade = models.ForeignKey(Grade, related_name='GradeMarks', on_delete=models.CASCADE) average = models.IntegerField() total = models.IntegerField() class StudentTotal(models.Model): rollno = models.ForeignKey(Student, related_name='StudentMarks', on_delete=models.CASCADE) gradeno = models.ForeignKey(GradeTotal, related_name='Fromgrade', on_delete=models.CASCADE) marks = models.IntegerField() I am using the model Grade to create GradeTotal and then StudentTotal. The object StudentTotal is only created when the foreignkey grade of GradeTotal and Student is same to the instant of Grade being used for the process. To do this I have the following serializer: class StudentDataSerializer(serializers.ModelSerializer): rollno = serializers.CharField() class Meta: model =StudentTotal fields = ('marks', 'rollno' ) class GradeSerializer(serializers.ModelSerializer): Fromgrade = StudentDataSerializer(many=True) class Meta: model = GradeTotal fields = ('average', 'total', 'Fromgrade', ) class MultipleGradeSerializer(serializers.ModelSerializer): GradeMarks = GradeSerializer(many=True) grade = serializers.CharField() class Meta: model = Grade fields = ("grade", "GradeMarks") def update(self, instance, validated_data): g_data = validated_data.pop('GradeMarks') for datas in g_data: a1 = datas["average"] t1 = datas["total"] g1 = GradeTotal.objects.create(grade=instance, average=a1, total=t1) data2 = datas.pop('Fromgrade') for data in data2: e1 = data["rollno"] r1 = Student.objects.get(rollno=data["rollno"]) if s1["grade"] == instance: StudentTotal.create(gradeno = g1, rollno = r1, marks =data["marks"]) return … -
How to wait for a callback response(webhook) in a django viewset
I have a django Modelviewset which will trigger a particular workflow to hit external APIs. After this workflow is finished there'll be a callback response. I have created a seperate webhook in django to capture the callback response. Question is how to wait in the view for this callback response ? How can this view know that callback has been recieved. I am saving to a model in the webhook. Can this be achieved using signals. If so how ? -
Django migartion fail, (2013, 'Lost connection to MySQL server at \'reading initial communication packet\')
The company work had bought domain name under NameCheap (no Root access) All I now need is setup the database and webpage will be working My company system use: Apache Version: 2.4.38 MySQL Version: 10.1.38-MariaDB-cll-lve Architecture: x86_64 Operating System: Linux Python: 3.7 Django: 2.1.7 but when I run python manage.py migrate I had this error: Traceback (most recent call last): File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/MySQLdb/connections.py", line 164, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server at \'reading initial communication packet\', system error: 2 "No such file or directory"') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/letsilap/virtualenv/IOT/3.7/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File … -
How to start Load Data when Django application run though gunicorn server?
For production setup, 1) I am facing this challenge like Django app is not initialize(not preload the data in memory) when gunicorn server start. When the first request comes then all these data load in memory. It is taking some time to load meanwhile got an error request timeout. 2) When every request comes, a new worker starts it loads the dataset into memory and server hang up. I tried to change worker_class from 'async' to 'gthread' but still facing the same problem. add pre_load = True //no improvement File name gunicorn_config.py workers = 2 worker_class = 'gthread' worker_connections = 1000 timeout = 30000 keepalive = 2 preload_app = True spew = False daemon = False raw_env = [ 'DJANGO_SECRET_KEY=something', 'SPAM=eggs', ] pidfile = None umask = 0 user = None group = None tmp_upload_dir = None errorlog = '-' loglevel = 'info' accesslog = '-' access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' proc_name = None def post_fork(server, worker): server.log.info("Worker spawned (pid: %s)", worker.pid) from gunicorn.workers.sync import SyncWorker class SyncWorkerPreload(SyncWorker): def run(self): pass def init_process(self): super(SyncWorkerPreload, self).init_process() import django django.setup() server.log.info('%s: App loaded' % self.pid) super(SyncWorkerPreload, self).run() worker.__class__ = SyncWorkerPreload def pre_fork(server, worker): pass def pre_exec(server): … -
Creating a multiple filter query from a list
Let's say in some database i have People who has this attributes: Name Age If i wanted to get all the people that are called Stuart or Steve i could use Q objects: qs = People.objects.filter(Q(name='Stuart') | Q(name='Steve')) But, what if i'm receiving a list of n names? Example: ['Bob, 'John','Rachel', 'Some other names that i don't know'...] How could i build a query with those n unknown names on the list? -
Spyne application with URL
I want to create application which has live URL of OTA , but it return errors. app = Application([ProtelService], 'http://www.opentravel.org/OTA/2003/05', in_protocol=Soap12(), out_protocol=Soap12(), ) I am sending this data in request. <?xml version='1.0' encoding='UTF-8'?> <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns="http://www.opentravel.org/OTA/2003/05" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:htng="http://htng.org/PWSWG/2007/02/AsyncHeaders"> <soapenv:Header xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"> <htnga:CorrelationID xmlns:htnga="http://htng.org/PWSWG/2007/02/AsyncHeaders">ce5ad730-96c7-4b5b-8e39-63048f2db569</htnga:CorrelationID> </soapenv:Header> <env:Body> <OTA_HotelResNotifRQ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" EchoToken="ce5ad730-96c7-4b5b-8e39-63048f2db569" TimeStamp="2019-03-28T09:49:46Z" Version="4" CorrelationID="ce5ad730-96c7-4b5b-8e39-63048f2db569" ResStatus="Commit" PrimaryLangID="de-DE" xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05 OTA_HotelResNotifRQ.xsd"> </OTA_HotelResNotifRQ> </env:Body> </env:Envelope> It gives me this error. <?xml version='1.0' encoding='UTF-8'?> <soap12env:Envelope xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope"> <soap12env:Body> <soap12env:Fault> <soap12env:Reason> <soap12env:Text xml:lang="en">Requested resource '{http://www.opentravel.org/OTA/2003/05}OTA_HotelResNotifRQ' not found</soap12env:Text> </soap12env:Reason> <soap12env:Role></soap12env:Role> <soap12env:Code> <soap12env:Value>soap12env:Sender</soap12env:Value> <soap12env:Subcode> <soap12env:Value>ResourceNotFound</soap12env:Value> </soap12env:Subcode> </soap12env:Code> </soap12env:Fault> </soap12env:Body> </soap12env:Envelope> -
Django count nested m2m objects
I have 3 models - class A(models.Model): ... b = models.ManyToManyField(B, related_name="related_a") class B(models.Model): ... class Entries(models.Model): ... b = models.ForeignKey(B, related_name="entries") I need to loop over all A objects and show the count of entries for each b in A. What would be the most efficient way to do it? -
How to do efficient reverse foreign key check on Django multi-table inheritance model?
I've got file objects of different types, which inherit from a BaseFile, and add custom attributes, methods and maybe fields. The BaseFile also stores the File Type ID, so that the corresponding subclass model can be retrieved from any BaseFile object: class BaseFile(models.Model): name = models.CharField(max_length=80, db_index=True) size= models.PositiveIntegerField() time_created = models.DateTimeField(default=datetime.now) file_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) class FileType1(BaseFile): storage_path = '/path/for/filetype1/' def custom_method(self): <some custom behaviour> class FileType2(BaseFile): storage_path = '/path/for/filetype2/' extra_field = models.CharField(max_length=12) I also have different types of events which are associated with files: class FileEvent(models.Model): file = models.ForeignKey(BaseFile, on_delete=models.PROTECT) time = models.DateTimeField(default=datetime.now) I want to be able to efficiently get all files of a particular type which have not been involved in a particular event, such as: unprocessed_files_type1 = FileType2.objects.filter(fileevent__isnull=True) However, looking at the SQL executed for this query: SELECT "app_basefile"."id", "app_basefile"."name", "app_basefile"."size", "app_basefile"."time_created", "app_basefile"."file_type_id", "app_filetype1"."basefile_ptr_id" FROM "app_filetype1" INNER JOIN "app_basefile" ON("app_filetype1"."basefile_ptr_id" = "app_basefile"."id") LEFT OUTER JOIN "app_fileevent" ON ("app_basefile"."id" = "app_fileevent"."file_id") WHERE "app_fileevent"."id" IS NULL It looks like this might not be very efficient because it joins on BaseFile.id instead of FileType1.basefile_ptr_id, so it will check ALL BaseFile ids to see whether they are present in FileEvent.file_id, when I only need to check the BaseFile ids … -
How to run django and angular into a single development server?
I have a project where I am using Angular js to consume the API that I built with Django-Framework. Currently I have to start up the django api using django development server e.g., python manage.py runserver 192.168.0.185:8080' and then I have to start up the angular (this is my webclient) js server using 'python manage.py runserver 192.168.0.185:8000 ' Is there any way I can setup my django project to to run and web client so that i will no longer be seperating the development server of api and web client . That when i run api server it will also include the web client. Any idea? . Thank you. -
ajax function not found
Getting error TypeError: $.ajax is not a function , i was creating ajax powered like button following this youtube video https://www.youtube.com/watch?v=pkPRtQf6oQ8&t=387s site is django based my script is <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "Unlike") } else { updateText(this_, removeLike, "Like") // remove one like } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) -
How to create a required Boolean field in recent Django REST Framework?
I'm not using Django forms, so this & this are not duplicates. I've tried this workaround, but del kwargs['required'] fails with "KeyError: 'required'". This other workaround doesn't seem to do anything, possibly because the field is defined on the model as well. Ditto for this workaround. -
Interactive web application with Django/Flask issue
I want to build a website that shows some data from a CSV file and collects some user data (which should be provided through some textbox widgets) and saves it in a CSV file(the same file). I already have a working Python code for the CSV handling. The problem is that I'm not sure what programming languages I need to use besides Python in order to achieve that using Flask or Django. And I'm not familiar with web development. Can I make it using only Python and Django/Flask(or any other web framework)? If not, what languages and resources do I need? And do I need a database for that? I tried some tutorials for both frameworks but Flask seems to need HTML and CSS, and Django wasn't much clear to me. Thank you. -
How to page result and filter it by ForeignKey field in Graphql?
I am writing a graphql api in Django. I want to do the search like the example below. I am new to use graphql and I only know how to return all the object. So, I would like to know 1) how to split the result into different page which each page contain 10 result. 2) How can I filter the result by the ForeignKey field? Like, I want to filter the Expense.objects by the ExpenseDetail.date and also output it. I have tried to use expense_set to do the search but graphql report error. How can I solve the above two problems. Many Thanks. Models.py (simplified a lot): class Expense(BaseModel): id = models.AutoField() price = models.FloatField() class ExpenseDetail(BaseModel): id = models.CharField() date = models.DateField() expense = models.ForeignKey(Expense, on_delete=models.CASCADE, default=None, null=True, blank=True) Schema.py: class ExpenseType(DjangoObjectType): class Meta: model = Expense class Query(graphene.ObjectType): list_expense = graphene.List(ExpenseType, search=graphene.String()) def resolve_list_expense(self, info, search=None, **Kwargs): return Expense.objects.all() Graphql: query{ listExpense(ExpenseId:"", page:1, pageSize:10) { page pageSize totalSize expense_set{ date } } } -
Authenticating Android with firebase Authentication and send token to verify to backend Django
the issue that I will address here is a pretty common, my concern is on one part of it that I will highlight: My Android App authenticates users using firebase Authentication (either create or verify that exists), then calls various APIs on my django backend. To call APIs I need to send a token in each request so that I prevent unauthorized requests. I was planning first of using Django Authentication but since I am using firebase Auth, I'm thinking of the following approach: When a user sign-in or log-in to Android device. the Android will generate a custom token (from firebase), store it on the phone and then send it in each API to the backend. In backend, I will use firebase API to get the user from firebase (the first time) and store the token in my users model. If the token is not found in my database and not available in firebase then I return a non-authorized user. For subsequent requests I validate the token with my local users table. Please advise if this approach is the best in this case. Thank you -
form's is_valid method skipped self.full_clean method while debugging
Question: I debug the form.is_valid step. I can clearly see it called self.errors but it skipped the self.full_clean() ; What I tried: I think it is because self._errors is not None but a empty dict. but have no idea where and when self._errors was set(I followed the form instantiate step but it's too complex so nothing found) Anyone knows about this? -
Error 'utf-8' codec can't decode byte 0x96 in position 268: invalid start byte when read file csv
I have error when read file csv my code class ImportExcel(APIView): permission_classes = [] def post(self, request): final = [] import openpyxl file = request.FILES['file'] print(file) data = file.read().decode("utf-8") line = data.split('\n') for item in line: field = line.split(',') data_dict = {} data_dict['name'] = field[0] data_dict['number'] = field[1] final.append(data_dict) return Response(final) and my error 'utf-8' codec can't decode byte 0x96 in position 268: invalid start byte Please to help me fix this thank all -
Overwriting Image with same name - Django
Through my project, I have users upload a profile picture. I save the profile picture as userID.jpg. If they upload a new profile picture, I want to overwrite the old profile picture, so I don't waste storage space. By browsing previously asked questions on stackoverflow, I redefined the OverwriteStorage: class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): if self.exists(name): os.remove(os.path.join(settings.MEDIA_ROOT, name)) return name When I upload the profile picture, I can see in the directory on my computer that the picture has been overwritten successfully.The image is saved with the path "media/profile/userID.jpg". However, when I display the image on my site, it is still the old picture. Through the Django site, when I open the path, I see the old picture, and when I try to change it through the admin, I get the following error: [WinError 32] The process cannot access the file because it is being used by another process: '\media\\profile\\userID.jpg' I guess I am incorrectly overwriting the file and another instance is still open, and to solve it, I need to properly close the image before overwriting. I tried doing that, but to to no success. -
Variable from javascript wont get passed on to the form
The variable ocode does not get passed to the def resetusername. document.getElementById("ocode").value gets the value from storageName and I verified it by using 'alert' function. Can anyone please tell me what I am doing wrong.Thank you function mySubmit() { document.getElementById("ocode").value = localStorage.getItem("storageName"); alert(document.getElementById("ocode").value); document.getElementById("myform").action = "/postresetusername/"; } <form method="post" id="myform" onsubmit="mySubmit()"> {% csrf_token %} <div class = "login-box"> <h1>Reset Username</h1> <div class = "textbox" style="float:left"> <input type = "email" placeholder="Previous Email" name = "email" id="email"> </div> <input type='hidden' id= "ocode" name='id' value=""> def postresetusername(request): email = request.POST.get('email') authe.verify_password_reset_code(ocode, "new_pwd") return render(request, "signIn2.html", {"messg": "Password reset"}) return render(request, "signIn2.html", {"messg": "Cant reset"}) -
HTTPS is crossed out with Django static files served from S3 bucket
I'm having an issue with Django static files. I'm using Django admin and Django Rest Framework. I'm trying to serve the static files for admin and DRF with an S3 bucket. I can successfully visit the URL of any file in the bucket and it will load in my browser, and the file is served over HTTPS. I created a nested stack in CloudFormation for the S3 bucket: Description: > This template deploys S3 buckets for serving Django static files. Parameters: AppUrl: Type: "String" Description: "The URL for our app (e.g. mydomain.com)" AllowedPattern: "[a-z0-9._-]+" Resources: AssetsBucket: Type: "AWS::S3::Bucket" Properties: BucketName: !Sub ${AppUrl}-assets AssetsBucketPolicy: Type: "AWS::S3::BucketPolicy" Properties: Bucket: !Ref AssetsBucket PolicyDocument: Version: "2012-10-17" Statement: - Sid: PublicReadForGetBucketObjects Effect: "Allow" Principal: "*" Action: "s3:GetObject" Resource: !Sub "${AssetsBucket.Arn}/static/*" When my application starts, it runs collectstatic and the static files are moved into the bucket. Here's the issue I'm having: When I visit a DRF URL with the query parameter ?format=json. This returns a JSON response, with no static files from the browsable API, and I don't see any errors. However, when I visit the browsable API or the admin interface, I seem to find one of three error messages. In Chrome, I'm either … -
Django WSGIScriptAlias does not work properly
Im running my Django app with apache and mod_wsgi. I wanted to run my app from a subdirectory - lets say example.com/test. I've configured my django.conf as shown below, but it does not work properly. It does run Django, but instead of showing me a "home" is shows django's 404. When I have WSGIScriptAlias pointng to / it works fin on exmaple.com, but with /test example.com shows apache page. Alias /static /home/trailslash/test/static <Directory /home/trailslash/test/static> Require all granted </Directory> <Directory /home/trailslash/test/testproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias /test /home/trailslash/test/testproject/wsgi.py process-group=testproject WSGIDaemonProcess testproject python-path=/home/trailslash/test:/home/trailslash/test/testenv/lib/python3.6/site-packages WSGIProcessGroup testproject bottom line... with this config: example.com points to apache home page and example.com/test runs Django but Django expects /test as part of its app not as its root. Thanks for your help. -
Static files not loading [DJANGO]
My images aren't loading while using static files from Django and I can fix the problem. Basically I can load neither my favicon <link rel="shortcut icon" type="image/png" href="{% static "images/FAVICON.png" %}"/> and my other image <link rel="shortcut icon" type="image/png" href="{% static "images/FAVICON.png" %}"/>. I think that would be enough for you to help me solve this problem! If you need anything else just ask! HTML <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Antonio Gonçalves</title> <link rel="shortcut icon" type="image/png" href="{% static "images/FAVICON.png" %}"/> </head> <body> <div id="MENU"> <div id="FOTO"> <span class="ORANGE"></span> <span class="WHITE"></span> <span class="ME_CIRCLE"><img src="{% static "images/ME2.png" %}" type="images/png" alt="ME NOT LOADING"></span> </div> </div> </body> </html> SETTINGS FILE """ Django settings for PORTFOLIO project. Generated by 'Django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR,'Templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC = os.path.join(BASE_DIR, 'static/') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'w6gvds6*%jdyt1a(#go7i7=f#)(as#-q(1eso5@%0nx!5-agdc' # SECURITY WARNING: … -
In Django how to mock an object method called by views.py during its import?
I am writing System Tests for my Django app, where I test the complete application via http requests and mock its external dependencies' APIs. In views.py I have something like: from external_service import ExternalService externalService = ExternalService data = externalService.get_data() @crsf_exempt def endpoint(request): do_something() What I want is to mock (or stub) ExternalService to return a predefined response when its method get_data() is called. The problem is that when I run python manage.py test, views.py is loaded before my test class. So when I patch the object with a mocked one, the function get_data() was already called. This solution didn't work either. -
How to fix django-oscar shipping UnboundLocalError?
I want to add a shipping methods to django-oscar, but I'm getting the UnboundLocalError error even though I've done everything on the document page. Request Method: GET Request URL: http://127.0.0.1:8000/checkout/shipping-address/ Django Version: 2.1.7 Exception Type: UnboundLocalError Exception Value: local variable 'methods' referenced before assignment repository.py from oscar.apps.shipping import repository from . import methods class Repository(repository.Repository): def get_available_shipping_methods(self, basket, user=None, shipping_addr=None, request=None, **kwargs): methods = (methods.Standard(),) if shipping_addr and shipping_addr.country.code == 'GB': # Express is only available in the UK methods = (methods.Standard(), methods.Express()) return methods methods.py from oscar.apps.shipping import methods from oscar.core import prices from decimal import Decimal as D class Standard(methods.Base): code = 'standard' name = 'Shipping (Standard)' def calculate(self, basket): return prices.Price( currency=basket.currency, excl_tax=D('5.00'), incl_tax=D('5.00')) class Express(methods.Base): code = 'express' name = 'Shipping (Express)' def calculate(self, basket): return prices.Price( currency=basket.currency, excl_tax=D('4.00'), incl_tax=D('4.00')) -
Django display certain message after redirect
Django display certain message I have two success messages displaying:one from 'profile.html' the other from include 'sidebar.html' after redirect i want to display the update profile notification only profile.html <div class="row justify-content-center"> <div class="col-md-6"> {% if messages %} <div class="alert alert-success p-3" role="success"> <ul class="messages" style="list-style: none; margin-bottom: 0;"> {% for message in messages %} <li{% if 'info' in message.tags %} class="info-message" {% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} </div> <div class="col-md-4"></div> </div> {%include 'base/sidebar1.html' with post=category_count all_cat=all_cat%} sidebar.html {% if messages %} <div class="alert alert-success" role="success" style=" padding-top: 16px; padding-bottom: 0px; margin-bottom: 10px;"> <ul class="messages" style="list-style: none;"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} views.py sidebar email subscription view def email_list_signup(request): form = EmailSignupForm(request.POST or None) if request.method == "POST": if form.is_valid(): email_signup_qs = Signup.objects.filter(email=form.instance.email) if email_signup_qs.exists(): messages.info(request, "You are already subscribed") else: messages.info(request, "Subscriber added successfully") subscribe(form.instance.email) form.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))''' -
Using django-taggit in a search filter
I am trying to make it so when I search a post it filters based on the tags in a model. I am using Django-Taggit by the way. For example if I search for 'apple'. I want all of the posts that have the tag apple to appear when I search. A few of the ways I have tried so far are... Post.objects.filter(tags__name__in=[""]) and Post.objects.filter(tags__post__icontains=tagquery) Neither of these returned anything so any help would be appreciated. Model: class Post(models.Model): title = models.CharField(max_length=200) live = models.BooleanField(default=False) tags = TaggableManager() slug = models.SlugField(unique=True, blank=True, null=True, default='', max_length=256) Views: class SearchListView(ListView): model = Post template_name = "public/search.html" def get_queryset(self): queryset = super().get_queryset().filter(live=True) # query = self.request.GET.get("q") # if query: # queryset = queryset.filter(title__icontains=query) tagquery = self.request.GET.get("tag") if tagquery: queryset = queryset.filter(tags__post__icontains=tagquery) return queryset