Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django elastic beanstalk CLI deployment failure after adding .env files to gitignore
I'm new to Django/EB/Git and been working on a django project and have successfully separated my setttings and separated .env files for both development and production which all works as expected and deployed- see the following project structure: Project Structure project root myapp settings __init__ base.py dev.py prod.py .env.dev .env.prod .gitignore manage.py requiremnts.txt However the moment I add my my .env files to the .gitignore file I now received the following error with deployment within eb logs (cfn-init-cmd.log): .gitignore # Elastic Beanstalk Files .elasticbeanstalk/* !.elasticbeanstalk/*.cfg.yml !.elasticbeanstalk/*.global.yml .env.dev .env.prod Error: eb logs (cfn-init-cmd.log) FileNotFoundError: [Errno 2] No such file or directory: '.env.prod' If i remove .env.prod from the .gitignore file then my project deploys successfully. Moreoever, I read online that might be due to me git adding and comitting the .env.prod file to the repo however believe I have also excluded git add/commit when I started fresh and re-created the git repo with the following command (commands run on local project): git add --all -- :!.env.dev :!.env.prod git commit -m "Initial commit" Followed by: eb deploy myproject-env See my .ebextensions config file as follows: .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myproject.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "myproject.settings.prod" aws:elasticbeanstalk:environment:proxy:staticfiles: "/static": "static/" packages: yum: python3-devel: [] mariadb-devel: [] … -
How to extract payload from a jwt Expired Token
I have made a view where I send a Refresh Token to email for activation account purpose. If token is valid everything works fine. The problem is when jwt token expire, I want to be able in backend to extract payload (user_id) from token when jwt.decode throw ExpiredSignatureError and in this way be able to auto resend an Email based on user_id extracted from token. Here is how i generate the token def activation_link(request, user, email): token = RefreshToken.for_user(user) curent_site = "localhost:3000" relative_link="/auth/confirm-email" link = 'http://' + curent_site + relative_link + "/" + str(token) html_message = render_to_string('users/email_templates/activate_account.html',{ 'activation_link': link, }) text_content = strip_tags(html_message) email_subject = 'Activate your account' from_email = 'notsure@yahoo.com' to_email = email @api_view(['POST']) def ConfirmEmailView(request): try: activation_token = request.data['activation_token'] payload = jwt.decode(activation_token,settings.SECRET_KEY, algorithms=['HS256']) user = User.objects.get(id = payload['user_id']) if user.is_confirmed: return Response('Already verified!', status=status.HTTP_200_OK) user.is_confirmed = True user.save() return Response(status=status.HTTP_202_ACCEPTED) except jwt.ExpiredSignatureError as identifier: // =>>> Here I want to decode activation_token and extract user_id return Response("Link- expired!", status=status.HTTP_403_FORBIDDEN) except Exception as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST) -
How can i add import export to a table and also order the columns in django
I want to add import export button and at the same time order the table columns class OrderEtudiant(admin.ModelAdmin): list_display = ('id_etudiant','nom_etudiant','prenom_etudiant','Telephone','Adresse','Filiere') search_fields = ('nom_etudiant',) class userdat(ImportExportModelAdmin): pass admin.site.register(Etudiant,userdat,OrderEtudiant) here is the problem i can't pass three parameters -
In-built template tags not recognized by django .tex template (with django-tex)
I'm using django-tex to compile pdf files from a django web app. When writing code in LaTeX there is frequent use of the sequences {{, {%, {# and some others which conflict with some of the template tags used in django to input context data or include logic into the template. There is a built-in tag called templatetag which can be used to input these characters with {% templatetag openvariable %}, {% templatetag openblock %} and {% templatetag opencomment %}, respectively. Also, code can be enclosed in {% verbatim %} {% endverbatim %} to ignore all template tags between the verbatim tag. However, when I try to use any of these tags in my template, I get the error ("Encountered unknown tag 'verbatim'.",). This error occurs for many of the in-built template tags like verbatim, templatetag, load, and most others. On the other hand, {{ context_variable }} and logical blocks like {% if %} {% endif %} do work perfectly. What could be the problem here? I have the following in settings for django-tex my settings.py file: LATEX_INTERPRETER = 'pdflatex' LATEX_GRAPHICSPATH = [str(os.path.join(BASE_DIR, '/songapp/templates/songapp/images')),] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
when i use the create function using django rest framework it dosent create a new person
when i use the create function using django rest framework it dosent create a new person instead it shows an error 405 Method Not Allowed. I even tried creating new person using frontend it just dosent work. views.py @api_view(['POST']) def create_person(request): serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) create.js: const Create = () => { let history = useHistory(); let [person, setPerson] = useState({ name:"", about:"", email:"", image:"", }) let createPerson = () => { e.preventDefault() fetch(`/api/person-create/`, { method: "POST", headers: { "content-type": 'application/json' }, body: JSON.stringify(person) }) .then(setPerson({ name:"", about:"", email:"", image:"", })) } let handleChange = (e) => { setPerson({...person, [e.target.id]: e.target.value}); console.log(person) } useEffect(() => { console.log("correct", person); }, [person]); return ( <div class="container"> <div class="row justify-content-center"> <form onSubmit={(e) => createPerson(e)}> <div> <h2> <button onClick={() => history.push('/')} className="btn btn-primary mt-4"> &#10094; Back </button> </h2> <h2 className="mt-4 mb-4" style={{width: '600px'}}> New Person </h2> <div className="form-group" style={{width: '600px'}}> <label>Name</label> <input onChange={handleChange} className="form-control" id="name" placeholder="Enter Name" value={person.name} /> </div> <div className="form-group" style={{width: '600px'}}> <label for="exampleInputEmail1">About</label> <textarea style={{height: '250px'}} onChange={handleChange} className="form-control" id="about" placeholder="Tell us somthing about yourself" value={person.about} /> </div> <div className="form-group" style={{width: '600px'}}> <label>Email</label> <input onChange={handleChange} className="form-control" id="email" placeholder="Enter Email" value={person.email} /> </div> <div className="custom-file mt-3"> <input onChange={handleChange} type="file" … -
filtering random objects in django
How can i filter 12 random objects from a model in django . I tried to do this but It does not work and It just returned me 1 object. max = product.objects.aggregate(id = Max('id')) max_p = int(max['id']) l = [] for s in range(1 , 13): l.append(random.randint(1 , max_p)) for i in l: great_proposal = product.objects.filter(id=i) -
Can not transform function in class in Django
Sorry for my poor knowledge of classes in Django, I have written my first training project via functions and now can not get it how to transform some functions in Classes. I had this function which works: @login_required def topic(request, topic_slug): """Выводит одну тему и все её записи.""" topic = get_object_or_404(Topic, slug=topic_slug) Проверка того, что тема принадлежит текущему пользователю check_topic_owner(topic.owner, request) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) Now could not transform it in to Class for the same work. I have this: class ShowTopic(DetailView): model = Topic template_name = 'learning_logs/topic.html' context_object_name = 'topic' slug_url_kwarg = 'topic_slug' def get_queryset(self): return Topic.objects.filter(topic__slug=self.kwargs['topic_slug']) For logging required I know I should add the mixin later, but right now I have error: Cannot resolve keyword 'topic' into field. Choices are: date_added, entry, id, owner, owner_id, public, slug, text And could not understand how can I insert entries here? Could somebody give me advice please? Thanks in advance. -
django boolean field validation issue
it seems that django does not handle checkbox input well. In my application, use need to choose either proceed or reject, I use a form with a checkbox to do this, which user event is handled by javascript. forms.py class ActionForm(forms.Form): action = forms.BooleanField() class Meta: fields = ['action'] template <form id="action-form" style="display: none" method="POST"> {% csrf_token %} {{ form }} <button type="submit">submit</button> </form> <div id="action-bar"> <button id="reject" class="action-button" type="button">reject</button> <button id="proceed" class="action-button" type="button">proceed</button> </div> javascript const form = document.getElementById('action-form'); const checkbox = form.querySelector('input'); const reject = document.getElementById('reject'); const proceed = document.getElementById('proceed'); reject.addEventListener('click', ()=>{ checkbox.checked = false; form.submit(); }); proceed.addEventListener('click', ()=>{ checkbox.checked = true; form.submit(); }); views.py def ActionView(request, pk): if request.method == 'POST': form = forms.ActionForm(request.POST) if form.is_valid(): print(form.cleaned_data['action']) return HttpResponse('') else: print(form.errors) return HttpResponse('') else: form = forms.ActionForm() return render(request, 'template.html', { 'form': form, }) The result I got <ul class="errorlist"><li>action<ul class="errorlist"><li>This field is required.</li></ul></li></ul> What I have tried: add required=False to the BooleanField, the result sent was always False even if I click on proceed add initial=True to the BooleanField, the result sent was always what the initial is. add both, the result sent was always False I will be so grateful for your suggestion -
POSTGRESQL NULL to zero
guys I have a big database table am using Django to plot answers, anyway 1: I can change NULL to Zeros. 2: and if the fields contain any character other than numbers remove it 3: Any recommendations on heatmap plot documentation maybe? Thanks -
Easy date time picker in django
I am fairly new to django so bare with me. I'd like to have several datepickers in some of my pages. I have followed the guide in the following link for Fengyuan Chen’s Datepicker (last one): https://simpleisbetterthancomplex.com/tutorial/2019/01/03/how-to-use-date-picker-with-django.html If I create a standalone html page with the code provided, it's all great! I don't understand how to embed the date time picker in other pages though. All of my html pages extend a base. And I put in the base head all of the contents like so: base.html <head> /* some unrelated things*/ <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <!-- Fengyuan Chen's Datepicker --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.css" integrity="sha256-b88RdwbRJEzRx95nCuuva+hO5ExvXXnpX+78h8DjyOE=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.js" integrity="sha256-/7FLTdzP6CfC1VBAj/rsp3Rinuuu9leMRGd354hvk0k=" crossorigin="anonymous"></script> </head> Then, in the page that i need to have the picker in: {% extends 'main/base.html' %} <input id="datepicker"> {% block myBlock%} <script> $(function () { $("#datepicker").datepicker(); }); </script> {% endblock %} in my views def test1(response): return render(response, "main/test1.html", {}) I find frustrating the fact that many guides are for standalone pages and not so many describe embedding. Then again it might be that I am very new to this. Thank you for the help! -
Detail viewset for product in django rest framework
I need to get just one product object in my VeiwSet based on a given slug, I looked into the docs, but I can't find any solution to this problem. I need to get the slug from the url path aswell, but I don't know how to do it too. Obviously the code below doesn't work. product/serializers.py from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): image = serializers.ImageField(required=True) class Meta: model = Product fields = ("name", "description", "slug", "id", "price", "stock", "image", "category") product/views.py from django.http.response import JsonResponse from rest_framework import serializers, viewsets from rest_framework.response import Response from django.http import JsonResponse from .serializers import ProductSerializer from .models import Product class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all().order_by('name') serializer_class = ProductSerializer class ProductDetailViewSet(viewsets.ViewSet, slug): queryset = Product.objects.filter(slug=slug) serializer_class = ProductSerializer product/urls.py from rest_framework import routers, urlpatterns from django.urls import path, include from .views import ProductViewSet, ProductDetailiewSet router = routers.DefaultRouter() router.register(r'', ProductViewSet) urlpatterns = [ path('<str:slug>/',), path('', include(router.urls)) ] -
Django money - making a MoneyField in my model
So I've been trying to import A money field from django-money using this code from djmoney.models.fields import MoneyField but every time am getting the same error Import djmoney.models.fields" could not be resolved I added djmoney to installed apps in the settings file and I used pip install django-money as well but it's still giving me the same error django-money version: 2.1 django version: 3.2.7 -
Django create an object that has a reference to another object using serializers
I want to create an order that has multiple ads and each ad must have a reference to a display object. I did this kind of thing previously just by setting the object's id in the put method and it worked well. models.py class OrdersDj(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) user_id = models.CharField(max_length=45, blank=True, null=True) class Meta: ordering = ["dateplaced"] class AdsDj(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) order = models.ForeignKey(OrdersDj,on_delete=models.CASCADE, blank=False, null=True) display = models.ForeignKey(Displays, on_delete=models.CASCADE, blank=False, null=True) null=True) serializers.py class AdsSerializer(serializers.ModelSerializer): display = DisplaySerializer() class Meta: model = Ads fields = "__all__" class OrderSerializer(serializers.ModelSerializer): ads = AdsSerializer(source="adsdj_set", many=True) def create(self, validated_data): ads_data = validated_data.pop('adsdj_set') order = Orders.objects.create(**validated_data) for ad in ads_data: Ads.objects.create(order=order, **ad) return order class Meta: model = Orders fields = "__all__" the put method data { "user_id": "1", "ads": [ { "display_id": "10", // "display" : 10, // "display" : "10", } ] } Here in dependence of what I insert for display, it expects a dictionary and not any other types. { "ads": [ { "display": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } } ] } -
creation of a new script tag in shopify
I am sending the post request to https://mystore.myshopify.com/admin/api/2021-10/script_tags.json with the respective request body. request body params below:- { "script_tag": { "event": "onload", "src": "my_link_to_script", "display_scope": "order_status" } } however i am getting the successful creation response. But the tag is not get inserted into my store checkout page. I am inserting the image below where the tag should get inserted after the successful response. enter image description here -
want to get multiple values from dropdown after adding script tag in html page it stop working or using select and script tag togetherit stop working
This is my load clients function from where I pass value to clients.html page views.py def load_clients(request): CPA_id = request.GET.get('CPA_id') clients = CPA_Client.objects.filter(CPA_id=CPA_id) return render(request, 'crm/clients_dropdown_list_options.html', {"clients": clients}) # return JsonResponse(list(cities.values('id', 'name')), safe=False client.html <select id="ddselect" name="framework[]" multiple class="form-control"> <option value="----">------</option> {% for Client_of_CPA in clients %} <option value="{{ Client_of_CPA.pk }}">{{ Client_of_CPA.name }}</option> {% endfor %} </select> In this code i am getting my output but need to select multiple values from a dropdown thats why i want to add some functionality of bootstrap jquery due to which i need script tag. After adding script tag page stop working -
How to style crispy forms with bootstrap4 in django?
I'm trying to style upload form used from crispy forms. Can you give me simple solution, and not to get too crazy about css. This is how it looks now! This is upload_document.html {% extends "base.html" %} {% load static %} {% load crispy_forms_tags %} {% block content %} <h1>Upload</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary">Upload</button> </form> {% endblock content %} models.py from django.db import models class UploadFile(models.Model): excel = models.FileField(upload_to="excel/", max_length=250) def __str__(self): return self.title forms.py from .models import UploadFile class GlForm(forms.ModelForm): class Meta: model = UploadFile fields = ('excel',) -
Reuse Django field definitions in other models
I'm having a few fields throughout different models. E.g. class A(models.Model): field_1 = models.CharField(max_length=5, blank=False) field_2 = models.CharField(max_length=100, blank=False) field_3 = models.CharField(max_length=200, blank=False) class B(models.Model): field_4 = models.CharField(max_length=5, blank=False) field_5 = models.CharField(max_length=100, blank=False) field_6 = models.CharField(max_length=200, blank=False) In addition of these classes, I want to create a lead class. This class contains data that will be potentially copied into the other models in the future. The data constraints are therefore the same but since this is optional data, some might be missing. I want to use DRY, but I also want to update the blank field. Any tips on how to use the exact field definitions from those original classes? class Lead(models.Model): field_1 = A.field_1 # but with updated blank field field_3 = B.field_3 # but with updated blank field I considered class dependency, but in reality I'm using fields from 5 classes which I fear will become an unreadable mess if the lead class depends on these. -
Django wagitail backend oracle migrate ORA-00907: missing right parenthesis
Django 3.2.9 Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production cx_Oracle 8.3.0 Python 3.7.6 I create a new project Wagtail and i change in setting.py Database section DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': '(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXX)(PORT = 1526)) (CONNECT_DATA = (SERVER = DEDICATED) (SID = XXXX)))', 'USER': 'ZZZZZZ', 'PASSWORD': 'ZZZZZZZ', 'HOST': '', 'PORT': '', } } when execute python manage.py migrate show this error: WARNINGS: wagtailcore.WorkflowState: (models.W036) Oracle does not support unique constraints with conditions. HINT: A constraint won't be created. Silence this warning if you don't care about it. Operations to perform: Apply all migrations: admin, auth, contenttypes, home, sessions, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: Applying wagtailcore.0059_apply_collection_ordering...Traceback (most recent call last): File "C:\Users\A262556\Documents\PROGETTI\prj-intranet-new\cms-prova\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\A262556\Documents\PROGETTI\prj-intranet-new\cms-prova\venv\lib\site-packages\django\db\backends\oracle\base.py", line 523, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-00907: missing right parenthesis The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\A262556\Documents\PROGETTI\prj-intranet-new\cms-prova\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\A262556\Documents\PROGETTI\prj-intranet-new\cms-prova\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute … -
Is there a way to allow blank data for Django restframework
I have a products model that I want to have optional fields that are not required by the user whenever i try to input empty data it throws an error 400 back to the user meaning the serialized data is not valid views.py def products(request): if request.method == 'GET': products = Product.objects.filter(user=request.user) serializer = ProductSerializer(products, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ProductSerializer(data=request.data) serializer.initial_data['user'] = request.user.pk if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' models.py class Product(models.Model): name = models.CharField(max_length=50) description = models.TextField(blank=True) price = models.FloatField() quantity = models.IntegerField(blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shop = models.ForeignKey(Shop, on_delete=models.DO_NOTHING) discount = models.FloatField(default=0) -
unicode_to_repr - depricated package of "rest_framework"
While upgrading Django 2.2 to 3.2.9 I've encountered a couple of dependencies that were deprecated, of which "unicode_to_repr" is the one I couldnt find sufficient information about, neither on its usage or of its substitutes. Can someone advise how to proceed? Is there a valid replacement for this module? Thank you, Lior. -
Put data from form to database - Django - sqlite3
I'm trying to solve this problem. I have buttons, which values send to this form- So it's that initial. And user instance. And I want to send the data to databse and I don't know how... I will be glad that you help me views.py def form_create(request, pk): form = Message() user = User.objects.get(username=request.user.username, first_name=request.user.first_name, last_name=request.user.last_name, email=request.user.email) undermessage = Undermessage.objects.get(id=pk) if not request.user.is_anonymous: # it is pre-filled form = Message(request.POST or None, initial={'email': user.email, 'sender': user.username, 'name': user.first_name, 'surname': user.last_name, 'm1': undermessage.m1, 'm2': undermessage}) if request.method == "POST": if form.is_valid(): form.save() return redirect("/") context = { 'undermessage': undermessage, 'form': form } return render(request, 'form.html', context=context) models.py class Message(models.Model): time = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey(User, null=True, blank=False, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=False) surname = models.CharField(max_length=100, null=True, blank=False) m1 = models.ForeignKey(M1, null=False, blank=False, on_delete=models.CASCADE) undermessage = models.ForeignKey(Undermessage, null=True, blank=True, on_delete=models.CASCADE) text = models.TextField(blank=True) some error: Cannot assign "'usr1'": "M1.sender" must be a "User" instance. thank you a lot!! -
set an objects boolean in views (django)
I want to set a booleanfield to True. this is the code in views: def iniciarTorneo(request, id): torneo = Torneo.objects.get(pk=id) torneo.iniciado = True torneo.save() return render(request, 'torneos/detalle.html', {'torneo': torneo}) I come from here: path('iniciar_torneo/<int:id>', iniciarTorneo), But the boolean is not changing. -
Nginx Django and ReactJS
Here is Nginx config file: server { server_name atlasalgorithms.com www.atlasalgorithms.com; root /home/ubuntu/tc/react/build; index index.html index.htm index.nginx-debian.html; location /api { limit_req zone=one; limit_conn addr 10; include proxy_params; proxy_pass http://unix:/home/ubuntu/tc/config.sock; } location / { try_files $uri /index.html; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/atlasalgorithms.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/atlasalgorithms.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.atlasalgorithms.com) { return 301 https://atlasalgorithms.com$request_uri; } # managed by Certbot if ($host = atlasalgorithms.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name atlasalgorithms.com www.atlasalgorithms.com; return 404; # managed by Certbot } The issue is that Django is reading that /api path, I have /dashboard API endpoint when I go to https://atlasalgorithms.com/api/dashboard/ Django reads the path as api/dashboard/ which results in Page not found (404) The current path, api/dashboard/, didn’t match any of these. how can I fix this? -
Django queryset annotate if SearchQuery is found in field
I have a model like this: (With a trigger in Postgres that populates vector_column) class Article(models.Model) content = models.TextField() vector_column = SearchVectorField(null=True) I query this model like this: Article.objects.filter( Q( vector_column=SearchQuery( "cat", config="english", search_type="phrase" ) | vector_column=SearchQuery( "dog", config="english", search_type="phrase" ) ) ) So it will filter out all articles with "dog" and "cat" in the content. I've been trying to figure out how I can annotate the articles by if the word is found in the vector_column. I can not do two separate queries because, in reality, I have a lot more conditions in the query than this. The optimal output would be something like this: [ { "content": "cats", "words_found": ["cat"] }, { "content": "dogs", "words_found": ["dog"] }, { "content": "dogs and cats", "words_found": ["dog", "cat"] } ] -
Django ListView how to make query I need in class as I had it before in my function
I'm new at django and did my first project using book Eric Matthews python crash course, but now I'm trying do it better and change function that works perfectly into class, but can not get how to make it in Class the same query by filtering public and not public "topics" for users. Could somebody give me advice please how it works in classes? The function which is works perfectly and then the class I need worked like this function: def topics(request): """Provide list of topics.""" public_topics = Topic.objects.filter(public=True).order_by('date_added') if request.user.is_authenticated: private_topics = Topic.objects.filter(owner=request.user).order_by('date_added') topics = public_topics | private_topics else: topics = public_topics context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) And there is the class I need that it worked like the previous function. Could you advice what should be in queryset with public, owner and request? class TopicsHome(ListView): model = Topic template_name = 'learning_logs/topics.html' context_object_name = 'topics' def get_queryset(self): return Topic.objects.filter(public=True).order_by('date_added')