Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why does webpack loader on django and vuejs shows TypeError when using render bundle?
Im trying to work with Django and vuejs using the webpack loader, however I'm running into this template error, Here is the full traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.6 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpack_loader', 'topics'] 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'] Template error: In template /home/grollier/Projects/Python/bethel/bethel_site/templates/index.html, error at line 21 **string indices must be integers** 11 : <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons"> 12 : </head> 13 : <body> 14 : <noscript> 15 : <Strong>We're sorry but frontend doesn't work properly without JavaScript enable. Please enable it to continue.</Strong> 16 : </noscript> 17 : <div id="app"> 18 : <app></app> 19 : </div> 20 : 21 : {% render_bundle 'app' %} 22 : 23 : <!-- built files will be auto injected --> 24 : </body> 25 : </html> Traceback (most recent call last): File "/home/grollier/anaconda3/envs/bethel/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/grollier/anaconda3/envs/bethel/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/grollier/anaconda3/envs/bethel/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/grollier/anaconda3/envs/bethel/lib/python3.7/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/home/grollier/anaconda3/envs/bethel/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/home/grollier/anaconda3/envs/bethel/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File … -
In Django, How to change only specific parameters on url in template using GET form?
<div class="md-form my-0"> <form action="{% url 'core:home' %}" method="GET" > <input name="priceMin" type="number" class="form-control mr-sm-2" placeholder="Min" aria-label = "Search"> </form> </div> I want to change only one parameter from my url. For example, if my current url looks like "home/?category=KN&priceMin=50", after form i want to get "home/?category=KN&priceMin=30" but i got "home/?priceMin=30". My other variables are erased, i want only 1 parameter to change, what should i do ? (My Url is suitable for that format so dont mind changing it) -
Using 'requests' library in Python Django 3.0.6
I am trying to get some data using Django forms, the data is actually an URL, like this: def sample(request): if request.method == 'POST': form = sampleForm(request.POST) if form.is_valid(): RDS = form.cleaned_data['RDS'] print(RDS) form = sampleForm() return render(request, 'form.html', {'form': form}) the url is in RDS variable. Now i want to use this url to make a GET request using Requests library of Python. I tried adding these lines after the above code: node_data = requests.get print(node_data.content) But it doesn't seem to work. Can anyone help? -
Cant access pagination methods inside template
I have some search results that are returned from database queries that I would like to paginate. From what I can tell, the pagination is working. The results are displayed with the correct number per page and I can add ?page=2 to the url and see the second page of results. My problem is that my template cant access pagination methods, for instance {{ result.previous_page_number }} or {{ result.next_page_number }}. I can however access these in my pagination method in my search view. here is my view def search(request): is_search = False def search(search_term): search_result = [] search_vector = SearchVector('name', 'practitioner__first_name', 'description', 'street', 'city') qs = Clinic.objects.annotate(search=search_vector).filter( search=search_term).values() if qs: for i in qs: search_result.append( Clinic.objects.get(practitioner=i['practitioner_id']). get_clinic_details()) mods_vector = SearchVector('mods__name') mqs = Profile.objects.annotate(search=mods_vector).filter( search=search_term).values() if mqs: for i in mqs: search_result.append( Clinic.objects.get( practitioner=i['user_id']).get_clinic_details()) print(search_result) seen_names = set() set_results = [] for obj in search_result: if obj['is_searchable']: if obj['name'] not in seen_names: set_results.append(obj) seen_names.add(obj['name']) return (set_results) coords = [] def paginate(search_term): search_result_list = search(search_term) for i in search_result_list: coords.append({ "lat": i['lat'], "lng": i['lng'], "url": f"clinic/{i['id']}", "name": i['name'] }) page = request.GET.get('page', 1) paginator = Paginator(search_result_list, 6) try: results = paginator.page(page) print(results.has_other_pages()) # returns correct result print(results.number) # returns correct result except … -
fullcalendar/django refetchEvents() not works or can not uderstand how it works
I have a django application with this model.py: from __future__ import unicode_literals from django.db import models class Events(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100,null=True,blank=True) start = models.DateTimeField(null=True,blank=True) end = models.DateTimeField(null=True,blank=True) def __str__(self): return self.name this view.py: from django.shortcuts import render from django.http import JsonResponse from mycalendars.models import Events def calendar(request): all_events = Events.objects.all() context = { "events":all_events, } return render(request,'calendar.html',context) def add_event(request): start = request.GET.get("start", None) end = request.GET.get("end", None) title = request.GET.get("title", None) event = Events(title=str(title), start=start, end=end) event.save() data = {} return JsonResponse(data) def remove(request): id = request.GET.get("id", None) event = Events.objects.get(id=id) event.delete() data = {} return JsonResponse(data) this urls.py: from django.conf.urls import url from django.contrib import admin from mycalendars import views urlpatterns = [ url('^calendar', views.calendar, name='calendar'), url('^add_event$', views.add_event, name='add_event'), url('^remove', views.remove, name='remove'), ] in templates I have the calendar.html with all the full calendar like this: <html><head> <link href='https://unpkg.com/@fullcalendar/core@4.4.0/main.min.css' rel='stylesheet' /> <link href='https://unpkg.com/@fullcalendar/daygrid@4.4.0/main.min.css' rel='stylesheet' /> <link href='https://unpkg.com/@fullcalendar/timegrid@4.4.0/main.min.css' rel='stylesheet' /> <script src='https://unpkg.com/@fullcalendar/core@4.4.0/main.min.js'></script> <script src='https://unpkg.com/@fullcalendar/interaction@4.4.0/main.min.js'></script> <script src='https://unpkg.com/@fullcalendar/daygrid@4.4.0/main.min.js'></script> <script src='https://unpkg.com/@fullcalendar/timegrid@4.4.0/main.min.js'></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <script> document.addEventListener('DOMContentLoaded', function() { var Calendar = FullCalendar.Calendar; var Draggable = FullCalendarInteraction.Draggable; var containerEl = document.getElementById('external-events'); var calendarEl = document.getElementById('calendar'); new Draggable(containerEl, { itemSelector: '.fc-event', eventData: function(eventEl) { return { title: eventEl.innerText, duration: '24:00', }; … -
How to Embed PDF in browser in Django instead of downloading it?
i'm new to this. my problem is that the browser downloads the pdf instead displaying. i tried some solutions in this site but none of them work fine for me eg:- -Display a pdf in object/embed django help me to fix this i use this code in my html file and nothing else. {% load static %} <body> <object data="test.pdf" type="application/pdf" title="SamplePdf" width="500" height="720"> <embed src="{% static 'test.pdf' %}" > </object> </body> please help me to fix this. -
Please tell me how to correctly receive and output comments on the event
I try to get and output comments that people will leave under a certain event, but I have encountered difficulty. I think the error is in the urls file since Traceback describes the error in add_review. If anyone knows how to solve this situation, help me. Here I fit the error code and source code Error: Internal Server Error: /event/event1/ Traceback (most recent call last): File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\dadi2\Desktop\church\website\views.py", line 26, in get return render(request, "event/event-detail.html", {"events": events}) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\template\base.py", line 163, … -
Passing a query into Django test
I want to test a view of my Django application. def search(request): query = request.GET.get('query') query_lower = query.lower() list_name = re.split("[- ’? ; , ' . : ' ' " " ]",query_lower) stripped_query = [strip_accents(x) for x in list_name] clean_query =[word for word in stripped_query if word not in stopwords] match_list = [] for x in Product.objects.all(): match = 0 for y in clean_query: if y in x.name or y in x.brand: match += 1 if match == len(clean_query): match_list.append(x.id) else: pass if not query: products_list= Product.objects.all() else: products_list = Product.objects.filter(id__in=match_list) context = { 'products': products_list, } return render(request, 'finder/search.html', context) I did create some products in my tests.py with setup and I want to test if I have a 200 status code if on of those products is searched: def test_Search(self): self.response = self.client.post(reverse(('finder:search'), {'query':'gazpacho'})) self.assertEqual(self.response.status_code, 200) I got a TypeError: unhashable type: 'dict'. So, how I am supposed to pass my query into my test for it to be run? -
How to increase performance of Django-React app
I'm developing Django-React (REST API) app which has multiple databases (MySQL). The biggest issue there is when I have to GET some data. For some tables to be shown on the frontend I need more than one minute. I connected frontend and backend via REST API and I'm using Axios as well to GET my data shown on the frontend. Not sure where actually problem is and what should I improve. Need assistance in troubleshooting this... -
DJango query omtimization for foreign key
class MainCategory(models.Model): main_category_id = models.PositiveSmallIntegerField(primary_key=True) name = models.CharField(max_length=30) image = models.URLField(null=True) class Meta: db_table = 'lookup_main_category' def __str__(self): return self.name class SubCategory(models.Model): sub_category_id = models.PositiveSmallIntegerField(primary_key=True) main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) image = models.URLField(null=True) class Meta: db_table = 'lookup_sub_category' def __str__(self): return self.name I have the above 2 models in my DJango REST framework project and I need an API output as below. What will be the optimum query without having typical for loop to get distinct main categories and then loop through it in the sub_category table? [ { "main_category_id": "10", "main_category_name": "main_name1", "image": "http://example/com1", "sub_categories": [ { "sub_category_id": "20", "sub_category_name": "sub_name1", "image": "http://example/com1" }, { "sub_category_id": "21", "sub_category_name": "sub_name2", "image": "http://example/com" } ] }, { "main_category_id": "11", "main_category_name": "main_name2", "image": "http://example/com2", "sub_categories": [ { "sub_category_id": "22", "sub_category_name": "sub_name2", "image": "http://example/com2" } ] } ] -
I'm getting an operational error in django administration in access records only
click on this link to Operational error What changes should I do to remove this error This is the code i wrote in models.py file from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage, on_delete=models.CASCADE) data = models.DateField() def __str__(self): return str(self.data) -
How to make every td elements link to a view using django?
I am building a toy project, building a calendar by django. when each day is clicked, I want to move into a form adding event. To build the calendar itself I used HTMLCalendar(), with some CSS. What would be smartest way to hyperlink each day(td element) to another form? This is my view code: def calbuilder(request): year = int(request.POST.get('year',None)) month = int(request.POST.get('month',None)) cal = HTMLCalendar(calendar.SUNDAY) cal = cal.formatmonth(year, month) cal = cal.replace('<td ', '<td width="150" height="150"') cal = cal.replace('border="0" cellpadding="0" cellspacing="0" class="month">','class="table">') context = { 'calendar':cal } return HttpResponse(json.dumps(context), content_type="application/json") def index(request, year=timezone.localtime().year, month=timezone.localtime().month): cal = HTMLCalendar(calendar.SUNDAY) cal = cal.formatmonth(year, month) cal = cal.replace('<td ', '<td width="150" height="150"') cal = cal.replace('border="0" cellpadding="0" cellspacing="0" class="month">','class="table">') return render(request, 'cencal/index.html', {'calendar': cal}) def makeevent(request, pk): pass And template code(Actually, I can't sure this would help): {% extends "cencal/base.html" %} {% block content %} <input type="button" id="prev" value="Prev" class="movemonth"> <input type="button" id="next" value="Next" class="movemonth"> <p id="calendar"> {{ calendar | safe }} </p> <script type="text/javascript"> function getMonthFromString(mon){ let d = Date.parse(mon + "1, 2020"); if(!isNaN(d)){ return new Date(d).getMonth() + 1; } return -1; } //접속하자마자 ajax로 현재 년/월로 calendar 업뎃. 이러면 별도의 index뷰를 안 만들어도 되지 않을까? var ajaxf = function(){ var year = 0; … -
How To Provide OR Search for Filters Introduced by User
How To Provide OR Search for Filters Introduced by User def teachers_list(request): qs = Teacher.objects.all() if request.GET.get('fname'): qs = qs.filter(first_name=request.GET.get('fname')) if request.GET.get('lname'): qs = qs.filter(last_name=request.GET.get('lname')) if request.GET.get('email'): qs = qs.filter(email=request.GET.get('email')) result = '<br>'.join( str(teacher) for teacher in qs ) # return HttpResponse(result) return render( request=request, template_name='teachers_list.html', context={'teachers_list': result} -
error in urls.py of root directory while adding search option to django project
hi iam new to python and doing my first project and while i tried to add search option in my project i came up with the following error: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_n ame attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. my urls.py of project is: """simplesocial URL Configuration The urlpatterns list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from . import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('', views.HomePage.as_view(), name="home"), path('admin/', admin.site.urls), path('test/', views.TestPage.as_view(), name="test"), path('thanks/', views.ThanksPage.as_view(), name="thanks"), path('accounts/', include("accounts.urls", namespace="accounts")), path('accounts/', include("django.contrib.auth.urls")), path('posts/', include("posts.urls", namespace="posts")), path('groups/',include("groups.urls", namespace="groups")), path('search/', include("search.urls", namespace="search")), path('search/', include("django.contrib.urls")), ] if settings.DEBUG: urlpatterns= urlpatterns + … -
Django admin autocomplete_fields not working if no module_permission
autocomplete_fields in admin are showing no results if a user has not module permission in the related model, althought it had view or change permission. Since the purpose of module permission is not to show the model in index, but still being able to view/edit it, this could be a bug, or it is required other configuration?. If not using autocomplete_fields, the same related models without module permission are showing, as it is expected. Thank you -
Showing one to many related objects in Django admin object list
Normally, Django admin follows the url convention of "app-name/modelname" to show the list display. Can I achieve something like "app-name/modelname//items" to show the many to one related "Items" list of that "modelname"? I know something like this can be usable "app-name/items/?item__id__exact=1", but I want to show the filtered items only associated to a specific model. Also I know that, the whole scenario can be achieved by custom url's, but I'm having hard time implementing the admin features on custom views. Any suggestions/snippets/links would be much appreciated. Thanks in advance. -
ValueError: Field 'id' expected a number but got 'Whisper'
Here is my models.py class RUDevice(models.Model): name = models.CharField(_("Device Name"), max_length=100, blank=False, null=False, help_text="Device Name", default='') last_active = models.DateTimeField(_("Last Active"), auto_now=False, auto_now_add=False, class Magazine(models.Model): device = models.ForeignKey(RUDevice, on_delete=models.CASCADE, null=False, blank=False, related_name='ru_magazine' ) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=False, blank=False, related_name='magazine_product_type') class MagazineProduct(models.Model): magazine = models.ForeignKey(Magazine, on_delete=models.CASCADE, null=False, blank=False, related_name='magazine_product', help_text="Select magazine for product") class ProductType(models.Model): brand = models.ForeignKey(ProductCompany, on_delete=models.CASCADE, null=False, blank=False, related_name='company', help_text="Select company name") size = models.ForeignKey(ProductSize, on_delete=models.CASCADE, null=False, blank=False, related_name='type_class', help_text="Select product class") class Product(models.Model): sku = models.CharField(_("SKU"), max_length=100, blank=True, unique=True,help_text="Store ID") product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=False, blank=False, related_name='product_type', help_text="Select product type") count= models.PositiveIntegerField(default=0) class SingleProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='product', help_text="Select product") I am trying to filter rudevices with specific brand. it will return all the rurudevices that's magazine has this brand. my first approach was this. for i in RUDevice.objects.all(): mg = Magazine.objects.filter(device=i) then filter all MagazineProduct with all the returned mg. MagazineProduct.objects.filter(magazine__in=mg, magazine__product_type__brand="Whisper") if i can filter magazineProduct then i can get rudevices . But i am getting ValueError: Field 'id' expected a number but got 'Whisper'. and is my apporach ok? -
How to continue executing celery queue after stopping Redis and then starting it later?
I am running a Django application that runs asynchronous tasks using Celery and using a Redis server as a worker. I need to be able to stop the entire infrastructure and bring it back up without causing a break in the execution of tasks. So I need to do this: 1) Stop the Django webservice 2) Stop celery 3) Shut down Redis daemon 4) Make a few changes in the server or move to a different machine 5) Start Redis daemon 6) Start Celery 7) Start the Django webservice When the entire infrastructure is back up again it should continue where it left off. i.e. if there were any tasks in the queue it should continue executing them. How do I go about doing this? Is there a way to save the queue and continue later? -
Django Custom model method with parameters, NON DRY
After much research and trouble i came up with a non DRY solution, Hope someone can make it DRY. All im trying to get is a calculated Price which takes a parameter and displays in the template accordingly. MODELS.PY class VehicleCategory(models.Model): CATEGORY_CHOICES=( ('E-Cycle', 'E-Cycle'), ('E-Scooter', 'E-Scooter') ) main_category = models.CharField(max_length=15, choices= CATEGORY_CHOICES) title = models.CharField(unique=True, max_length=200) image = models.ImageField( null=True, blank=True, width_field="width_field", height_field= "height_field", default= 'e-bike.png', upload_to='category') width_field = models.IntegerField(default=250) height_field = models.IntegerField(default=250) slug =models.SlugField(max_length=200, db_index=True, unique=True) def __str__(self): return self.title def get_price(self, duration): for item in VehiclePrice.objects.all(): if item.vehicle_category.title == self.title and (duration >= item.slab.start and duration <= item.slab.end): return item.total_price class Meta(): verbose_name = "Vehicle Category" verbose_name_plural = "Vehicle Categories" class PriceSlab(models.Model): start = models.IntegerField() end = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s ' % (self.start, self.end) class VehiclePrice(CustomerStatus): help_text= "Ensure no more than 2 digits after decimal" vehicle_category = models.ForeignKey(VehicleCategory, on_delete= models.SET_NULL, null=True, related_name='vehicle_category_price') slab = models.ForeignKey(PriceSlab, on_delete=models.CASCADE) net_price = models.DecimalField(help_text= help_text, max_digits=5, decimal_places=2) tax_percent = models.DecimalField(help_text=help_text, max_digits=4, decimal_places=2, default=18.00) discount_percent = models.DecimalField(help_text=help_text,max_digits=4, decimal_places=2, default=0, blank=True) @property def total_tax(self): tax = (self.net_price * self.tax_percent)/100 return tax @property def get_price(self): total = self.net_price + self.total_tax return total @property def total_discount(self): discount = (self.get_price * … -
Django filesystem/file-based cache failing to write data 5-10% of the time
We are doing background data processing with Django Celery, taking a large CSV file (up to 15MB), converting it into list of dict data (which also includes some Django objects), and breaking it up into chunks to process as individual tasks: @task def main_task(data): i=0 for chunk in chunk_up(data): chunk_id = "chunk_id_{}".format(i) cache.set(chunk_id, chunk, timeout=FIVE_HOURS) sub_task.delay(chunk_id) i += 1 @task def sub_task(chunk_id): data_chunk = cache.get(chunk_id) ... # do processing main_task runs in concurrent processes in the background managed by Celery. We originally used Redis backend but found it would routinely run out of memory during peak load scenarios and high concurrency. So we switched to Django's filebased cache backend. Although that fixed the memory issue, we saw that 20-30% of the cache entries never got written. No error thrown, just silent failure. When we go back and look up the cache from CLI, we see that for e.g. chunk_id_7 and chunk_id_9 would exist, but chunk_id_8 would not. So intermittently, some cache entries are failing to get saved. We swapped in diskcache backend and are observing the same thing, though cache failures seem to be reduced to 5-10% (very rough estimate). We noticed that in past there where concurrent process issues … -
Include Example Value of body instead of parameters, Django swagger?
Is there any way to include example value/schema to a django-rest-framework for functions/api_view Example: https://generator3.swagger.io/index.html Expected outcome -
Preventing a user from submitting a form with empty field
I am a beginner in Django expanding upon their polling app tutorial by making dynamic form sets. I have a page where users can write a question and then dynamically add/remove any number of choices they want using the django-dynamic-formset plugin. So far, if the user tries to post without inputting any question they will get an error message like so: However, if the user fills in question field with no choices filled, the poll will submit. How do I prevent this so the user must be required to fill out at least one choice field? I used inlineformset_factory for both my Poll model and Choice model. According to Django docs, each model field's "blank" attribute should be set to False as default so I'm not sure why this is occurring. I also added in my own comments, please feel free to correct me if they are wrong. forms.py class ChoiceForm(ModelForm): class Meta: model = Choice exclude = () ChoiceFormset = inlineformset_factory(Poll, Choice, form=ChoiceForm, fields=['choice_text'], extra=2 ) Here is my CreateView class: views.py class PollCreateView(LoginRequiredMixin, CreateView): # form to create new poll model = Poll # automatically generates Poll form fields = ['question_text'] template_name = 'polls/poll_form.html' success_url = '/' def … -
How to achieve dependent foreign keys listing in django-admin?
Suppose I have 3 models:- Address, Country, State Address Model: class AddressModel(BaseModel): country = models.ForeignKey(CountryModel, null=True, blank=True, on_delete=models.PROTECT) state = models.ForeignKey(StateModel, null=True, blank=True, on_delete=models.PROTECT) city = models.CharField(max_length=200, null=True, blank=True) pincode = models.CharField(max_length=6, null=True, blank=True) address_line_1 = models.TextField(max_length=200, null=True, blank=True) address_line_2 = models.TextField(max_length=200, null=True, blank=True) Country Model: class CountryModel(BaseModel): name = models.CharField(max_length=100) code = models.CharField(max_length=30) and State Model: class StateModel(BaseModel): country = models.ForeignKey(CountryModel, on_delete=models.PROTECT) name = models.CharField(max_length=100) code = models.CharField(max_length=30) While adding a new address in django admin, I want to show the list of only those states which belong to the selected country i.e I want to implement something like dependent foreign key list in django-admin. I would like to achieve it without using jquery or ajax How can I do that? -
unable to send messages to slack from my django app using python-slackclient
I am having an django app https://satyalakshmi.pythonanywhere.com/modsy/login/ this is the url now My requirement every user logins to my app should be able to message to the slack user after logging there should be an chat tab and in that there should be slack users list of the previously logged users shown and the user logged in should be able to post a message to the user in the list Is this requirement possible? On searching about this I found an plugin https://github.com/slackapi/python-slackclient as said in this I had kept this code in views.py from slack import WebClient from slack.errors import SlackApiError slack_token = os.environ.get("SLACK_BOT_TOKEN") client = WebClient(token=slack_token) try: response = client.chat_postMessage( channel="C0XXXXXX", text="Hello from your app! :tada:" ) except SlackApiError as e: # You will get a SlackApiError if "ok" is False assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' When I run this I am not getting any errors and even not posting the message can anyone summarize how to use this in my django app to achieve my requirement please -
Is there anyway to send continous HttpResponse from Django instead of once?
I'm working on django based project. And I don't have much deep knowledge about django framework. I want to send Httpresponse from views.py continuously. So instead of using return Httpresponse("") which ends the function, I want to send continuous response.