Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
implementation of link decorator in RichTextField (CKEditor) to Django admin panel
I am using CKeditor in my Django app and I'd like to ask if there is any way to implement link decorator to my body field (RichTextField). What I want is a feature that will detect tags (I am using django-taggit to handle tags) in the text and will create a hyperlink that will redirect to the tag page. For example. I put python is amazing in my RichTextField where python is a tag so it will be automatically hyperlinked to http://127.0.0.1:8000/tag/python after I save the article. Right now, I need to do it manually by clicking cltr+K and inserting a link but I am wondering if this can be automated by any chance? -
Django format a request in a list
I need help to format a response of a django request, This is a exemple : With a model like this: Book(models): name = string author = string release = date A request : Book.objects.filter(author='Hergé').value('name') I got : [{'name':'Tintin au Tibet'}, {'name':'Tintin au Congo'}, {'name':'Tintin chez les Picarros'}] I want this : ['Tintin au Tibet','Tintin au Congo','Tintin chez les Picarros'] My question: How to I get what I want by changing only the request ? -
Django : Add an additional set to objects without direct relative ForeignKey
The subject seems a bit confusing but my case is a little complicated. I'm building an app for mapping supplier products files (called FLOW). I've got 4 models : models.flow : flow from the supplier (csv) class Flow(models.Model): [...] nothing special here models.FicheHeader : all the fields I will populate with the datas fetched in the CSV class FicheHeader(models.Model): label = models.CharField(max_length=50, unique=True) models.FicheHeaderFlow : built another table for referencing all needed fields that need to be fulfilled class FicheHeaderFlow(models.Model): label = models.ForeignKey(FicheHeader, on_delete=models.CASCADE) flow = models.ForeignKey(Flow, on_delete=models.CASCADE) used = models.BooleanField(default=False) models.FlowSample : samples of the first line from the CSV recorded when flow is created class FlowSample(models.Model): index_col = models.IntegerField() content = models.TextField(max_length=255) flow_id = models.ForeignKey(Flow, on_delete=models.CASCADE) This last Model is only connected to the Flow FK. Now , I need to display in the same template all fields mapped with the relative columns ids of the CSV and show the result preview using the FlowSamples. I managed to do everything BUT retrieving FlowSamples related to the MappingField.fl_fiche_header_flow. Because MappingField and FlowSample have no FK direct relation (no SET possible). My query_set : def get_queryset(self, *args, **kwargs): return FicheHeaderFlow.objects. prefetch_related(Prefetch('mappingfield_set', MappingField.objects.select_related('fl_fiche_header_flow') .order_by('fl_fiche_header_flow_id', 'fl_fiche_inside_field_position'))) .filter(flow_id=self.kwargs['pk']).order_by('-used', 'pk') I tried during 2 … -
Parse second/third page and add to list with BeautifulSoup
I am trying to scrape a website for recipes and then present a page with a random pick. For this I have made a piece of code that works perfect when I just get the first page, 35 recipes. However: I want to grab the recipes from the 2nd and 3rd page as well. I figured I should write a loop for this but I can't seem to get it right. What did I do wrong in this code? from django.shortcuts import render import requests import re from bs4 import BeautifulSoup import random # Create your views here. def recipe(request): #Create soup page = 0 while page != 2: webpage_response = requests.get("https://www.ah.nl/allerhande/recepten-zoeken?page=" + str(page)) webpage = webpage_response.content soup = BeautifulSoup(webpage, "html.parser") recipe_links = soup.find_all('a', attrs={'class' : re.compile('^display-card_root__.*')}) recipe_pictures = soup.find_all('img', attrs={'class' : re.compile('^card-image-set_imageSet__.*')}) recipe_prep_time = [ul.find('li').text for ul in soup.find_all('ul', attrs={'class': re.compile('^recipe-card-properties_root')})] #Set up lists links = [] titles = [] pictures = [] #create prefix for link prefix = "https://ah.nl" #scrape page for recipe for link in recipe_links: links.append(prefix + link.get('href')) for title in recipe_links: titles.append(title.get('aria-label')) for img in recipe_pictures: pictures.append(img.get('data-srcset')) page = page +1 #create random int to select a recipe nummer = random.randint(0,105) print(nummer) #select correct link … -
Limit Django filter query set by a N number of field
I think I cannot well express myself with words so I can put some code so you can understand me better I have a model class Obj(models.Model): foo = models.IntegerField() Then I have 8 objects where. obj1.foo = 1 obj2.foo = 1 obj3.foo = 1 obj4.foo = 2 obj5.foo = 2 obj6.foo = 2 obj7.foo = 3 obj8.foo = 3 With the query set objs = Obj.objects.all() obj = QuerySet[obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8] Then the query that I want is limit the obj by foo filtered_obj = QuerySet[ obj1, # foo=1 obj2, # foo=1 obj4, # foo=2 obj5, # foo=2 obj7, # foo=3 obj8. # foo=3 ] I don't want repeated fields more than 2 times. -
Verifying SendGrid's Signed Event Webhook in Django
I am trying to get signed from sengrid Webhook: https://docs.sendgrid.com/for-developers/tracking-events/getting-started-event-webhook-security-features from sendgrid.helpers.eventwebhook import EventWebhook, EventWebhookHeader def is_valid_signature(request): #event_webhook_signature=request.META['HTTP_X_TWILIO_EMAIL_EVENT_WEBHOOK_SIGNATURE'] #event_webhook_timestamp=request.META['HTTP_X_TWILIO_EMAIL_EVENT_WEBHOOK_TIMESTAMP'] event_webhook = EventWebhook() key=settings.SENDGRID_HEADER ec_public_key = event_webhook.convert_public_key_to_ecdsa(key) text=json.dumps(str(request.body)) return event_webhook.verify_signature( text, request.headers[EventWebhookHeader.SIGNATURE], request.headers[EventWebhookHeader.TIMESTAMP], ec_public_key ) When I send test example from sengrid, always return False. I compared keys and all is correct, so, I think that the problem is the sintax of the payload: "b[{\"email\":\"example@test.com\",\"timestamp\":1648560198,\"smtp-id\":\"\\\\u003c14c5d75ce93.dfd.64b469@ismtpd-555\\\\u003e\",\"event\":\"processed\",\"category\":[\"cat facts\"],\"sg_event_id\":\"G6NRn4zC5sGxoV2Hoz7gpw==\",\"sg_message_id\":\"14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0\"},{other tests},\\r\\n]\\r\\n" -
Django unspecified error when deploying on Apache2
Below is the error when I try deploy Django==3.2.12, wagtail==2.16.1, python 3.8.2, mod_wsgi 4.9 on a Debian 11 server. I have a full stack trace at the end. class SimpleLazyObject(LazyObject): TypeError: Error when calling the metaclass bases 'property' object is not callable When I run this on my local dev machine which is a Mac it works just fine. I found someone with the exact same problem but no clarity about how it was resolved. The resources I have been using to assist are 1, 2, 3, 4. I have tried installing mod_wsgi using pip and as well as from sources. Used various guides for Apache2 config. Upgraded from python 3.8 to 3.9 as well as downgraded to 3.7. Create interpreter '0.0.0.0|'. [Tue Mar 29 11:49:06.679710 2022] [wsgi:info] [pid 199764:tid 139683953432320] mod_wsgi (pid=199764): Adding '/var/www/html/portal' to path. [Tue Mar 29 11:49:06.680057 2022] [wsgi:info] [pid 199764:tid 139683953432320] mod_wsgi (pid=199764): Adding '/var/www/html/portal/portalvenv/lib/python3.8/site-packages' to path. [Tue Mar 29 11:49:06.689628 2022] [wsgi:info] [pid 199764:tid 139683953432320] [remote xx.xx.xx.xxx:yyyy] mod_wsgi (pid=199764, process='saida-befree_portal', application='0.0.0.0|'): Loading Python script file '/var/www/html/portal/portal/wsgi.py'. [Tue Mar 29 11:49:06.705081 2022] [wsgi:error] [pid 199764:tid 139683953432320] [remote xx.xx.xx.xxx:yyyy] mod_wsgi (pid=199764): Failed to exec Python script file '/var/www/html/portal/portal/wsgi.py'. [Tue Mar 29 11:49:06.713633 2022] [wsgi:error] [pid 199764:tid … -
how to configuring django redirect_uri domain name when use ms-identity-python-django-tutorial
I'm trying to integrate the sso in ms-identity-python-django-tutorial, the redirect_url I configured in the Azure portal is https://example.com/auth/redirect, but the redirect_url when django project is started locally The domain name has always been localhost, how do I configure it as example.com in my project -
how to round up float or int input values in python
How to round up number in python, i have tried but when the user enters value it becomes string type.user can enter Float or int value.after that data is need to round(). Here i am checking ENtered value is valid Int or Float, If yes i am asking for choice => roundof Then here i need to roundof and print output def isfloat(num): try: float(num) return True except ValueError: return False def swicthChoice(arg,val): if(arg=="roundOf"): data = int(val) print(round(data)) else: print("Enter Valid ") def ask_ip(): val = input("Enter your value: ") #float or int. res = isfloat(val) if(res): arg = input("Enter your Chioce: ") swicthChoice(arg,val) else: print("Invalid Input") ask_ip() ask_ip() -
Adding interswitch in to a django project
I have an app where users would store students information. And I want to add Interswitch as my payment processor. I want a user to be able pay me $5 dollars every month. I'm using Django. I'm beginner in payment processing and I don't know how this works. Is anybody who can help me do that using Django. I do my own research but all I found is for PHP how can I use it using Django to make that happen. Thanks. -
Errors when viewing pages with children in admin UI after DB migration
After migrating our project from MySQL to PostgreSQL, parts of the admin UI has broken. When navigation to pages with children, an error is thrown which seems to originate from Wagtail core. Here's the log: Environment: Request Method: GET Request URL: https://beta.detfri.dk/admin/pages/3/ Django Version: 3.0.6 Python Version: 3.8.10 Installed Applications: ['home', 'search', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['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', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.legacy.sitemiddleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Template error: In template /var/www/detfri.dk/detfri/venv/lib/python3.8/site-packages/wagtail/admin/templates/wagtailadmin/pages/listing/_page_title_explore.html, error at line 6 operator does not exist: character = uuid LINE 1: ...."id") WHERE "wagtailcore_page"."translation_key" = '1c0af87... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. 1 : {% load i18n wagtailadmin_tags %} 2 : 3 : {# The title field for a page in the page listing, when in 'explore' mode #} 4 : 5 : <div class="title-wrapper"> 6 : {% if page.is_site_root %} 7 : {% if perms.wagtailcore.add_site or perms.wagtailcore.change_site or perms.wagtailcore.delete_site %} 8 : <a href="{% url 'wagtailsites:index' %}" class="icon icon-site" title="{% trans 'Sites menu' %}"></a> 9 : {% endif %} 10 : {% endif %} 11 : … -
can not render values of array (jquery)
hey i can not render all my values. i got names (button) if i click these i will render the array behind it. if i use .append() it will render all of them but when i click again it wil not refresh it and get stacked. what i want use is something like .text() or .html(). but i can not find the issue it wil return always the first one in the array and the other values are not showing. var treinen =$("#treinenArray0"); var list = data.info[0].kwalificaties; $.each(list, function(index, value){ treinen.html($('<li>'+ value + '</li>')); }); -
why does my django request.user is always anonymous except on chrome? [closed]
when I use firefox , I use the auth.login(request, user),and then I reload the front-end and send a request to django again,and then the request.user is anonymous,but it's okay on chrome,what's wrong? -
Update Database column after every 30 days in django
I am creating a Django application where my requirement is that for each user I have a boolean value which is set to False by default. Now if the user completes a particular task then the value change to true. Now after 30 days from the value changed to true the value should be updated to false. i.e user completes a task and then the value changes to true and remains to true for 30 days and then the value changes to false after 30 days automatically. How can I achieve this in Django? -
return Database.Cursor.execute(self, query, params)django.db.utils.OperationalError: no such column
I know before run the server i must be makemigrations but i can't i don't know so much python and django i can't migrate or makemigrations or runserver i tried specified for main app but still give me same error i write this 2 times nothing changed i try to make a price tracker for myself when i try makemigrations or runserver give me this error ; File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: main_app_item.status The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\KADAK\Desktop\Fiyat Takip\FiyatTakip\manage.py", line 21, in <module> main() File "C:\Users\KADAK\Desktop\Fiyat Takip\FiyatTakip\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\KADAK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 403, in check … -
Django Deserialization Error - Installing Fixture
I am trying to load JSON data into DATABASE, using the following: django_books % python manage.py loaddata book_import_data.json but unfortunately I am getting this: Traceback (most recent call last): File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/serializers/json.py", line 70, in Deserializer yield from PythonDeserializer(objects, **options) File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/serializers/python.py", line 125, in Deserializer for (field_name, field_value) in d["fields"].items(): KeyError: 'fields' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/jrchavez/Desktop/project/project-books/django_books/manage.py", line 22, in <module> main() File "/Users/jrchavez/Desktop/project/project-books/django_books/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/management/commands/loaddata.py", line 102, in handle self.loaddata(fixture_labels) File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/management/commands/loaddata.py", line 163, in loaddata self.load_label(fixture_label) File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/management/commands/loaddata.py", line 251, in load_label for obj in objects: File "/Users/jrchavez/Desktop/project/books_env/lib/python3.9/site-packages/django/core/serializers/json.py", line 74, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/jrchavez/Desktop/project/project-books/django_books/books/fixtures/book_import_data.json': this is the file i try to upload: [ { "model": "books.Book", "pk": 1 }, { "model": "books.Book", "pk": 2 }, { "model": "books.Book", "pk": 3 }, { "model": "books.Book", "pk": 4 }, { "model": "books.Book", "pk": 5 }, { "model": "books.Book", "pk": 6 }, { "model": … -
django template doesn't display fields of a list of objects
I'm currently working on a project using django 4.0.3 and I want to create a dashboard with the recent activities performed by a user. for exemple I have a LTA model and I want that whenever the user works on an LTA (create, read, or update) it is added to the recently viewed LTA. To do this I use a session key called "recently_viewed_lta" and whenever a user works on an lta it's Id is added to the session variable. This works fine, the problème is when I try to display them on a template it doesn(t display. I hope the code will help to understand my problem. this is my view def home(request): ltas = Lta.objects.in_bulk(request.session["recently_viewed_lta"], field_name='numlta') # ltas = Lta.objects.all() env = Enveloppevol.objects.all() rapports = Rapportvente.objects.all() context = { 'ltas': ltas, 'env': env, 'rapports': rapports } print(ltas) return render(request, "home.html", context) This is my home.html <p class="fs-3">Activité récente</p> <p>Here are the ltas {{ ltas }} </p> <p>Here is the session {{ request.session.recently_viewed_lta }} </p> {% for i in request.session.recently_viewed_lta %} <p>Session element {{ i }}</p> {% for lta in ltas.items %} <p>Lta n° {{ lta.numlta }} </p> {% endfor %} {% endfor %} <hr> this is the output … -
I want to change the throttle period in django API [closed]
I want to hit API only for 3 times after 3 times this API is not respond. After 3 hits on this API it show popup for registration.After filling this registration form again this API works. As per my knowledge, In django API throttle period are second, minute, hours,and day only. But i want that this API can not work after 3 hits till registration is not completed. My major issue that can we set throttle period infinite or long periods means years. -
Cronjob on windows using python
I am new in cron job...! SO, I need your help to build a cronjob. I want a cronjob that automatically schedule my google analytics data on windows? -
forbiden in django project on RHEL7 server
I have uploaded successfully my project on the RHEL7 server and it's running using the Nginx web server but when I am trying to login to my user then is throwing a Forbidden CSRF token. MY get request is working but not working POST request how do I solve it? -
how to override the update method of a model in django
I am using django with python. I am trying to update the model whenever a field is updated, in this case because i have a lambda function in the cloud, i want when a postgres query update an instance of the model, during the update action, update the age of the Person model below: data Contact table id = 1 name = 'john' age = 38 sql UPDATE contacts_contact SET name = 'jane' where id = '1'; # this works fine now i want to make sure that when the name is changed to jane as above, that the age update automatically in django with the override method django class Contact(models.Model): .. name = models.CharField() age = models.IntegerField() def update(self, *args, **kwargs): if self.age: self.age = 25 super().update(*args, **kwargs) # i tried this super(Contact, self).update(*args, **kwargs) # i tried this too both update methods i tried above do not update the age of the person regardless of the fact that the sql query update worked is there something that i am missing? PS: I want to update that field specifically in django, not in the sql query -
How to pass query string parameters in URL in Django Rest Framework
I'm trying to replicate this same URLhttp://localhost:1555/api/Data/GetPendingLevelTwo?levelId=2 in Django it takes a query parameter. Thought, I'm using the function based view for my whole project and no Serializers. All I just fetch from database and show it in front end. This is what I have tried views.py: def GetPendingLevelTwo(request, levelId): if request.method == 'GET': cursor = connection.cursor() cursor.execute('EXEC [dbo].[usp_getLevelTwo] @lvlOneId=%s,', (levelId)) result_set = cursor.fetchall() print('PendingLevelOne', result_set) data = [] for i in range(len(result_set)): data.append({ 'L1Id': result_set[i][0], 'Level1':result_set[i][1] }) return Response(data) urls.py: Here, I want to pass the ? instead of / path('Data/GetPendingLevelTwo/<int:levelId>', GetPendingLevelTwo, name='GetPendingLevelTwo'), -
How can i redirect url without trailing slash to one with trailing slash
I've got this code def category_view(request, path, instance): if instance is not None: categories = instance.get_ancestors(include_self=True) category_descendants = instance.get_descendants(include_self=True) product = ProductInStore.objects.filter(product__product_category__in=category_descendants).order_by('-created_at') paginator = Paginator(product, 9) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'categories': categories, 'product': product, 'page_obj': page_obj, } return render(request, 'ecommerce/category_view.html', context=context) return render(request, 'ecommerce/no_category.html') and this url url(r'^kategorie/(?P<path>.*)', mptt_urls.view(model='categories.models.EcommerceProductCategory', view='ecommerce.views.category_view', slug_field='slug'), name='category_view'), When i put category/categoryx/ it works, but when i put category/categoryx it looks for another category. Categoryx/ != categoryx Do you have any idea how to redirect the path without trailing slash to the one with trailing slash? -
Why edit is not working even code is correct
when I click on update, it is not updating. I don't know what to do. Everything is working except edit. views.py: def addnew(request): if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): try: form.save() return redirect('/') except: pass else: form = BookForm() return render(request,'book/index.html',{'form':form}) def index(request): books = Book.objects.all() return render(request,"book/show.html",{'books':books}) def edit(request, id): book = Book.objects.get(id=id) return render(request,'book/edit.html',{'book':book}) def update(request, id): book = Book.objects.get(id=id) form = BookForm(request.POST,instance=book) if form.is_valid(): form.save() return redirect('/') return render(request,'book/edit.html',{'book': book}) def destroy(request, id): book = Book.objects.get(id=id) book.delete() return redirect("/") urls.py: from django.contrib import admin from django.urls import path from book import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='index'), path('addnew',views.addnew), path('edit/<int:id>',views.edit), path('update/<int:id>',views.update), path('delete/<int:id>',views.destroy), ] templates/books: edit.html: <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script> </head> <body> {% block content %} <div class="col-md-12"> <form method="post" class="post-form" action="/update/{{ book.id }}"> {% csrf_token %} <div class="container"> <br> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <h3>Update Details</h3> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Book Id:</label> <div class="col-sm-4"> <input type="text" class="form-control" name="id" id="id_id" required maxlength="20" value="{{book.id}}"/> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Book Name:</label> <div class="col-sm-4"> <input type="text" class="form-control" name="name" id="id_name" required maxlength="100" value="{{book.book_name}}" /> </div> </div> … -
Show data from specific table in my view django
I want only the requests from the Hospital. How can I achieve this? Example: User from Hospital class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) FKbelongs_to = models.ForeignKey('HospitalViewRoleForUsers', on_delete = models.CASCADE, null=True, blank=True) Hospital Model class HospitalViewRoleForUsers(models.Model): RequestsFromLab = models.ForeignKey('request', on_delete=models.PROTECT) Requests from the Hospital FKHospitalRequests = models.ForeignKey('HospitalViewRoleForUsers', on_delete = models.PROTECT) user_request = models.ForeignKey('customuser', on_delete= models.PROTECT) In my View I need to validate which Hospital the user belongs to and, Pass only the request information from that hospital to my user view. The user view that I am trying to build def Get_UserRequestByHospital(request, pk): user = request.user items = requests.objects.filter(FKHospitalRequests = 1).values_list('id', flat = True) return render(request, 'user_profile/list-user-request.html', {'items': items}) In Jupyter testing data it appears like this user_hospital2 = requests.objects.filter(FKHospitalRequests = 1).values_list('id', flat = True) <QuerySet [1]> As we can see, Jupyter returns the request id. Which is linked to the Hospital. But, I am confused and I need help thinking on a solution. I am new to Django, so. I suppose I need to pass the PK to the view, and then, create a filter to check if PK is equal to FK from the Hospital Request? But, also, How I know this user belongs to the Hospital? …