Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pycharm cookiecutter docker django project Django support not working
I have a project that I have created with cookieecutter django (docker). I'm setting up Interpreter via docker-compose via Pycharm. Interpreter works fine. Django support is not working even though I have Django Support enabled. However, when I use Interpreter in another project in this project, django support works.But I can't use it because it's a different Interpreter for different project. even the .filter() function from one of my models does not come as a suggestion enter image description here enter image description here When I use the docker compose Interpreter of another project for this project in pycharm, django support works. But I couldn't understand, I created the project with cookiecutter, I didn't change anything. Why django support is not working. -
docker react+django, Access to XMLHttpRequest at 'http://localhost:8000' from origin 'http://localhost' has been blocked by CORS policy
I have a docker running with a service on the backend with Django and DRF, and another at the frontend with react I'm trying to make an API call from my react to my Django server const getRealItems = () => { axios.get(`http://localhost:8000/item`).then( (response) => { console.log("realItems = ", response) } ) } this endpoint works normally on a browser or through insomnia and returns a 200 with the data, I have also tried to replace the endpoint on my method to the pokemon API and received a 200 with the data, so the method is fine the issue is hitting the endpoint on my server This is my settings.py ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ ... 'rest_framework', 'restaurant', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] CORS_ALLOWED_ORIGINS = [ "http://localhost", "http://localhost:80", ] CORS_ORIGIN_ALLOW_ALL = True ... and I added this on my viewset.py class MenuItemViewSet(ModelViewSet): queryset = MenuItem.objects.all() serializer_class = MenuItemSerializer #GET def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) def finalize_response(self, request, response, *args, **kwargs): response["Access-Control-Allow-Origin"] = "*" return super().finalize_response(request, response, *args, **kwargs) … -
I have an aplication build with django for the backend, and for the front end i used tailwind css and flowbite ui, the problem is deploying on heroku
I have an aplication build with django for the backend, and for the front end i used tailwind css and flowbite ui (installed with npm), the problem is deploying on heroku, i can't get the css working on host, on production it uses ca cache css (i will provide a picture),i dont know why, i installed the django compressor (flowbite ui requierment).enter image description here I have tried almost everything, and i want a guide or video resolv this problem -
How to reference a varaible inside a template syntax in Django?
I have code as below: {% for entry in qs %} {% for field_name in field_names %} <span>{{entry.field_name}}</span> {%endfor%} {%endfor%} But nothing will show up inside span tag. Then I change back to {{entry.name}} which "name" is a property of every entry. Then the correct value shows up. Why is that? Thanks... -
I want to improve my queryset performance, I am using Pagination to return paginated response in django but its taking so much time
here is my pagination code over a queryset. query_end_time = time.time() - start print(query_end_time, "query_end_time") total_rows = query_set.count() number_of_pages = 0 paginator = Paginator(query_set, number_of_rows) number_of_pages = paginator.num_pages page_number = request.GET.get("page_number") order_item = list(paginator.get_page(page_number)) pagination_end_time = time.time() - start print(pagination_end_time, "pagination_end_time") query time and pagination time tried django pagination document but not landed to any conclusion -
Django not stop send line notify
I use django send line notify like this code in views.py . def lineAlert(token, msg): url = 'https://notify-api.line.me/api/notify' token = token headers = { 'content-type': 'application/x-www-form-urlencoded', 'Authorization':'Bearer '+token } while True: msg = msg r = requests.post(url, headers=headers , data = {'message':msg}) print(r.text) def Test(request): lineAlert('xxxxxxxxxxxxxxxxxxxxxxxx', "test") I want to send line notify 1 time only but it continue send message line notify like this. How to fix it? Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} {"status":200,"message":"ok"} -
django not receiving correct response? in front
overview When you press the 'like!' button, there is processing to feed back to the front screen via server processing (create or delete). No error when creating. Feedback is fine too. I get an error when deleting and the feedback doesn't work. The content of the error seems to be that json cannot be received correctly. The creation process and deletion process are almost the same, and the records are also registered and deleted in the database. So the processing is exactly the same. What's causing this? It seems so simple, but... detail # model class Articles(models.Model): title = models.CharField(max_length=200) note = models.TextField() user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) objects = ArticlesQuerySet.as_manager() @staticmethod def with_state(user_id: int) -> QuerySet: return Articles.objects.annotate( likes_cnt=Count('likes'), liked_by_me=Case( When(id__in=Likes.objects.filter(user_id=user_id).values('articles_id'), then=1), default=0, output_field=IntegerField() ) ) class Likes(models.Model): articles = models.ForeignKey('Articles', on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint( fields=['articles_id', 'user_id'], name='articles_user_unique' ) ] # views.py class LikesCreateView(LoginRequiredMixin, CreateView): def post(self, request, *args, **kwargs): return_value = None try: Likes.objects.create(user_id=kwargs['user_id'], articles_id=kwargs['article_id']) article = Articles.with_state(kwargs['user_id']).get(pk=kwargs['article_id']) return_value = json.dumps({'likes_cnt': article.likes_cnt, 'liked_by_me': article.liked_by_me}) print(f'LikesCreateView return_value[{type(return_value)}]: ', return_value) except User.DoesNotExist: logging.critical('There was an access from an unauthorized user account') except Articles.DoesNotExist: logging.critical('An unauthorized article was accessed') … -
AmazonLinux2 Welcome Page shows over Nginx Installation
So, I'm setting up a backend api on Amazon Linux 2 and I have installed Nginx, set up a service systemd file that uses Gunicorn to run the django instance and create a sock file at /home/ec2-user/backend/testsite.sock. That file is getting created properly. Loading that file into the Nginx /etc/nginx/conf.d/testsite.com server block. The Issue: testsite.com Nginx file: server { server_name api.testsite.com; listen 80; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; error_log logs/error.log warn; proxy_pass http://unix:/home/ec2-user/backend/testsite.sock; } } I've set up the security group to allow HTTP on port 80 and when I visit http://api.testsite.com, I'm seeing this page still: Thank you for using Amazon Linux 2. Now that you have it installed, find announcements and discussion in the AWS Discussion Forums. Also try AWS documentation. Nginx status output: (venv) [ec2-user@testsite conf.d]$ sudo systemctl status nginx.service ● nginx.service - The nginx HTTP and reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since Sun 2023-04-02 05:33:49 UTC; 39min ago Process: 3395 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS) Process: 3391 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS) Process: 3389 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS) Main PID: 3397 (nginx) CGroup: /system.slice/nginx.service ├─3397 nginx: master process /usr/sbin/nginx └─3398 nginx: … -
Django ORM & Django REST Framework: How to make "grouped" arrays?
Currently, my Django server can return the JSON below: [ { "id": 1, "customerId": 1, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 2, "customerId": 1, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 3, "customerId": 1, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 4, "customerId": 2, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 5, "customerId": 2, "description1": "...", "description2": "...", "description3": "...", "description4": "..." } ] I want to rewrite it and make some groups based on customerId(customer_id in Django), e.g. [ { "customerId": 1, "data": [ { "id": 1, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 2, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 3, "description1": "...", "description2": "...", "description3": "...", "description4": "..." } ] }, { "customerId": 2, "data": [ { "id": 4, "description1": "...", "description2": "...", "description3": "...", "description4": "..." }, { "id": 5, "description1": "...", "description2": "...", "description3": "...", "description4": "..." } ] } ] But I don't know how to make this using Django's views and serializers. How can I get such JSON? -
How to implement dynamic filtering in Django ListView based on user input?
I'm working on a Django project where I need to display a list of items and allow users to filter the items based on various criteria. I'm using Django's generic ListView for displaying the items, but I'm not sure how to implement the dynamic filtering based on the user's input. Here's my current setup: models class Item(models.Model): name = models.CharField(max_length=100) category = models.CharField(max_length=50, choices=CATEGORY_CHOICES) price = models.DecimalField(max_digits=6, decimal_places=2) available = models.BooleanField(default=True) views: class ItemListView(ListView): model = Item template_name = "items/item_list.html" item_list.html {% for item in object_list %} <div class="item"> <h2>{{ item.name }}</h2> <p>Category: {{ item.category }}</p> <p>Price: {{ item.price }}</p> </div> {% endfor %} I'd like to allow users to filter the items by category, price range, and availability. What's the best way to implement this functionality in a Django ListView? Any guidance or examples would be much appreciated! -
Custimizing Django Admin (multiple registraion to a model)
I have a Django app with a master model that has a lot on detailed models. the detaled models are related to the master with foreign keys in each. I registered my master model in django admin and included all my detail models as "TabularInline" layout. My models.py looks like: # models.py file # class MasterModel(models.Model): # master model fields ... class DetailModel_01(models.Model): # detail model fields class DetailModel_02(models.Model): # detail model fields class DetailModel_03(models.Model): # detail model fields class DetailModel_04(models.Model): # detail model fields My admin.py looks like: class Detail_01_Inline(admin.TabularInline): model = Detail_01 class Detail_02_Inline(admin.TabularInline): model = Detail_02 class Detail_03_Inline(admin.TabularInline): model = Detail_03 class Detail_04_Inline(admin.TabularInline): model = Detail_04 @admin.register(MasterModel) class MasterModelAdmin(admin.ModelAdmin): inlines = [ Detail_01_Inline, Detail_02_Inline, Detail_03_Inline, Detail_04_Inline, ] The master model has too many fields, and too many inlines. therefore, not convienient to the users. I need to splet the inlines. can i register the master model more than one time in Django admin, and include part of the inlines each time ?? your ideas are so appreciated. Suhail -
How to add a link in fcm-django notification?
I am working on a project where I am using fcm-django for sending push notifications to a devices. I want to include a link in the notification that opens a specific page in the web app when clicked. How can I add a link to the notification using fcm-django? Here is my code from firebase_admin.messaging import Message from firebase_admin.messaging import Notification from fcm_django.models import FCMDevice fcm_devices_of_this_user = FCMDevice.objects.filter(user=user_obj, active=True) if fcm_devices_of_this_user: fcm_devices_of_this_user.send_message( MESSAGE( notification=NOTIFICATION(title=notification_for, body=message) ) ) Any help would be appreciated. -
Why can't the inherited class get updated value?
The parent: class TemplateViewEnhance(TemplateView): cur_page_number = -1 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["field_names"] = School.get_fields_name() cur_page_number = int(self.kwargs["page_number"]) print("update page _number to {}".format(cur_page_number) ) child: class EditSchool(TemplateViewEnhance): template_name = "editschool.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(super().cur_page_number) result: update page _number to 1 -1 I think context = super().get_context_data(**kwargs) will update the cur_page_number value and then super().cur_page_number will get the updated value. But it's not. Also, do I hvae to give initial value to cur_page_number? Thanks. -
Only render part of django template if objects.all is not empty
I only want to render part of a django template if objects.all is not empty. Normally this is done like: <ul> {% for thing in things.all %} <li>{{ thing.name }}</li> {% empty %} <li>Sorry, nothing to list here</li> {% endfor %} </ul> But what if I want to have a heading or something that only shows if there's something to put in the list? I don't want the heading to be repeated each time the for loop runs. Is there something like {% not empty %} I could use, e.g.: {% if things.all not empty %} <h1>Here's the list of things</h1> <ul> {% for thing in things.all %} <li>{{ thing.name }}</li> {% endfor %} </ul> The above, however, throws a TemplateSyntaxError for django Not expecting 'not' as infix operator in if tag. How can we check if something is empty before running the loop? -
Render Submit Button in Same Row as Form Field in Django Crispy Forms
I'm using Django Crispy Forms, and rather than have the Submit button render below the rest of the fields, I want to move it to the same row as another field. My current Form code follows: class SetForm(forms.ModelForm): class Meta: model = Set fields = ['exercise', 'actual_weight', 'actual_reps', 'actual_difficulty'] helper = FormHelper() helper.form_method = 'POST' helper.layout = Layout( Row( Column('exercise', css_class='form-group col-md-12 mb-0'), css_class='form-row' ), Row( Column('actual_weight', css_class='form-group col-6 mb-0'), Column('actual_reps', css_class='form-group col-6 mb-0'), ), Row( Column('actual_difficulty', css_class='form-group col-6 mb-0'), Column(helper.add_input(Submit('submit', 'Submit', css_class='form-group btn-primary col-6 mb-0'))), ) ) This doesn't work though, the Submit button is still on its own row below the form, though the col-6 class does appear to be applied. I tried looking at this question, but it neither has answers nor uses Django Crispy Forms, as well as this one, but that one is focused on prepended text and it's not straightforward to modify the answers for this use case. Help please! -
301 redirect with query parameter "?page=" in urls.py
Have some problem with duplicate pages in Django 1.10. When the file had the following code: urlpatterns = [ ... url(r'^(?P<slug>[-\w]+)$', views.category, name='cat'), ... ] Pages site.com/category?page=5 and site.com/category/?page=5 displayed the same content. Then I added next redirect: urlpatterns = [ ... url(r'^(?P<slug>[-\w]+)$', views.category, name='cat'), url(r'^(?P<slug>[-\w]+)/$', RedirectView.as_view(pattern_name='cat', permanent=True)), ... ] And now i have redirect from site.com/category/?page=5 to site.com/category (without query parameter), but not to site.com/category?page=5 Please tell me where to fix it -
Collectstatic Code Line Changed my CSS code in Django
So I build a RESPONSIVE website on Django, and deployed it on Heroku. Here is a link https://three-d-production.herokuapp.com/ On a the full HD resolution design looks good, but when entered website on my phone, some parts of website were moved. I think that the problem in the settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') But I have no idea how to fix it. Here is a GITHUB code: https://github.com/PHILLyaHI/ThreeDProduction PLEASE HELP ME CHROME DEV TOOLS POV IPHONE 12 POV -
Can I create an instance of AbstractUser in my model class in the model.py in django?
I am new to django and from a tutorial video, in the model.py file for the profile app, he created an instance of the User model in a one-to-one relationship with the profile model class like so: ` from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, blank=True, null=True) I understand that he created a one-to-one relationship with the profile model and the User model by creating an instance of the User model in the class. I am trying to achieve this with AbstractUser as well. I tried to do the same thing like so: from django.contrib.auth.models import AbstractUser class Blogger(models.Model): user = models.OneToOneField(AbstractUser, blank=True, null=True) In the settings.py, I have connected the PostGresSql database like so: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'bookandreviews', 'USER': 'postgres', 'HOST': 'localhost', 'PASSWORD': '2030', 'PORT': '5432' } } I ran py manage.py runserver and I got this error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: users.Bloggers.user: (fields.E300) Field defines a relation with model 'AbstractUser', which is either not installed, or is abstract. users.Bloggers.user: (fields.E307) The field users.Bloggers.user was declared with a lazy reference to 'auth.abstractuser', but app 'auth' doesn't provide model 'abstractuser'. I don't understand it. So I tried to add … -
if form.is_valid() return errors when using get_or_create
class Books(models.Model): book_file = models.FileField( upload_to="books", validators=[validate_book_extension], verbose_name="book", ) title = models.CharField(max_length=255, default=None) author = models.ForeignKey(Author, on_delete=models.CASCADE, default="") coauthors = models.ManyToManyField(CoAuthor, blank=True) publisher = models.ForeignKey( Publisher, on_delete=models.SET_DEFAULT, default=None, related_name="books_published", ) genres = models.ManyToManyField(Genre) edition = models.IntegerField(default=None) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) i am having trouble with form validation when uploading a book to a database. The model has fields for authors and coauthors with ForeignKey and ManyToManyField relationships, and you're using the get_or_create method in the view function that handles the submission of fields with ForeignKey and ManyToManyField relationship. However, the if form.is_valid() statement returns errors and if i don't check if the form is valid the form submits. Below is the error that pops up. views.py @login_required def addbook(request): if not request.user.is_superuser: return redirect(notfound) else: books = Books.objects.all() genres = Genre.objects.all() authors = Author.objects.all() coauthors = CoAuthor.objects.all() publishers = Publisher.objects.all() form = BookForm() if request.method == "POST": form = BookForm(request.POST, request.FILES) if form.is_valid(): book = request.FILES.get("book_file") title = request.POST.get("title") genres_name = request.POST.getlist("genres") author_name = request.POST.get("author") co_authors = request.POST.getlist("coauthors") publisher_name = request.POST.get("publisher") author, created = Author.objects.get_or_create( name=author_name.title()) publisher, created = Publisher.objects.get_or_create( name=publisher_name.title() ) book = Books.objects.create( title=title.title(), publisher=publisher, edition=request.POST.get("edition"), author=author, book_file=book, ) for genre in genres_name: … -
Pythonanywhere Template is not rendering on the django
I'm trying to deploy my webapp on pythonanywhere, but my template is not rendering at all, however the same code is showing just fine on my local visual studio. i'm receiving the below error. my views is as follows: from django.shortcuts import render # Create your views here. def Home(request): return render(request, 'Home.html') my settings is TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'Templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Please help, what am i missing? -
Forbidden (CSRF cookie not set.) - Django 4.1 and React
General Information: I'm facing the following error Forbidden (CSRF cookie not set.) while posting in my React app. I've been through many of the similar posts, but they doesn't seem to solve my issue. I believe my issue is on my React app, and not on my Django side, since I do get a 200 response on a GET request, but when posting, my React app doesn't get a grip on my CSRF token. Noted, but unexplainable: I do not see my CSRF set when I check in Applications in my chrome inspector on http://localhost:3000/ Terminal Response: Django System check identified 1 issue (0 silenced). April 01, 2023 - 22:02:51 Django version 4.1.7, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [01/Apr/2023 22:05:05] "GET /accounts/csrf-cookie HTTP/1.1" 200 29 Forbidden (CSRF cookie not set.): /accounts/register/ [01/Apr/2023 22:05:14] "POST /accounts/register/ HTTP/1.1" 403 2870 React Note that the development build is not optimized. To create a production build, use npm run build. assets by status 1.33 MiB [cached] 17 assets assets by status 16.9 MiB [emitted] assets by chunk 16.9 MiB (name: main) asset static/js/bundle.js 16.9 MiB [emitted] (name: main) 1 related asset asset main.41b1aa5256b383579099.hot-update.js 4.01 KiB [emitted] … -
I want to deploy django to gae and display images
I have an app created with django and deployed with google app engine. Images stored in the static folder are not displayed in the template. But the css file works fine. I don't understand why the image is not loaded even though the css file is loaded. Is there any solution? ▼version Django 4.1.1 ▼Error GET https://<myapp>.an.r.appspot.com/static/img/example.png/ 404 ▼app.yaml runtime: python39 instance_class: F1 env: standard service: default entrypoint: gunicorn -b :$PORT config.wsgi:application includes: - secrets/secret.yaml handlers: - url: /static static_dir: staticfiles/ - url: .* secure: always script: auto ▼part of settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent if os.getenv('GAE_APPLICATION', None): # production DEBUG = False ALLOWED_HOSTS = ['myapp.an.r.appspot.com'] else: # develop DEBUG = True ALLOWED_HOSTS = ['*'] import yaml with open(os.path.join(BASE_DIR,'secrets','secret_dev.yaml'), encoding="utf-8") as file: objs = yaml.safe_load(file) for obj in objs: os.environ[obj] = objs[obj] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', "myapp", 'django_cleanup.apps.CleanupConfig', 'django_feather', 'widget_tweaks', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", 'myapp.middleware.middleware.AdminProtect', ] ROOT_URLCONF = "config.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'templates'),], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", 'myapp.context_processor.notice_content', ], }, }, ] WSGI_APPLICATION = "config.wsgi.application" # Database … -
Search a part of a word using django-elasticsearch-dsl-drf
I am building a Django application that contains search engine using elastic search by django_elasticsearch_dsl_drf library. I want to allow user to search for only letters or a part of a word and elastic search returns all words that contain these letters. For example if the user submitted 'legal' word the result will be all articles containing 'legal, legally, illegal, illegally'. I have used nGram tokenizer to make this but it doesn't work as when I submit the word no results are shown to me. here is the most important part which is in documents.py: from django_elasticsearch_dsl import Document, fields, Index from django_elasticsearch_dsl.registries import registry from django.conf import settings from .models import * from elasticsearch_dsl import analyzer, tokenizer autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'nGram', min_gram=1, max_gram=20), filter=['lowercase'] ) entry_index=Index('entries') @registry.register_document class EntryDocument(Document): title = fields.TextField( attr='title', fields={ 'raw': fields.TextField(required=True,analyzer=autocomplete_analyzer), 'suggest': fields.CompletionField(), } ) body = fields.TextField( attr='body', fields={ 'raw': fields.TextField(required=True,analyzer=autocomplete_analyzer), # 'suggest': fields.CompletionField() } ) class Index: name = 'entries' settings = { "number_of_shards": 1, "number_of_replicas": 0, 'max_ngram_diff': 20 } class Django: model = entry fields= [] for more details: models.py: class entry(models.Model): title = models.CharField(max_length=600) body = models.TextField() Serializers.py: class EntryDocumentSerializer(DocumentSerializer): class Meta: document = EntryDocument fields = ( 'title', … -
This django app asks a mutiple-choice question from the user
The app checks the user answer and shows the result and then checks if the user answered the question or not. if the user answered the question the options will disable and **checks **the option that user selected but i got that error: TemplateSyntaxError at /questions/ Could not parse the remainder: '[question.id]' from 'answers[question.id]' html: ` {% for question in questions %} <div class="question"> <p>{{ question.text }}</p> <form method="post" action="{% url 'submit_answer' question.id %}"> {% csrf_token %} <input type="hidden" name="question" value="{{ question.id }}"> <input type="radio" id="option_1_{{ question.id }}" name="answer" value="1" {% if 1 in answers[{{question.id}}] %}checked{% endif %} {% if answers[question.id] is not None %}disabled{% endif %}> <label for="option_1_{{ question.id }}">{{ question.option_1 }}</label> <br> <input type="radio" id="option_1_{{ question.id }}" name="answer" value="2" {% if 2 in answers[question.id] %}checked{% endif %} {% if answers[question.id] is not None %}disabled{% endif %}> <label for="option_2_{{ question.id }}">{{ question.option_2 }}</label> <br> <input type="radio" id="option_1_{{ question.id }}" name="answer" value="3" {% if 3 in answers[question.id] %}checked{% endif %} {% if answers[question.id] is not None %}disabled{% endif %}> <label for="option_3_{{ question.id }}">{{ question.option_3 }}</label> <br> {% if not request.session.question_answers.get(str(question.id)) %} <button type="submit">Submit Answer</button> {% else %} <p>Your answer has been submitted.</p> {% endif %} </form> </div> {% endfor %} … -
django filter by related
my models: class Person(models.Model): name = models.CharField(max_length=255) class BankAccount(models.Model): iban = models.CharField(max_length=28) owners = models.ManyToManyField(Person, through='BankAccountPerson') class BankAccountPerson(models.Model): bank_account = models.ForeignKey(BankAccount, on_delete=models.RESTRICT, related_name = 'ownership') person = models.ForeignKey(Person, on_delete=models.RESTRICT, related_name = 'ownership') is_owner = models.BooleanField(null=True, blank=True) class Meta: unique_together= [['bank_account','person']] let's assume, that account no 1 has two owners: person:1 and person:2 And now if I filter like this: person=Person.objects.get(pk=1) collection = BankAccount.objects.filter(owners=person) will get only one row - with person1. But I'd like to get two rows: - with both people. Because I want to get accounts with owners, where one of owners is person I can do it with SQL: SELECT * FROM structure_bankaccount INNER JOIN "structure_bankaccountperson" ON ("structure_bankaccount"."id" = "structure_bankaccountperson"."bank_account_id") WHERE structure_bankaccount.id in (SELECT bank_account_id FROM "structure_bankaccountperson" WHERE "structure_bankaccountperson"."person_id" = 1) I can do it with two steps: owned_accounts = BankAccountPerson.objects.filter(person=person).values_list('bank_account_id') collection = BankAccount.objects.filter(id__in=owned_accounts) But I wonder if I can do it with some Q, F or other function in one django filter...