Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to import file into django without abstract link, not using statics
My Django project need to show some pdf files in web page. Files are stored out of my project. I can get their abstract link, but when I try to import them into my project, it doesn't work. When I copy file to my statics folder and change code with static, it worked. But there is a plenty of files, I can't download all of them to statics folder in my project. What should I do? -
How to fix 500 error after deploying when DEBUG = False, ALLOWED_HOSTS=['*']
I am getting a 500 error when I run the server on digital ocean and have set DEBUG = False in Settings.py of my django app. I am running the Django server on port 8000, and have had the same issue when using gunicorn. No errors show up when DEBUG = True, and my ALLOWED_HOSTS = ['*']. I have a custom 404 template and handler. The error shows up on any page I attempt to load, except the Django admin page. Please let me know if you have any ideas!!! Exact error message: "GET /accounts/login/ HTTP/1.1" 500 27 settings.py file: import os from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '**********' MAILMAN_PASSWORD = "*********" DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'mysite', 'webapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] 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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dashboard_db', 'USER': 'dashboard_db_admin', 'PASSWORD': '**********', 'HOST': 'localhost', 'PORT': '', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': … -
Can't display another Highcharts chart on my HTML page
Been looking at Highcharts doc and also "Integrating Django and Highcharts" by simpleisbetterthancomplex. I'm not sure what went wrong with my codes, that the second charts ain't display. I'm using Django views.py to retrieve data from the database. <div class="carousel-inner"> <div class="carousel-item active"> <div class="border" id="container" style="min-width: 100px; height: 400px; margin: 0 auto;"></div> <script src="https://code.highcharts.com/highcharts.src.js"> </script> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> Highcharts.chart('container', {{ chart|safe }}); </script> </div> <div class="carousel-item"> <div class="border" id="container2" style="min-width: 100px; height: 400px; margin: 0 auto;"></div> <script src="https://code.highcharts.com/highcharts.src.js"> </script> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script> Highcharts.chart('container2', {{ chart2|safe }}); </script> </div> <div class="carousel-item"> <div class="carousel-caption" > <h3>Currently Unavailable</h3> </div> </div> </div> Expected two charts to be display on two different panel of the carousel -
How to display the formset in django with TemplateResponseMixin
I keep getting Method Not Allowed: /2/module/ message error when i try to access this page. How can I access the view from this custom class based views. forms.py from django import forms from django.forms.models import inlineformset_factory from core.models import ( Course, Module ) ModuleFormSet = inlineformset_factory(Course, Module, fields = [ 'title', 'description'], extra=2, can_delete=True) views.py class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'core/manage/module/formset.html' course = None def get_formset(self, data=None): return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course, id=pk, owner=request.user) return super(CourseModuleUpdateView, self).dispatch(request.pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course':self.course,'formset':formset}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST) if formset.is_valid(): formset.save() return render('core:manage_course_list') return self.render_to_response({'course': self.course,'formset': formset}) template.py {% extends "base.html" %} {% block title %} Edit "{{ course.title }}" {% endblock %} {% block content %} <h1>Edit ""{{ course.title }}"</h1> <div class="module"> <h2>Course modules</h2> <form action="" method="post"> {{ formset }} {{ formset.management_form }} {% csrf_token %} <input type="submit" class="button" value="Save modules"> </form> </div> {% endblock %} urls.py path('<int:pk>/module/', views.CourseModuleUpdateView.as_view(), name='course_module_update') I am not sure where the problem is coming from as I tried to use PDB to check on everything. Any assistance will be much appreciated. -
Element of my django forms.py is not defined?
I've got a problem with django with handling forms : I created a form with 2 fields, and I associated it to my view, but it tells me that my fields are undefined. Could you explain me please ? I created a form in my index.html : <form action="/addUser" method="post"> {% csrf_token %} <label> Name of the Employee : <input type="text" name="employeeName", id="employeeName"/> </label> <label> Email of the Employee : <input type="email" name="employeeEmail", id="employeeEmail" /> </label> <button class="btn btn-primary" type="submit">Add User</button> </form> Then I created in views.py def addUser(request): if request.method == 'POST': form = CreationUserForm(request.POST) newEmployee = Employee() newEmployee.name = form[employeeName] newEmployee.email = form[employeeEmail] newEmployee.save() return HttpResponseRedirect(reverse('app:home')) And then I created in forms.py class CreationUserForm(forms.Form): employeeName = forms.CharField(label='employeeName', max_length=254) employeeEmail = forms.CharField(label='employeeEmail', max_length=254) So I don't understand why I get this error : name 'employeeName' is not defined For my point of view it is... I tried with form.employeeName too, but it considered as a non existant attribute. Thank you for helping :) -
Vuetify v-data-table doesn't fully load data: blank rows
I am using example data of Vuetify 1.5.16 documentation: https://v15.vuetifyjs.com/en/components/data-tables The table is shown correctly and I can edit it using props. The only problem is that data is not fully loaded. There is exactly the same number of lines in table as there is objects in array. When I enabled prop "loading", it is all the time true. {% extends 'base.html' %} {% block title %}Page name{% endblock %} {% block custom_style %} <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@1.5/dist/vuetify.min.css" rel="stylesheet"> <!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui"> --> {% endblock %} {% block content %} <v-app id="app-name"> <template> <v-data-table dark loading no-data-text :headers="headers" :items="desserts" class="elevation-1"> <template v-slot:items="props"> <td> {{ props.item.name }}</td> <td class="text-xs-right">{{ props.item.calories }}</td> <td class="text-xs-right">{{ props.item.fat }}</td> <td class="text-xs-right">{{ props.item.carbs }}</td> <td class="text-xs-right">{{ props.item.protein }}</td> <td class="text-xs-right">{{ props.item.iron }}</td> </template> </v-data-table> </template> </div> </v-app> {% endblock %} {% block custom_js_back %} <!-- development version, includes helpful console warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@1.5/dist/vuetify.js"></script> <script> var vueData = new Vue({ delimiters: ["<%", "%>"], el: '#app-name', data: { // example data headers: [ { text: 'Dessert (100g serving)', align: 'left', sortable: false, value: 'name', }, { text: 'Calories', value: 'calories' }, { text: 'Fat (g)', value: 'fat' … -
In Django REST Framework, how to make SerializerMethodField work for html template?
I made a serializer that uses SerializerMethodField that grabs some foreign fields from models other than the base model defined in Meta class, because I would like these fields to be displayed on the html page. However, calling these foreign fields in html doesn't seem to work. The html (character_list.html): {% block content %} <table> {% for character in characters %} <tr> <td><b>{{ character.name }}</b></td> <!-- This can be correctly shown --> <td>{{ character.primary_description_title }}</td> <!-- The foreign field that doesn't show --> <td>{{ character.primary_description_content }}</td> <!-- The foreign field that doesn't show --> </tr> {% endfor %} </table> {% endblock %} urls.py (relevant part only): ... path('description_list/<int:character_id>/', views.CharacterDescriptionListView.as_view(), name='description_list'), ... views.py (relevant part only): # It has a hell bunch of hierarchy, # But tldr, the serializer it would take is CharacterSerializer in this case class NovelCharacterListView(CharacterViewMixin, CustomNovelListCreateView): template_name = 'polls/character_list.html' def get_filter_object(self): return get_object_or_404(Novel, id=self.kwargs['novel_id']) def get_queryset(self): novelObj = self.get_filter_object() return Character.objects.filter(novel=novelObj) # All the relevant superclasses class CharacterViewMixin(object): _model_class = Character _writable_serializer = CharacterSerializer _read_only_serializer = CharacterReadOnlySerializer _data_name_single = 'character' _data_name_plural = 'characters' class CustomNovelListCreateView(CustomNovelListMixin, generics.ListCreateAPIView): class Meta: abstract = True def get_filter_object(self): raise NotImplementedError('Class %s.get_filter_object is not implemented.' % self.__class__.__name__) # def get_serializer_class(self): # return self._writable_serializer … -
Can't get Django settings inside of my view
I'm trying to pull stripe settings from my cookiecutter base.py, and it's not working. I'm not sure if I have not set my view correctly, or what. I'm testing all of this locally, and I have installed stripe via pip and added it to my installed apps (not sure if I needed to do that) here is my urls.py for the payment view path("payment/", TemplateView.as_view(template_name="pages/Payment.html"), name="payment") And here is my views.py class PaymentView(TemplateView): template_name = 'Payment.html' def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context I've got the following in my base.py STRIPE_SECRET_KEY = 'sk_test_xxxx' STRIPE_PUBLISHABLE_KEY = 'pk_test_xxxxx' I feel my issue isn't that I have the keys in the wrong place. I may just have my view class not named correctly. Any help? Thanks! -
How can I send this variable from django view to html using ajax on key up?
I am making and app that send data in realtime to the user in the html and I want to update the paragraph tag every time the users releases a key. My HTML: <form method="POST"> {% csrf_token %} <p id="amount_word" class="amount_word" style="text-align:center">{{ amount_words }}</p> </form> My javascript ('texteditor' is a textarea that I have): $("#texteditor").keyup(function(event){ data = {'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()}; $.ajax({ type:'POST', url:'/write/', datatype: 'JSON', data: data, success: function(data) { console.log(data) // check out how data is structured $('.amount_word').contents()[0].textContent = data.amount_words } }) }) My python view: def write_view(request, *args, **kwargs): if request.is_ajax() and request.method == "POST": def send_text(): texteditor = request.POST['TextEntered'] amount_words = "Amount of words: " + texteditor print(amount_words) texteditor = request.POST.get('TextEntered') if texteditor == 'NoneType': print("NoneType here") else: send_text() return JsonResponse({'amount_words': amount_words}) return render(request, "write.html") else: return render(request, "write.html") The template is write.html, and the URL is /write -
Django tutorial error: "TypeError at /admin/ - 'set' object is not reversible"
I am going through an official Django tutorial called "Writing your first Django app" and am currently at part 2. Here is the URL: https://docs.djangoproject.com/en/2.2/intro/tutorial02/ When trying to access the admin panel at http://127.0.0.1:8000/admin/, as per the instructions, I receive the following error: Environment: Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 2.2.4 Python Version: 3.7.3 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback: File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner 213. if request.path == reverse('admin:logout', current_app=self.name): File "/usr/local/lib/python3.7/site-packages/django/urls/base.py" in reverse 58. app_list = resolver.app_dict[ns] File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py" in app_dict 512. self._populate() File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py" in _populate 463. url_pattern._populate() File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py" in _populate 446. for url_pattern in reversed(self.url_patterns): Exception Type: TypeError at /admin/ Exception Value: 'set' object is not reversible I am on a Mac with Python 3 installed. I looked up all other similar questions for this … -
How to change text of dropdown button after selecting dropdown item?
I'm having some trouble to getting my javascript to work, I was wondering if anyone could give me some guidance on where I can put the javascript code directly in my html file. Is this the correct way of doing it? This is how it looks right now on my screen. Thank you!! -
How do I retrieve a field from a Many-To-Many table?
I need to retrieve a value from a Many-To-Many query. Let's say I have 3 models: Toy, Part, and ToyParts ToyParts has a field called "part_no". I need to be able to get the value of this. class Toy(models.Model): parts = models.ManyToManyField(Part, through="ToyParts") class Part(models.Model): pass class ToyParts(model.Model): toy = models.ForeignKey(Toy, ...) part = models.ForeignKey(Part, ...) part_no = models.CharField(...) I've tried using: Toy.parts.all().first().part_no which obviously doesn't work as Part does not have a field called "part_no" I've also tried just simply using: ToyParts.objects.filter(toy=...,part=...) but that adds additional queries. How would I be able to get part_no without querying ToyParts directly? -
Django ModelFormSet clicking "Submit" saves form but does not update to database
Background: I'm building a personal dictionary web-application, and have a queryset of terms and definitions. In my web app, I have an edit page, where I want to show a ModelFormSet that allows the user to edit any/all entries, and delete them if needed - the form has a delete button for each row and a submit button to save changes to the form. The current issue is that when I click on a set to edit, the formset shows up correctly, and when I change a term and hit "Submit" the form updates to show the change. However, when I go back to my "View Set" page, the term hasn't been updated, which I assume means the change didn't go through to the actual database - the form itself was simply submitted. This is what I would like to currently fix, and I also want to make it so that the delete button deletes the entry. What I've Tried: I've gone through every StackOverflow question I could find relating to the topic, and various solutions were: add an instance parameter when passing in "request.POST", re-initialize the formset after saving, change the "action" url in the HTML page, etc., but … -
I need my Django get_absolute_url to do two different things
So I have a small issue with one of my models when I want to fire get_absolute_url. When someone create's an article on my site I would like it to return them to the 'under-review' page to tell them that there page is currently under review. But the issue is that my sitemap is showing that every article comes up as www.example.com/under-review/ instead of www.example.com/post/example-slug I would normally use return reverse('post-detail', kwargs={'slug': self.slug}) for that which fixes the problem. But then brings up the issue that when someone creates the article, it takes them straight to the page instead of the under-review page. Model: def get_absolute_url(self): # return reverse('post-detail', kwargs={'slug': self.slug}) return reverse('under-review') Ideally I would have it so when someone posts a post, it takes them to the under-review page up at the same time serves the return reverse('post-detail', kwargs={'slug': self.slug}) so it shows up correctly in my sitemap. Thanks. -
django url pattern problem 'NoReverseMatch'
I have 'url(r'^topics/(?P\d+)/$', views.topic, name='topic')' in urls.py but when I try to go to localhost:8000/topics/1 it tells me that it tried one pattern: 'topics/(?P\d+)/$' I would think it would be '*topics/(?P***d+)/$' I'm using a book called The Python Crash Course (1st edition)(ch. 18). This is a local server using Django 1.11 with Python. I've tried a lot of reformatting on the url pattern but I am new at this so I don't know what else to do. ... urlpatterns = [ url(r'^$', views.index, name='index'), # Show all topics. url(r'^topics/$', views.topics, name='topics'), # Detail page for a single topic. url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'), ] I expected it to pop up with the correct page but it always says 'NoReverseMatch at /topics/01/' -
django-rest-framework, passing a foreign key field as url parameter for lookup
I am trying to search for all serial numbers with a specific sales_order(foreign key) field by providing the sales order as a url parameter to its viewset. I'm not sure why my queryset isn't being displayed by a GET request This is a new system I am developing, and as a django newbie I am having some trouble getting everything working the way I'd like it too. Currently, I have configured my routes so that 127.0.0.1:8000/api/serialWSales/ just displays all serial numbers, and I want to have 127.0.0.1:8000/api/serialWSales/(<sales_order>)/ to display only the serial numbers with the sales order number given. I was able to get and print the desired queryset based on the sales_order key, but am having difficulty displaying the queryset with a GET request. I am unsure why the queryset isn't being displayed and the "display: Not Found" exception is being given. Relevant models # Model for Sales table class Sale(models.Model): sales_order = models.CharField(max_length=70, blank=False) model = models.ForeignKey(Model, null=True, on_delete=models.SET_NULL, related_name='sales') quantity = models.IntegerField(blank=False, default=1) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, related_name='sales') sale_id = models.IntegerField(default=1, unique=True, primary_key=True) class Meta: unique_together = [['sales_order', 'model']] verbose_name = 'Sale' verbose_name_plural = 'Sales' db_table = 'tbl_sales' def __str__(self): return self.sales_order def save(self, *args, **kwargs): … -
Save everything for new object except ManyToMany field in Django
I want to save object with ManyToMany relation. When I submit the form, all things save except field that have ManyToMany relation. These are my files: #Forms.py class ExamForm(ModelForm): class Meta: model = Exam fields = '__all__' #Models.py class Exam(models.Model): questions = models.ManyToManyField(Question) title = models.CharField(max_length=250) class Question(models.Model): title = models.CharField(max_length=250) answer = models.TextField(null=True, blank=True) #Views.py def add_exam(request): if request.method == "POST": form = ExamForm(request.POST) if form.is_valid(): new_exam = form.save(commit=False) new_exam.save() return redirect('view_exam') else: form = ExamForm() template = 'add_exam.html' context = {'form': form} return render(request, template, context) What is wrong with these codes? -
Django DateTime serializing
im getting a strange serialized representation of my DateTimeField, at the ending of the representation I get a "-05:00" on the JSON. Inside my model the field is defined as: ultima_actualizacion = models.DateTimeField(auto_now=True) And in the serializer I got it inside the Meta Class: class Meta: fields = ( ... 'ultima_actualizacion', ... ) But when I make a request in the response JSON I get something like: { ... "ultima_actualizacion": "2019-08-07T15:34:22.692530-05:00" } Which seems odd because I haven't changed the format and still get that "-05:00" in every ultima_actualizacion I have looked and tried changing the format and input formats as specified in: Django Rest Framework Fields and in this other answer but still get the "-05:00" -
Monitoring django connections
I'm trying to investigate how well my application is utilising pooled django connections to a mysql database. From mysql, I am able to see the connections and their state, but it appears that the vast majority (often over 99%) of the connections are generally in an idle state. I have been able to monitor the queries made from the django application by following the advice in this post: https://stackoverflow.com/a/24876751/8196202. I am now looking to monitor the connections in a similar way -- i.e. detect when a new connection is created, how long the connection is kept open, and how much of the connection's life is spent in an idle vs active state. I'm wondering if anyone has some tips or suggestions on how to go about gathering this information? My goal is to use the information gathered to try and decide on reasonable values to use for CONN_MAX_AGE, etc. -
Django, When to use multiple template loaders
This is a standard practice question So I have a Django app that contains the standard loader that loads all my web templates from the assets/template folder along with most expected context processors. My app also sends out e-mails in txt and html formats for which I use a different loader. The loaders are set up as follows: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'assets/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' ], }, }, { 'NAME': 'EmailTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'assets/mails')], 'APP_DIRS': True, }, ] When rendering the mails I use get_template(..., using='EmailTemplates') and it works fine. However, my partner argues that the differences between the loaders are minimal and that it's better to make it just one loader and placeassets/mailstoassets/templates/mails`. As Django was build to support multiple template loaders (as evident by the parameters using in the many key template methods, I was wondering: When is it useful to implement multiple template loaders on a site and when should it be avoided? -
Django how to extend generic View class
I noticed that I am setting site-wide context variables and request variables for many views on my site. Naturally, this situation calls for inheritance. If all of my view class-based views are inheriting from SiteView instead of the generic View, I can factor out all the commonalities into the SiteView child class. I can then inherit from SiteView on all my views. But, I cannot get this to work. Here is my code: from django.contrib.auth.decorators import login_required from django.views.generic import View from django.utils.decorators import method_decorator class SiteView(View): ''' Extends the generic django-supplied View class ''' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(SiteView, self).dispatch(*args, **kwargs) def get(self, *args, **kwargs): ''' Adds the variables required in the get request ''' context = super(SiteView, self).get(*args, **kwargs) context['common_var'] = 'some common value' context['user'] = request.user return self.render_to_response(context) This throws the following TypeError: dispatch() missing 1 required positional argument: 'request' Any help would be appreciated -
Defining views and urls in Django. Why aren't parenthesis used to call the function?
I have been going through "Python Crash Course", and I'm working on the "Django Web Application project (Learning Log)" stage. There is something that contradicts what I have already learned... """views.py file""" from django.shortcuts import render def index(request): """The home page for Learning Log.""" return render(request, "learning_logs/index.html") """urls.py file""" from django.urls import path from . import views app_name = "learning_logs" urlpatterns = [ # Home page path("", views.index, name="index") ] In the code above, in "urls.py" file, views.index is called but without parentheses. Why is that? Also, the index function has "(request)" parameter, but the argument is never provided. Am I missing something? Note that this code works fine. -
How can a Ajax/jQuery script show three dependent form dropdown box entries all within one form url?
I am developing a simple form prototype that contains 4 entries in PythonAnywhere (Python 3.7 + Django): PinID (Independent, simple manual number entry) Region (Independent Dropdown Box) Name (Region-Dependent Dropdown Box) Source (Name-Dependent Dropdown Box) What shows up in the Name box is dependent on the Region box, and what shows up in the Source box is dependent on the Name box. So ultimately, the Source Box is dependent on the Region box (If A, then B. If B, then C. So C is dependent on A). To note, if the Region or Name box is blank, their respective dependents are blank. As my current code is written (which is likely wrong), I can only get my Name box to autopopulate correctly. The Source box remains blank, but it does indeed autopopulate correctly after I refresh the page. However, I intend to keep the form all in one url. I refer to two other .html files to "insert" themselves into the form's .html file without refreshing the page. In the jQuery script, I put the identical segment of code for the second dependent dropdown box under the success function of the first dependent dropdown box, which might be my issue. … -
Images as static files in Django (development)
I'm having trouble displaying an image in my home.html template in development. In settings.py, I have this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # for production STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static-assets'), # for development ) The relevant part of the file structure is this: pred_market_pg [base directory] staticfiles [empty] static-assets mp_logo_dark.jpg templates home.html [further templates] markets [all the usual app files] static css markets.css users [all the usual app files, no static folder] In home.html, I then have {% load static %} on top, and further down <img src="{% static 'mp_logo_dark.jpg' %}"/>. I have DEBUG = True and have included django.core.staticfiles in my INSTALLED_APPS in settings.py. Where am I going wrong? -
Django query_params array type instead of string
I have an ApiView that supports get requests: class BookApiView(APIView): def get(self, request): search_criteria = request.query_params When I send a GET request to this end point: http://0.0.0.0:3000/api/book/?q=the+lord+of+the+rings The request.query_params is: <QueryDict: {'q': ['the lord of the rings'], 'page': ['2']}> Instead of being: <QueryDict: {'q': 'the lord of the rings', 'page': '2'}> How can I stop the value from becoming a list or my only option is to parse the value and convert it back to a string?