Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python django intercepting an sql query before it is executed
I have a library that natively crashes into django and works with django Admin and knows how to use objects.all() and so on. The QuerySet goes instead of to the database location in another api project. I need to intercept an sql query before executing which django does so that I can do even more magic with queries. maybe someone knows how to do it in theory ? well, or there is an example I will be glad to see. у меня есть библиотека которая нативно врезается в django и работает с django Admin и умеет использовать objects.all() и тд. Сам QuerySet в место базы данных ходит в другой проект по api. мне нужно перехватить sql запрос до выполнения который делает django что бы я мог делать еще больше магии с запросами. может кто то знает как это в теории сделать ? ну или есть пример буду рад увидеть. I tried to look for something similar on the Internet, but everywhere there is information only for outputting information to the logs about executed requests through Middleware я пробовал искать что то подобное в интернете но везде есть информация только на вывод в логи информацию о выполненных запросах через Middleware -
pylint with Django settings not working in vscode
I am attempting to configure pylint to use in my Django project. However, in VS Code it does not seem to be working when I configure my settings.json. For example, my settings.json is as follows: { "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.linting.pylintArgs": [ "--disable=C0111", "--load-plugins", "pylint_django", "--django-settings-module", "myproject.settings" ] } When I remove the two lines "--django-settings-module" and "myrpject.settings", pylint begins to work and throws linting errors. When I add the lines back, the linting errors go away (when they should actually be linting errors i.e. importing a package that isn't used). Below is my folder structure for the project I am working in. What could be the issue behind the django-settings-module? Why is it not registering when the argument is used? -
Django how to pass clicked on link text to a URL on another HTML page showing static images?
I have table of tickers on one HTML page, and four charts displayed on another HTML page. These charts come from my static/images folder full of hundreds of images named by ETF tickers. If I click the ETF ticker "PSCD" in the first row of the table, how can I have that linked in the other HTML page so that it shows only the images from my static/images folder whose filename contains the associated ticker...in this case "PSCD" when clicked. In the charts.html code example below, I hardcoded PSCD into the image tag but I want this dynamically linked. Below you will see my table.html page showing my table from above. Next is the charts.html where I would like the etf_ticker that was clicked in that table to be entered into the image tags such as <img src="{% static 'forecast/images/sample_regression_PSCD.jpg' %}" alt="sample_regression"/></div> where you see I have hardcoded "PSCD" into the image tag. But I need this to be dynamic, from which you click on the link in table.html, and it gets inserted into the image tag in charts.html. table.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ETF Table</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/table_style.css' %}"> … -
Combining two serializer into one
I have a ListApiView where i list the data on a website and on the same page i could select the records and export to xl and pdf file here right now i am using same serializer called ListingSerializer for exporting the data to file and listing it, for listing the data and exporting the fields are same except for exporting i have two additional fields to be exported but right now i need two serializers one for listing ListingSerializer and other for exporting ExportSerializer without repeating the fields. class ListingSerializer(serializers.ModelSerializer): class Meta: model = Mymodel fields = '__all__' class ExportSerializer(serializer.ModelSerializer): date_records_received = serializers.SerializerMethodField() class Meta: model = Mymodel fields = '__all__' Class Mylist(ListAPIView): def get_queryset(): return queryset def get_serializer(): serializer = ListingSerializer(self.get_queryset(), many=True, context={'request': self.request}) return serializer -
When I access the page, nothing appears
question I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem? class Post(models.Model): created =models.DateTimeField(auto_now_add=True,editable=False,blank=False,null=False) title =models.CharField(max_length=255,blank=False,null=False) body =models.TextField(blank=True,null=False) def __str__(self): return self.title from Todolist import models from django.views.generic import ListView from django.utils import timezone class TodayView(ListView): model = models.Post template_name ='Todolist/today.html' def get_queryset(self): Today_list= models.Post.objects.filter( created=timezone.now()).order_by('-id') return Today_list {% extends "Todolist/base.html" %} {% block content %} {% for item in Today_list %} <tr> <td>{{item.title}}</td> </tr> {% endfor %} {% endblock %} urlpatterns=[ path('today/' ,views.TodayView.as_view() ,name='today')] -
Failed building wheel for psycopg2 (Windows 11)
I am building a Django project, and as I was installing the psycopg2(using virtual env), I kept getting an error. Versions: Django==4.1.2 Python==3.11.0 PIP==22.3 OS==Win11 Code: (env) PS C:\Users\keiko\Desktop\project> pip install psycopg2 Error: ERROR: Failed building wheel for psycopg2 Running setup.py clean for psycopg2 Failed to build psycopg2 Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure I have already tried the solutions I found on the internet like: Install psycopg2-binary instead. Code: pip install psycopg2-binary Error: Failed building wheel for psycopg2-binary Upgrade the wheel and setup tools Code: pip install --upgrade wheel pip install --upgrade setuptools pip install psycopg2 Install it with python Code: python -m pip install psycopg2 ERROR: Failed building wheel for psycopg2 Install the Microsoft C++ Build Tools ... but still none of these solutions helped me. I'm really hoping to install the package(psycopg2) on my project, I've been stuck with this error for so long and I can't really find any solution to this. I hope someone can help me with this. -
Beginner in Django, I would like to know how to retrieve the fields of the Consultation table starting from the Students table?
This is the error I get ProgrammingError at /Action/PassagePerso/19E000183/ operator does not exist: character varying = numeric LINE 1: ...on", public."Actions_students" WHERE matricule_id = 19E00018... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Request Method: GET Request URL: http://127.0.0.1:8000/Action/PassagePerso/19E000183/ Django Version: 4.1.2 Exception Type: ProgrammingError Exception Value: operator does not exist: character varying = numeric LINE 1: ...on", public."Actions_students" WHERE matricule_id = 19E00018... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Exception Location: /home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school/venv/lib/python3.10/site-packages/django/db/backends/utils.py, line 89, in _execute Raised during: Actions.views.ConsultationPersonnelle Python Executable: /home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school/venv/bin/python Python Version: 3.10.4 Python Path: ['/home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/jasonfofana/D/Workspace/PYTHON/Projects/Pharmacy_school/venv/lib/python3.10/site-packages'] Server time: Wed, 02 Nov 2022 02:42:05 +0000 I would like to use the two tables Consultation and Students in relations to display the information of a person def ConsultationPersonnelle(request, pk_student): student = Students.objects.get(pk=pk_student) consult = Students.objects.raw(f'SELECT * from public."Actions_consultation", public."Actions_students" WHERE matricule_id = {student.matricule} and matricule = {student.matricule}') context = {'consultant': consult} return render(request, 'consult_perso.html', context) -
CSS files loaded but got not rendered Django Rest Framework
I have a Django app with Gunicorn and Nginx deployed on AWS ECS. NGINX can load static files but the page still shows only text. Nginx: server { listen 80; listen [::]:80; server_name api.example.com; location /health { access_log off; return 200; } proxy_read_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; # Main app location / { if ($request_method !~ ^(GET|POST|HEAD|OPTIONS|PUT|DELETE|PATCH)$) { return 405; } include /etc/nginx/mime.types; proxy_pass http://example-api:8000; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_set_header X-Forwarded-Port $http_x_forwarded_port; } location /static/ { autoindex on; alias /my_app/static/; } } In settings.py STATIC_URL = '/static/' STATIC_ROOT = '/my_app/static/' When I inspect the webpage, all CSS files are loaded, no 404 (It was an issue before but I fixed that). So not sure what else I am missing here. The UI works fine when running without Nginx and runserver, but on AWS ECS, I use gunicorn. -
How to use stored_procedure on Django Rest_framework
I'am trying to use my own stored_procedure to create an API of my own, it's purpose is to add an item into a table this is my raw Models.py class Clearanceinsert(models.Model): sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) this is currently my insert function def add(request): if request.method == "POST": if request.POST.get('sem') and request.POST.get('sy') saverec = Clearanceinsert() saverec.sem = request.POST.get('sem') saverec.sy = request.POST.get('sy') cursor = connection.cursor() userid = request.user.userid cursor.execute("select add_clearance_item_new('"+saverec.sem+"','"+saverec.sy+"') return HttpResponseRedirect('/Admin/index') else: return render(request, 'Admin/add.html') I did create an serializer class InsertItemSerialize(serializers.ModelSerializer): Class Meta: fields = ['sem','sy'] I remove some column so the code is shorter and easy to read, but this is basically it -
How to cache database tables in Django?
My app requires repetitive lookup a lot from same tables. Normally it should be design with foreign key to refer from table1 to table2, but there are no foreign keys design(yes db designed poorly). views look like this: class FileDownloaderSerializer(APIView): def get(self, request, **kwargs): filename = "All-users.csv" f = open(filename, 'w') datas = Userstable.objects.using(dbname).all() serializer = UserSerializer( datas, context={'sector': sector}, many=True) df=serializer.data df.to_csv(f, index=False, header=False) f.close() wrapper = FileWrapper(open(filename)) response = HttpResponse(wrapper, content_type='text/csv') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = "attachment; filename=%s" % filename return response this is my serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = Userstable fields = _all_ section=serializers.SerializerMethodField() def get_section(self, obj): return section.objects.using(dbname.get(pk=obj.sectionid).sectionname department =serializers.SerializerMethodField() def get_department(self, obj): return section.objects.using(dbname).get(pk=obj.deptid).deptname there are lots of table, more than 5 table, here I'm just showing 2 of them. Basically in the csv we need to import representable data. But in the main table, they only stored the id of the data, we need to get the actual representable data from the secondary table, hence the lookups. from the basics of programming. I understand that python normally cached variables that were being declared when a process runs, so the program doesn't have to go through declarations every time the variable is called. … -
Is there a way to filter a queryset with a field from another queryset in Django?
I am working on an endpoint that given a purhcase_id or a list of purchase_ids, it should return product_id and its related [info_ids], but in order to find the product_ids, I need to look into invoice table Data structure Invoice Table purhcase_id invoice_id Product Table product_id info_ids invoice_id Info Table info_id info_fields The input is purhcase_id, and purhcase_id has a 1:1 relationship to invoice_id, so that I should be able to do a lookup to get the invoice_id, and use that invoice_id to filter products + get its related info_ids, however, I am not sure how to do this in django properly with this nested relationship. -
Django return JsonResponse and continue
I have this function in Django and I want that when ever the return JsonResponse(payload) is executed, Django should continue to execute the rest of the code but the rest of the code is rather not def paytes(request): payload ={ "USERID": code_id, "MSISDN": serviceCode, "MSGTYPE": type_msg, "USERDATA": text, "SESSIONID": session_id, "MSG": response, } print('MSG: ',response) # headers = { # 'Content-Type': 'application/json' # } # response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) return JsonResponse(payload) url = 'https://prod.theteller.net/v1.1/transaction/process' transaction_id = random.randint(100000000000, 999999999999) amounte = "000000000080" amount = str(amounte) data = { "amount" :amount, "processing_code" : "000200", "transaction_id" : transaction_id, "desc" : "Mobile Money Payment Test", "merchant_id" : "TTM-00000727", "subscriber_number" : "233244491909", "r-switch" : "MTN", } encoded = base64.b64encode(b'rad5d4a81d6a3453:MTQwODBiMjU3Yzg1ODhhYmIwM2Q5ZmFmYWVlNjJkOWQ=') # change this as well headers = { 'Content-Type': 'application/json', 'Authorization': f'Basic {encoded.decode("utf-8")}', 'Cache-Control': 'no-cache' } res = requests.post(url, data=json.dumps(data), headers=headers) print(res.text) response_data = res.json() status = response_data["status"] print(response_data) print(status) return HttpResponse(res) -
How To Join Two Models with Different Column Names and Return All Instances?
I aim to create a dataframe of the Top 3 Selling menu_items in my Purchases table. My thoughts are to create a join on the Purchases model with the Menu_Item model where Purchases.menu_item = Menu_Item.title. I will convert the QuerySet to a DataFrame using django_pandas.io. I plan to use the sum of Menu_Item.price associated with each distinct Purchases.menu_item to determine the Top 3 menu_items of all the records in the Purchases table. My problem is that I cannot join the two tables successfully. I’ve scoured the interwebz for a working solution to join two models with different field names, which returns all instances, and I tried various solutions, but the scarce articles on this topic yielded no joy. models.py ... class MenuItem(models.Model): title = models.CharField(max_length=100, unique=True, verbose_name="Item Name") price = models.FloatField(default=0.00, verbose_name="Price") description = models.CharField(max_length=500, verbose_name="Item Description") def __str__(self): return f"title={self.title}; price={self.price}" def get_absolute_url(self): return "/menu" def available(self): return all(X.enough() for X in self.reciperequirement_set.all()) class Meta: ordering = ["title"] class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, verbose_name="Menu Item") timestamp = models.DateTimeField(auto_now_add=True, verbose_name="DateTime") def __str__(self): return f"menu_item=[{self.menu_item.__str__()}]; time={self.timestamp}" def get_absolute_url(self): return "/purchases" class Meta: ordering = ["menu_item"] I tried adapting too many unsuccessful code fragments to reproduce here, so I am looking … -
testdriven.io: The Definitive Guide to Celery and Django. Running task from Django shell causes error
I am currently going through 'The Definitive Guide to Celery and Django' course by testdriven.io. I've managed to containerize the whole application. Everything was built correctly and seemed to work just fine, but when I tried to enter the Django shell and run a task, to ensure everything works correctly, the following error appeared. >>> divide.delay(1, 2) Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/usr/local/lib/python3.10/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/usr/local/lib/python3.10/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/usr/local/lib/python3.10/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/usr/local/lib/python3.10/site-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) File "/usr/local/lib/python3.10/site-packages/amqp/transport.py", line 184, in _connect self.sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.10/site-packages/celery/app/task.py", line 425, in delay return self.apply_async(args, kwargs) File … -
MMO Backend Architecture Questions and Review Request
I am making a simple MMO backend with Django as a personal/portfolio project. (I am not actually making an mmo game) You can find the project here So I have some questions for the architecture because I designed it 1. Architecture 1.1 Terminology AuthServer= Web Server responsible for the authentication UniverseServer= Web Server responsible for the persistent storage of the game (Couldn't find a better naming) MatchmakingServer= Web Server that acts as intermediary between the client and the GameServerManager GameServerManager= A cluster manager responsible for starting/stoping GameServerInstances GameServerInstance= An instance of the game server PlayerClient= The game client of the player 1.2 Flow 1.2.1 Authentication PlayerClient logins to AuthServer to obtain an AuthToken at /api/auth/login/ 1.2.2 Retrieving Player Data PlayerClient requests all the needed data from the UniverseServer at /api/universe/user/{...} (example: the characters list) 1.2.3 Connecting To A Game Server PlayerClient requests an available game server from the MatchmakingServer with some parameters The MatchmakingServer checks if there is an available GameServerInstance on the database with these parameters If there is an available GameServerInstance, the MatchmakingServer responds to the PlayerClient with the IP and the Port of the GameServerInstance, else it is gonna send a request to the GameServerManagerto spawn one … -
Django logging configuration star notation
Let's say I have the following Django logging config: LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "root": { "handlers": ["console"], "level": "WARNING", }, "loggers": { "django": { "handlers": ["console"], "level": "INFO", "propagate": False, }, "app1.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, "app2.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, "app3.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, }, } Notice how I'm repeating the same configuration for all app management commands. I'd love to be able to consolidate into a single entry like so: "*.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, } But this doesn't seem to work. Is this possible or do I need to repeat the config for all apps? -
Getting Celery tasks repeated multiple times in production
I'm new to Celery, and I created a simple app that connects to a web socket server to receive tasks and schedule them using Celery. My Celery queue display tasks based on the type of the message (text messages first, and then buttons that run the next task if one of them is clicked). Locally, everything run as expected. But, some tasks are repeated multiple times in production, especially the triggers (buttons). In my production environment, I created a web service for Django and one Celery background worker with a Redis database. Here are the commands I used to run Celery worker and beat in production: # Start command (celery worker and beat) celery -A bot.celery worker --beat --scheduler django --loglevel=info --concurrency 4 # Start command (Django) daphne -b 0.0.0.0 bot.asgi:application My Django and Celery settings: CELERY_BROKER_URL = "redis://localhost:6379/0" # localhost replaced with the internal Redis URL in production CELERY_RESULT_BACKEND = "redis://localhost:6379/1" # localhost replaced with the internal Redis URL in production TIME_ZONE = 'UTC' CELERY_ENABLE_UTC = True CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' ASGI_APPLICATION = 'bot.asgi.application' Some of the worker output: Nov 1 09:00:15 AM [2022-11-01 08:00:15,178: INFO/MainProcess] missed heartbeat from celery@srv-cdcl4202i3msb94icl70-5469f7b9d8-gzks7 Nov … -
Django how to hyperlink to images in static folder by ticker symbol?
I have a table of ETF tickers, ETF names, and their Index names. I want each entry in the table to be clickable and linked to their associated images in the static/images folder. Each image is named after each ETF's index ticker. So when a user clicks on, for example, the first entry ETF ticker "PSCD" links to 'static/myapp/images/sample_regression_S6COND.jpg'. The substring in the link "S6COND" is the part I need as a relative link. Each ETF ticker has a different Index ticker. These Index tickers are in a model associated with the table. In my table.html page, when I hardcode the link to the static image <td><a href="{% static '/myapp/images/sample_regression_S6COND.jpg' %}" target="_blank">{{i.etf_ticker}}</a></td> (see how I typed "S6COND" into the link?), it works, but not when I try to turn it into a relative link {{i.index_ticker}} like <td><a href="{% static '/myapp/images/sample_regression_{{i.index_ticker}}.jpg' %}" target="_blank">{{i.etf_name}}</a></td>. My static files in correctly placed inside my app folder and includes images, css, and js folders. All images are inside the static/myapp/images folder. table.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ETF Table</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/table_style.css' %}"> <style type="text/css"></style> </head> <body> <div class="container"> <table id="table" class="table table-dark table-hover table-striped table-bordered … -
Django DateField returns error: str' object has no attribute 'day'
I'm not sure why I'm getting this error. I'm happy to provide add'l info! I've been working through a Django tutorial that makes articles for a blog. I've got the page up and the admin setup. When trying to add an article, the error is generated. In my model I have a DateField with auto_now_add=True. I would think that would pull the datetime, but it's returning the error on date.day. AttributeError at /admin/post/article/add/ 'str' object has no attribute 'day' Request Method: POST Request URL: http://xxx.x.x.x:8000/admin/post/article/add/ Django Version: 4.1.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'day' Exception Location: /Users/user/PycharmProjects/assembly_tracker/venv/lib/python3.10/site-packages/django/db/models/base.py, line 1338, in _perform_date_checks Raised during: django.contrib.admin.options.add_view Python Executable: /Users/user/PycharmProjects/assembly_tracker/venv/bin/python Python Version: 3.10.3 Python Path: ['/Users/user/PycharmProjects/assembly_tracker', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Users/user/PycharmProjects/assembly_tracker/venv/lib/python3.10/site-packages'] Server time: Tue, 01 Nov 2022 19:37:30 +0000 The error is coming in on the following lines in _perform_date_checks when it hits date.day lookup_kwargs = {} # there's a ticket to add a date lookup, we can remove this special # case if that makes it's way in date = getattr(self, unique_for) if date is None: continue if lookup_type == "date": lookup_kwargs["%s__day" % unique_for] = date.day … lookup_kwargs["%s__month" % unique_for] = date.month lookup_kwargs["%s__year" % unique_for] = date.year else: … -
How to store list of tuples in django model
I am working on a food recipe database web app in Django 4 and want to store an unknown number of ingredients required for a recipe within a given model. The ingredient is described by a name, a volume, and a measuring unit - eg: Sugar 400 grams, Eggs 2 pieces, etc. I am using PostgreSQL What is the best practice to store such data within a given model while preserving the ability to query the data or do arithmetic operations on the volumes of the ingredients please? I have found two options so far, but since I am very new to web development, I do not know if they could work: Create a separate model for ingredient and use a many-to-many relationship to connect the models but this would create a new object for every instance that for instance volume is different Just use TextField() and then use some crazy Regex to separate the ingredients out Given that I am new to web development, I have no clue what is the most suitable option. Thanks -
Django unit tests. Post data with duplicate keys
I'm writing a Django unit test against an app I inherited. In the context of a unit test I am doing something like: data = {'foo':'bar','color':'blue'} self.client.post(url,data=data) However, the app expects muiltiple form data for "color" in the same key in the HTTP request, such as: foo: bar color: orange color: blue What's the best and most pythonic way to handle this? Is there a django class I should be using that already covers this? I obviously can't create a python dict with duplicate keys, so I am not sure what I should use to get the above desired HTTP POST. I can't change the underlying app, I'm interfacing with something that already exists! -
Need an explination to why a Form with method post is not callin the action correctly with django url tag?
While trying to create a simple search form using method="POST" and action linking to a url that should trigger a view to render a different template I have come across it not working all it does is tag on the csrf to my index url and acts like I am using GET not POST any thoughts on why? View: @login_required(login_url='login_register') def search_site(request): if request.method == "POST": searched = request.POST['searched'] context = { 'searched': searched } return render(request, 'bugs/search_site.html', context) else: return render(request, 'bugs/search_site.html') URL: path('search_site/', views.search_site, name='search_site'), Search bar template: <div class="input-group"> <form method="POST" action="{% url 'search_site' %}"> {% csrf_token %} <input class="form-control" type="search" placeholder="Search for..." aria-label="Search for..." name="searched"> <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i></button> </form> </div> Search result template: {% extends 'bugs/base.html' %} {% block content %} <div class="container-fluid px-4"> {% if searched %} <h4 class="mt-4">results for {{ searched }}</h4> {% endif %} </div> {% endblock %} I have tried changing method to get, I have tried to change my url and my view to no avail. -
Django ManyToMany relationship on unioned queryset from different models
I'm unable to join ManyToMany relationship records using a serializer to a unioned queryset from different DB modals. I have two similar DB models, A and B both with a ManyToMany relationship with another model, Tag. from django.db import models class Tag(models.Model): name = models.CharField(max_length=100) class A(models.Model): name = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) class B(models.Model): name = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) I want to union A and B, and join the data from Tag via a Serializer. Here's my serializer: from rest_framework import serializers from union.models import A, B, Tag class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class ABUnionSerializer(serializers.Serializer): name = serializers.CharField() tags = TagSerializer(many=True) When I create a queryset that unions A and B, then pass that to ABUnionSerializer, the serializer does not join the Tag data from B correctly. Example: from django.test import TestCase from union.models import A, B, Tag from union.serializers import ABUnionSerializer class UnionTestCase(TestCase): def test_union(self): ta = Tag.objects.create(name='t-a') tb = Tag.objects.create(name='t-b') a = A.objects.create(name='aaa') a.tags.add(ta) b = B.objects.create(name='bbb') b.tags.add(tb) u = A.objects.all().union(B.objects.all()) s = ABUnionSerializer(u, many=True) print(s.data) The Serializer attempts to use relationship table from A instead of B. In this example, this causes the serialized record "bbb" to have tag "t-a" … -
How do I set(repeatedly) a Foreign Key Model, on multiple fields in another Model ? + Django
Trying to build a Model -> Trip, with multiple Hotel entries per region -> denoted by variables _pb, _hv, _nl. class Trip(models.Model): hotel_pb = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True) hotel_hv = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True) hotel_nl = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True) How do I achieve this without creating region specific Hotel models ? I have tried using the same Foreignkey, but throws error. -
Not able to configure any URLs in Django; going to localhost:8000 shows the congratulations page
As title - I've been going through the official tutorial (part 1) and have gotten to the point where we wire an index view into the URLConf. However, when I run python manage.py runserver I only see the "congratulations! the installation was successful!" page, not the HTTPResponse that's supposed to return. It says that I haven't configured urls, but there are like 3 steps to follow so far and I'm confused on how I managed to go wrong when copying some code into views.py and creating a urls.py file. Going to localhost:8000/polls gives me 404 not found error. I made sure to create urls.py within the "polls" directory (which in turn is within the project "mysite" directory); the `view.py My urls.py code is as follows: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path(' ', views.index, name='index'), path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] My views.py code is as follows: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") When I do python manage.py runserver, I'm inside the mysite directory (that contains the polls and mysite apps' directories). I'm really not sure where I might be going wrong; any …