Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'str' object has no attribute 'model'
@staff_member_required @never_cache def departures(request, fields=None): qs = Booking.objects.filter(status="PURCHASED").order_by=('departure_date') model = qs.model response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % slugify(model.__name__) writer = csv.writer(response) # Write headers to CSV file if fields: headers = fields else: headers = [] for field in model._meta.fields: headers.append(field.name) writer.writerow(headers) # Write data to CSV file for obj in qs: row = [] for field in headers: if field in headers: val = getattr(obj, field) if callable(val): val = val() row.append(val) writer.writerow(row) return response line model = qs.model throws the error 'str' object has no attribute 'model' but I have other functions that have the same/similar code that does not throw an error like if form.cleaned_data.has_key('departure_date') and form.cleaned_data['departure_date'] != '' and form.cleaned_data['departure_date'] != None: qs=Booking.objects.filter(departure_date__travel_date__exact=form.cleaned_data['departure_date']).filter(status="PURCHASED") model = qs.model So I am surprised that an error is being thrown, any ideas please -
Django serializer for .count()
I'm trying to make server-side pagination and for this i've need object's count. So the problem is that i get error when trying to get this value because of serializer ('int' object is not iterable) i dont khow how to create serializer that returns this value. Below is the usual serializer for the model and of course it doesn't work properly. views.py class CountItem(ListAPIView): queryset = Item.objects.count() serializer_class = ItemSerializer Serializer.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' -
Django og graph tags issue
<meta property="og:url" content="{% block ogurl %}{% url 'post:Homepage' %}{% endblock %}" /> <meta property="og:image" content="{% block ogimage %}{% static 'img/brand/logo.png' %}{% endblock %}" /> Result; <meta property="og:url" content="/" /> <meta property="og:image" content="/static/img/brand/logo.png" /> What I want; <meta property="og:url" content="sitename.com" /> <meta property="og:image" content="sitename.com/static/img/brand/logo.png" /> Where i did mistake, can you help me -
How to change the class of a H element in Wagtail Draftail Editor
I would like to add custom classes to H1, H2, H3, etc. in the Draftail editor. I was looking at hooks but I am unsure if I'm looking at the right method, if you get what I mean? The result I would like to have is, for example: <h1 class="custom-h2"> Lorem ipsum dolor sit amet </h1> Thanks in advance! -
Chnage request.user in django middleware
I have a custom token for letting my user access api s the problem is here that I need to get current user for some part of code using request.user how can I write middleware to do this for me? -
Django 2.2 FilteredSelectMultiple outside Admin panel
I've setup urls.py to include the javasript-catalog, and my forms.py is defined like this: from django.contrib.admin.widgets import FilteredSelectMultiple class FooBarForm(forms.ModelForm): class Meta: model = Foo fields = ( '__all__' ) bar = forms.ModelMultipleChoiceField(queryset=FooBar.objects.all(), widget=FilteredSelectMultiple("verbose name", is_stacked=False)) class Media: css = {'all':('admin/css/base.css', 'admin/css/widgets.css', 'admin/css/forms.css', 'admin/css/responsive.css')} Inside my template.html is: {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {{ form.media }} </head> <body> <div class="container"> <div class="row"> {{ form }} </div> </div> <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> </body> </html> That converts to this after rendering: <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="/static/admin/css/base.css" type="text/css" media="all" rel="stylesheet"> <link href="/static/admin/css/widgets.css" type="text/css" media="all" rel="stylesheet"> <link href="/static/admin/css/forms.css" type="text/css" media="all" rel="stylesheet"> <link href="/static/admin/css/responsive.css" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/admin/js/SelectBox.js"></script> <script type="text/javascript" src="/static/admin/js/SelectFilter2.js"></script> </head> <body> <div class="container"> <div class="row"> <select name="foo" required id="bar" multiple class="selectfilter" data-field-name="Concelhos" data-is-stacked="0"> <option value="1">....</option> </select> </div> </div> <script type="text/javascript" src="/jsi18n/"></script> </body> </html> The forms renders as it should, but doesn't work. The console error show as below: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined at findForm (VM59 SelectFilter2.js:11) at findForm (VM59 SelectFilter2.js:12) Any ideas … -
Testing on Django rest framework
I got stuck on testing small piece of code for 3 hours, every time I am receiving the same error. class DroneCategoryTests(APITestCase): def post_drone_category(self, name): url = reverse(views.DroneCategoryList.name) data = {'name': name} response = self.client.post(url, data, format='json') return response def test_post_and_get_drone_category(self): new_drone_category_name = 'Hexacopter' response = self.post_drone_category(new_drone_category_name) print("PK {0}".format(DroneCategory.objects.get().pk)) assert response.status_code == status.HTTP_201_CREATED assert DroneCategory.objects.count() == 1 assert DroneCategory.objects.get().name == new_drone_category_name here is the code when I type pytest it shows too long error that's why I cannot paste here but I can say the error is about database like self = <django.db.backends.utils.CursorWrapper object at 0x7f1d57a216d8> sql = 'SELECT "toys_toy"."id", "toys_toy"."created", "toys_toy"."name", "toys_toy"."description", "toys_toy"."toy_category", "toys_toy"."release_date", "toys_toy"."included_inhome" FROM "toys_toy" ORDER BY "toys_toy"."id" ASC' params = () ignored_wrapper_args = (False, {'connection': <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f1d5b68d0b8>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7f1d57a216d8>}) here test is about Drone but I do not know why Toy models is appearing. How can I fix the problem? -
TypeError: expected string or bytes-like object while updating M2M
I am trying to update a ManyToMany field in django while doing this I am getting the following error : value = self.get_prep_value(value) File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1408, in get_prep_value value = super().get_prep_value(value) File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1268, in get_prep_value return self.to_python(value) File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1369, in to_python parsed = parse_datetime(value) File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/utils/dateparse.py", line 106, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object Here is my models.py class tag(models.Model): name = models.CharField(max_length=100) created_date = models.DateTimeField(default=timezone.now) description = models.TextField(blank=True) def __str__(self): return self.name class tutorial(models.Model): title = models.CharField(max_length=200) link = models.URLField() tags = models.ManyToManyField(tag) category = models.CharField(max_length=200, choices = TUTORIAL_CATEGORIES) created_date = models.DateTimeField(default=timezone.now) @cached_property def __str__(self): return self.title views.py I am actually generating title & tags from a custom script that's why the serialzer are incomplete. I am trying to send the following JSON data : { "link":"https://youtu.be/DHvMXvCVQVA", "category":"video" } @api_view(['GET', 'POST']) def tutorials(request): """ get: Returns all tutorials post: POST a tutorial """ if request.method == 'GET': tutorials = tutorial.objects.all() serializer = tutorialSerializer(tutorials, many=True) return JSONResponse(serializer.data) elif request.method == 'POST': postserializer = tutorialPOST(data = request.data) if postserializer.is_valid(): title, tags = generateTags(request.data['link']) print(title) print(tags) updateDB = tutorial.objects.create( title = title, link = request.data['link'], category = request.data['category'], created_date = timezone.now ) … -
how to access a list of list in python
below is how the list looks like. I want to access list of list. I want to access it because I want to store it to a database.the response_body looks like this. [ { "username_count": 0, "description": "som string", "rules": [ { "id": 10845, "type": "some string" } ], "event_count": 7, "flow_count": 0, "assigned_to": null, "security_category_count": 3, "follow_up": false, "source_address_ids": [ 858,345 ], "source_count": 1, "inactive": false, "protected": false, "category_count": 3, "source_network": "some string", "destination_networks": [ "other", "some string" ], "closing_user": null, "close_time": null, "remote_destination_count": 1, "start_time": 1563267761163, "last_updated_time": 1563268006582, "credibility": 3, "magnitude": 6, "id": 4786, "categories": [ "string1", "string2", "string3" ], "severity": 8, "policy_category_count": 0, "device_count": 3, "closing_reason_id": null, "offense_type": 0, "relevance": 5, "domain_id": 0, "offense_source": "172.168.15.120", "local_destination_address_ids": [ 3 ], "local_destination_count": 1, "status": "OPEN" }, I have tried doing this response_body = json.loads(response.read().decode('utf-8')) for j in response_body: obj, created = Offenses.objects.get_or_create(oid=j['id'], defaults={'description': j['description'], 'assigned_to': j['assigned_to'], 'categories':j['categories']}) but this doesn't work as it returns None how should I access the category in the above list because category is itself a list? it should return some string but instead returns None. -
Improving cold start up times on Google App Engine running Django on Python 3.7 Standard environment
I'm running a Django-based web app on Google App Engine under the Python 3.7 Standard Environment. When using the app, requests usually take around 500ms, which is completely acceptable. Howevever, when the app has not been accessed for some time (a few minutes), the logs show that the Google App Engine instance is shut down, and the next request requires gunicorn to load again and takes about 20 second. I obciously can't have users wait 20 seconds before the page loads. When testing on my local setup, the server takes a few seconds to load environment variables, and then the debug server loads almost immediately. I don't think there is a problem with my code, given that once the "cold start" occurs, everything is running fast, so it's not like the requests are waiting for a database read or something like that. What options are there to optimise django cold starts on Google App Engine? So far, I've increased instance class to F4, and specified the number fo gunicorn workers according to this guide. I can in theory go to F4_1G, but that's the highest available instance, and it doesn't seem to address the cold start issue. The only other … -
Django Validation error not showing on form
#I want to check the user registration.# ##if the username has already been registered, give the user a validation error.## In my terminal environment, the data_user dictionary is also printed but in my form registration, a username validation error does not work into help.html This is the same Form. ---> https://imgur.com/a/osAv0xn models.py from django.db import models class SignUpModel(models.Model): name = models.CharField(max_length=20,null=True) family = models.CharField(max_length=30,null=True) username = models.CharField(max_length=10) email = models.EmailField(null=True,unique=True) password = models.CharField(max_length=20,null=True) # Create your models here. class LoginModel(models.Model): username = models.CharField(max_length=15) password = models.CharField(max_length=20) views.py from django.shortcuts import render from .forms import * from django.contrib.admin.views.decorators import staff_member_required @staff_member_required() def blogPostSignUpView(request): form = BlogPostSignUpModelForm(request.POST or None) if form.is_valid(): form.save() print(form.cleaned_data) form = BlogPostSignUpModelForm() template_name = "help.html" context = {"title":"register","form":form} return render(request,template_name,context) @staff_member_required def blogPostLoginView(request): form = BlogPostLoginModelForm(request.POST or None) if form.is_valid(): # print(request.POST) # obj = form.cleaned_data # data_user = SignUpModel.objects.filter(username=obj['username']) # print(data_user) # if obj['password'] == data_user['password']: # print(data_user) obj = form.save(commit=False) obj.save() # form = BlogPostLoginModelForm() template_name = 'help.html' context = {"title":"login","form":form} return render(request,template_name , context) forms.py from django import forms from .models import SignUpModel,LoginModel #Sign UP Form class BlogPostSignUpForm(forms.Form): name = forms.CharField() family = forms.CharField() username = forms.CharField() email = forms.CharField(widget=forms.EmailField) password = forms.CharField() class BlogPostSignUpModelForm(forms.ModelForm): … -
how to fix "djang-admin not recognized"
I just formatted my OS due some reason so installed python and django again. I tried to create the python project in the same environment as previous project but unlike that it does not recognizes the "django-admin" command please help me to solve this issue. I tried reinstall it with pip and also created the environmental variable for django still not worked. enter image description here -
I am working on django but my static files are no loading
These are my files kindly tell me what i am doing wrong or what changes are needed to be done settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'firstapp/style.css' %}"/> <h1>Here are all Albums</h1> {% if all_albums %} <ul> {% for album in all_albums %} <li><a href="{% url 'firstapp:detail' album.id %}">{{ album.album_title }}</a> </li> {% endfor %} </ul> {% else %} <h1>No data found</h1> {% endif %} style.css body{ background: white url{"images/background.png"}; } -
Save an output file on disk using shell commands in a django app
I am creating a script to run shell commands for simulation purposes using a web app. I want to run a shell command in a django app and then save the output to a file. The problem I am facing is that when running the shell command, the output tries to get saved in the url that I am in which is understandable. I want to save the output to for example: '/home/myoutput/output.txt' rather than /projects or /tasks I have to run a whole script and save it's output to the txt file later but that is easy once this is done. Tried os.chdir() function to change directory to /desiredpath first from subprocess import run #the function invoked from views.py def invoke_mpiexec(): run('echo "this is a test file" > fahadTest.txt') FileNotFoundError at /projects Exception Type: FileNotFoundError -
Creating ModelForm with EmbeddedModelField and customize fields within EmbeddedModelField
I have a model (parentmodel) which is having a EmbeddedModelField (embedmodel). This is basically a document in MongoDB. Below is the Model classes class embedmodel(models.Model): sendto = models.CharField(max_length=10) sendtouser = models.CharField(max_length=15) sendtogroup = models.CharField(max_length=15) class parentmodel(models.Model): name = models.CharField(max_length=30, unique=True, primary_key=True) type = models.CharField(max_length=11) enabled = models.BooleanField() rule = models.EmbeddedModelField(model_container=embedmodel) class Meta: managed = False db_table = 'parentmodel' And this is how my document in mongodb looks like { 'name': 'rule1', 'type': 'static', 'enabled': True, 'rule': { 'sendto': 'external', 'sendtouser': 'sam', 'sendtogroup': 'vendor' } } I am trying to create a form which helps me create new rules and this is what i have in forms.py where i want to customize the form fields as well. class RulesForm(forms.ModelForm): name = forms.CharField(max_length=30, required=True) type = forms.CharField(max_length=11, required=True) enabled = forms.BooleanField(widget=forms.CheckboxInput) class Meta: model = parentmodel fields = ['name', 'type', 'enabled', 'rule'] How to do customize the fields being displayed from embedmodel? I tried the below but no luck. class RulesForm(forms.ModelForm): name = forms.CharField(max_length=30, required=True) type = forms.CharField(max_length=11, empty_value="UserDefined", required=True enabled = forms.BooleanField(widget=forms.CheckboxInput) sendto = forms.ChoiceField(widget=forms.Select, choices=[(1, 'External'), (2, 'Internal')]) sendtouser = forms.CharField(max_length=30, required=False) sendtogroup = forms.CharField(max_length=30, required=False) class Meta: model = Rules fields = ['name', 'type', 'enabled', 'rule'] and class RulesForm(forms.ModelForm): … -
How can i use other apps api in my own project?
Let's say i wanted to use the weather api to implement in my django code. I know how to create Rest-api in django but how can i use api of other sources to django itself? -
Display checkbox value from Database Django
I'm making a ModelForm. I have a Gender field in which I have given choices.In forms.py file I have converted those choices into checkbox using widget. models .py class UserModel(models.Model): #username=models.ForeignKey( # on_delete=models.CASCADE, # related_name='custom_user') name=models.CharField( max_length=50, verbose_name='Full Name', ) gender=models.CharField( choices=( ('M','Male'), ('F','Female'), ), max_length=1, verbose_name='Gender', default='M' ) forms.py class UserForm(forms.ModelForm): class Meta: model=UserModel exclude=() widgets = { 'DOB': forms.SelectDateWidget(), 'gender':forms.RadioSelect(), #'hobbies':forms.CheckboxSelectMultiple() } everything works fine and data is stored in database,But when I fetch data from the database using commands.Instead of getting the name of choice I get 'M',or 'F'. I know for choice field we can user object.get_gender_display to get name of choice and it returns full name of choice. But since I have converted the choice to checkbox field in forms.py,now when I fetch data from database using object.get_gender_display it returns functools.partial(<bound method Model._get_FIELD_display of <UserModel: hoo>>, field=<django.db.models.fields.CharField: gender>) How can I get original name as "Male' and 'Female' ? Thanks -
How to Get a function from one app to be used in another app in Django
I have two apps Products and Shopping_cart, and I have a model in the shopping_cart app called order with the method get_cart_items and get_cart_total, In the shopping_cart app i have a view called order_details which gives the order summary, However in the products app i have a view which renders the index.html ,so i want to show the order summary on the header of the index.html template using the order_details view from the shopping_cart app on the same app works fine but on the products app doesn't template <div class="header-cart-content flex-w js-pscroll"> <ul class="header-cart-wrapitem w-full"> {% for item in order.get_cart_items %} <li class="header-cart-item flex-w flex-t m-b-12"> <div class="header-cart-item-img"> <img src="{{ MEDIA_URL }}{{ item.product.get_featured_image.url }}" alt="IMG"> </div> <div class="header-cart-item-txt p-t-8"> <a href="#" class="header-cart-item-name m-b-18 hov-cl1 trans-04"> {{ item.product.name }} </a> <span class="header-cart-item-info"> {{ item.product.price }} </span> </div> </li> {% empty %} <p> You have not added any items yet.</p> {% endfor %} </ul> {% if order.get_cart_total != None %} <div class="w-full"> <div class="header-cart-total w-full p-tb-40"> Total:${{ order.get_cart_total }} </div> {% endif %} {% if order.get_cart_items %} <div class="header-cart-buttons flex-w w-full"> <a href="{% url 'shopping_cart:order_summary' %}" class="flex-c-m stext-101 cl0 size-107 bg3 bor2 hov-btn3 p-lr-15 trans-04 m-r-8 m-b-10"> View Cart </a> <a href="{% … -
Django: List Items of each categories in a single page
I'm working on checklist app and each checklist have tasks with categories. I would like to list the tasks per category in the format below: Category 1 Task 1 of Category 1 Task 2 of Category 1 Category 2 Task 1 of Category 2 Task 2 of Category 2 I’ve tried this answer - Django: List Products of each Categories in a page But always have a blank list without any errors.. class Checklist(models.Model): slug = models.SlugField(max_length=250, unique=True, blank=True) name = models.CharField(max_length=250, unique=True) profile = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.ForeignKey( ChecklistCategory, blank=True, null=True, on_delete=models.SET_NULL ) language = models.ForeignKey( ChecklistLanguage, blank=True, null=True, on_delete=models.SET_NULL ) image = models.ImageField( upload_to='images/checklist/cover/%Y/%m/%d/', default='default_cover.png', blank=True, null=True ) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='checklist_likes', blank=True) class Meta: ordering = ['-name'] def get_like_url(self): return reverse('checklist_like_toggle_url', kwargs={'slug': self.slug}) def get_absolute_url(self): return reverse('checklist_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = gen_slug(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class ChecklistTaskCategory(models.Model): task_category_name = models.CharField(max_length=250, unique=True, blank=True) def __str__(self): return self.task_category_name class ChecklistTask(models.Model): task = models.CharField(max_length=300, unique=True, blank=True) description = models.TextField(max_length=500, blank=True, null=True) checklist = models.ForeignKey( Checklist, on_delete=models.CASCADE, blank=True, null=True ) task_category = models.ForeignKey( ChecklistTaskCategory, blank=True, null=True, on_delete=models.CASCADE) done = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='task_done', blank=True) slug = models.SlugField(max_length=250, unique=True, blank=True) def get_done_url(self): return … -
Login page returned "account does not exist" after successful registration of user
I am a newbie in django web development. I was creating a simple bank web application. The registration works well as users can be created and logged in automatically. However, when I log out the user and try to log in again, the page tells me that the account does not exist. I think the error is in my views.py file. I have tried to find the error but as I have said I am a newbie. Kindly, someone assist me. views.py: def login_view(request): if request.user.is_authenticated: return redirect("home") else: form = UserLoginForm(request.POST or None) if form.is_valid(): account_no = form.cleaned_data.get("account_no") password = form.cleaned_data.get("password") # authenticate with Account No & Password user = authenticate(account_no=account_no, password=password) if user is not None: login(request, user, backend='accounts.backends.AccountNoBackend') messages.success(request, 'Welcome, {}!' .format(user.full_name)) return redirect("home") context = {"form": form, "title": "Load Account Details", } return render(request, "accounts/form.html", context) backends.py: from django.contrib.auth import get_user_model User = get_user_model() class AccountNoBackend(): def authenticate(self, request, account_no=None, password=None): try: user = User.objects.get(account__account_no=account_no) if user and user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None I expect to be redirected to a success page but instead it cannot find the requested account number -
Django custom template filter feeding cookie or default value
I'm designing a custom django filter, just to make sure it works I have something like this {{ "Sleeps:"|translate:"fr" }} and it works. Now in the final implementation, I want it to get a cookie or else use a default value {{ pg.title|translate:request.COOKIES.lang|default:"en" }} I'm getting this error VariableDoesNotExist at /chalet/belle-chery Failed lookup for key [lang] in {'_ga': 'GA1.1.1026479868.1547798010', 'cookie-policy': 'true', 'csrftoken': 'VrVrvgZUfFrWhFDFjLIvZgOus9NrmjDx1JwNP2lzvz2FRAGmC1lLrKwiH4g31X5F', 'sessionid': 'ptp6smvt9w95qtqlkc7klx736u5k7uu5'} so it doesn't implement the default part. So I figure there's either a way to fix this or use middleware to set the cookie if it's not set. Would be nice if it doesn't need middleware. -
Use Querysets and JSON correctly in API View
I am trying to write my custom API view and I am struggling a bit with querysets and JSON. It shouldn't be that complicated but I am stuck still. Also I am confused by some strange behaviour of the loop I coded. Here is my view: @api_view() def BuildingGroupHeatYear(request, pk, year): passed_year = str(year) building_group_object = get_object_or_404(BuildingGroup, id=pk) buildings = building_group_object.buildings.all() for item in buildings: demand_heat_item = item.demandheat_set.filter(year=passed_year).values('building_id', 'year', 'demand') return Response(demand_heat_item)) Ok so this actually gives me back exactly what I want. Namely that: {'building_id': 1, 'year': 2019, 'demand': 230.3}{'building_id': 1, 'year': 2019, 'demand': 234.0} Ok, great, but why? Shouldn't the data be overwritten each time the loop goes over it? Also when I get the type of the demand_heat_item I get back a queryset <class 'django.db.models.query.QuerySet'> But this is an API View, so I would like to get a JSON back. SHouldn't that throw me an error? And how could I do this so I get the same data structure back as a JSON? It tried to rewrite it like this but without success because I can't serialize it: @api_view() def BuildingGroupHeatYear(request, pk, year): passed_year = str(year) building_group_object = get_object_or_404(BuildingGroup, id=pk) buildings = building_group_object.buildings.all() demand_list = [] for … -
Override default show option in datatables
I'm trying to override "show entries" option in datatable using jquery provided in datatables documentation. But it looks like datatable js cdn is overriding this to 10 again. After reloading it shows "25" but then again changes to "10" again. <script> $('#items2').dataTable( { "lengthMenu": [ [25, 50, -1], [25, 50, "All"] ] } ); </script> <script> $('#items').dataTable( { "lengthMenu": [ [25, 50, -1], [25, 50, "All"] ] } ); </script> -
send array of data as post to django
I am trying to send post request through a form to django views so as to use it to retrieve data from database on next page (action page). I am not getting the data on second page however. I have tried to use array in the name and assign array value in the form. I tried a for loop of values and names as well. However no data is received at the second page. The form to send post request: <form method="post" action="{% url 'cartpage' %}" id="formcart"> {% csrf_token %} <script> for(var i=0;i<prods.length;i++){ document.write('<input type="gone" name="cartitems[]" style="display: none;" value="prods[i]" />'); } </script> </form> Trying to get post data and the array elements on the second page in views.py: def cart(request): if request.method == 'POST': try: cartitems = request.POST.getlist('cartitems') except (KeyError): raise firstval = pionizedb.objects.filter(id__contains=cartitems[:1]) context = { 'firstval': temfil, } return render(request, 'cart.html', context) alert({{firstval}}); in html page should return first value of the array. -
How to return multiple rows with django subquery?
I am trying to get values from subquery to use in annotation, and gives an django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression error. I have queries like q = A.objects.filter(id=OuterRef('id'), b=b)\ .select_related('provider')\ .only('id', 'b', 'code')\ .distinct('code')\ .values_list('code', flat=True) t = t.annotate(**{x: ArrayAgg(Subquery(hotel_match))}) I really want to return multiple values if exists with combining ArrayAgg and StringAgg to export values as csv. How can I work with that ?