Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms: how to get product's data from db with ajax
I have models (ShopStock and SaleItem), I have registered product and price in ShopStock model, in SaleItem model i also have product and price fields. What i want is when i select a product in (SaleItemForm) the price field to be filled with a price from Shopstock model. I have no idea how to do it in javascript. Models class Product(models.Model): name = models.CharField(max_length = 100, blank=True) class ShopStock(models.Model): products = models.ForeignKey(Product, null=True, blank=True, on_delete = models.SET_NULL) price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) class SaleItem(models.Model): product = models.ForeignKey(ShopStock, null=True, blank=True, on_delete = models.SET_NULL) quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) I tried this to solve my problem but it's not working Views def price(request): if request.method == 'GET': total_price = SaleItem.price response_data ={} response_data['price'] = total_price return JsonResponse(response_data) Templates $(document).ready(function() { $('#id_product').change(function(){ var query = $(this).val(); console.log(query); $.ajax({ url : "/price/", type : "GET", dataType: "json", data : { client_response : query }, success: function(json) { document.getElementById('id_price').value=json.price; }, failure: function(json) { alert('Got an error dude'); } }); }); }); Forms class SaleItemForm(forms.ModelForm): product = forms.ModelChoiceField(queryset=ShopStock.objects.all(), widget=forms.Select(attrs={'class':'form-control', 'id':'id_product'})) class Meta: model = SaleItem fields = ['product', 'quantity', … -
create, download PDF and return form on submit with Django
For a small project i want users to fill in a form and when they submit, it has to download a PDF with the form data & return them to the same page. But i'm not sure how to achieve this. Im using a generic CreateView and a createPDF() function. This is what i've tried so far: class FormView(CreateView): model = ExampleModel succes_url = reverse_lazy('Create') fields = ["first_name", "last_name"] def form_valid(self, form): formData = form.save(commmit=False) first_name = formData.first_name last_name = formData.last_name createPDF(requests, first_name, last_name) return super().form_valid(form) def createPDF(request, first_name, last_name): buffer = io.BytesIO() p = canvas.Canvas(buffer) p.drawString(15, 800, first_name, last_name) p.showPage() p.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='example.pdf') The problem here is that i dont see any errors, so i'm not sure what's going wrong. With the code above users can fill in the form and when they submit, they will return to the form again, which is good, but unfortunately the PDF file never downloads.. what is going wrong here? appreciate any help :) -
Azure AD token to connect SQL Server - Django
I have successfully connected the Azure SQL Server using AccessToken in the pyodbc. Here I didn't use username or password to connect the DB. conn = pyodbc.connect(connString, attrs_before = { SQL_COPT_SS_ACCESS_TOKEN:tokenstruct}); #sample query using AdventureWorks cursor = conn.cursor() cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid") row = cursor.fetchone() while row: print (str(row[0]) + " " + str(row[1])) row = cursor.fetchone() Reference Link: https://github.com/felipefandrade/azuresqlspn Now the problem is how to use this in the Django framework? We can't have a username or password to connect the database when using azure token. -
Bootstrap table not allow clicks (link) on search or filter result
I am new to Bootstrap table and use this https://codepen.io/AurelieT/pen/JGxMgo example and added click function which working fine until I apply any bootstrap features such as filtering, search, pagination, and others after applying any bootstrap features not able to click as before my table-row function not work, and not able to get table row id for selected checkbox its only show ('btSelectItem': ['on', 'on']) on Django View console instead of table id or name once click some button. <td class='table-row' data-href="{% url 'detail' item.slug%}">{{ item.item_name }}</td> my css style .table-row{cursor:pointer;color: blue;} query for click $(document).ready(function($) { $(".table-row").click(function() { window.document.location = $(this).data("href"); }); }); Appreciate your help and advice. -
Paginating in ListView django
I am trying to paginate data in my table in html template, but it is not working. I am using default paginate system from list views. Also I have a form in which user can pass items per page value. This is my code for views.py: def get_paginate_by(self, queryset, **kwargs): itemsForm = ItemsPerPageForm(self.request.GET) if itemsForm.is_valid(): itemsPerPage = itemsForm.cleaned_data.get('items_per_page') print(itemsPerPage) if itemsPerPage is None: return 4 else: if itemsPerPage > 0 and itemsPerPage <= Category.objects.get_queryset().count(): return itemsPerPage else: return 4 And this is my django template: </table> <tbody> {% for category, expenses in noOfExpenses %} <tr> <td>{{ page_obj.start_index|add:forloop.counter0}}.</td> <td>{{ category.name|default:"-" }}</td> <td>{{ expenses }}</td> </tr> {% empty %} <tr> <td colspan="6">no items</td> </tr> {% endfor %} </tbody> </table> <hr/> {% include "_pagination.html" %} {{page_obj}} <form method="get" action=""> {{itemsForm.as_p}} <button type="submit">submit</button> </form> And _pagination.html: <div class="pagination"> <span class="pagination__nav"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} <br/> Total items: {{page_obj.paginator.count}} </span> </div> So in the end, on the website, despite that I have only 4 items, I have 2 … -
os.path.join('BASE_DIR','template') problem
When i run following code In settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', **'DIRS': ['os.path.join('BASE_DIR','template') '],** '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', ], }, }, ] its shows an error template not found but when i execute following code in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', **'DIRS': ['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', ], }, }, ] this work fine!!! what this os.path.join('BASE_DIR','template') actually means?? Thanks in advance!!!! -
Django - My key object id jumped from 11 to 44. Why?
I had added a few movies and their object ids were sequential: 1,2,3,4,5,6,7,8,9,10,11. But today I just added a new movie and the last one before it had 11 as id, but this new movie was given id 44. Why is this, why did it skip 12 and go all the way to 44? example.com/admin/movies/movie/1/change/ example.com/admin/movies/movie/2/change/ ... example.com/admin/movies/movie/10/change/ example.com/admin/movies/movie/11/change/ example.com/admin/movies/movie/44/change/ class Movie(models.Model): name = models.CharField(max_length=255) create_date = models.DateTimeField() owner = models.ManyToManyField(User) def __str__(self): return self.name -
React JS: How to pass static files to front-end (Django, React, Webpack) + ( no loaders are configured for .MP4 files )
I'm using a combo of Django + react js + webpack to build my application and I'm still really green on react js and webpack so I have no clue how to host or pass the files to frontend. So basically I don't pass the static files via django, and I don't have any configuration for static files in django. I'm trying to pass the static files which are in react js main directory. This is my project structure: And you can also see the webpack config that I have right now. But my question is how do I have to pass static files to react js? My code: import React from 'react'; import Video from '../videos/video.mp4'; import { HeroContainer, HeroBg, VideoBg } from './HeroElements'; const HeroSection = () => { return ( <HeroContainer> <HeroBg> <VideoBg /*src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4" */ src={Video} type="video/mp4" autoPlay loop muted /> </HeroBg> </HeroContainer> ) } export default HeroSection; -
Createing url paths with following integers Django
Trying to create a path such as hostname://homesapp/1/1 using regular integers for the first number and pk for the second, i know using re_path it would be similar to from django.contrib import admin from django.urls import path, include, re_path from .import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.LocationView.as_view(), name='property'), re_path(r'^([0-9]+)/(?P<pk>[0-9]+)/$', view.PropertyDetail.as_view(), name="propertyview"), ] but not sure about just using path for the final url -
TypeError: 'User' object is not iterable using Django
I am trying to route an AJAX GET request through views.py and return it to a template, but only show the object items connected with the logged in user. I am attempting to use filter() but am getting the following error: 'User' object is not iterable. Here is the views.py class: class user_playlist(ListView): template_name = 'testingland/dashboard.html' context_object_name = 'playlist' model = UserVenue def get_queryset(self): venue = self.request.GET.get('venue', None) list = self.request.GET.get('list', None) return UserVenue.objects.filter(self.request.user) Here is the template: <body> {% block content %} <div class="container-fluid" style="padding:15px"> <!--location --> <div class="row"> <div class="col-sm-3" id="playlist"></div> <ul class = "cafe-playlist"> {% for item in playlist %} <li> <div> <h6 class="playlist-name">{{ item.list }}</h6> </div> </li> {% endfor %} </ul> </div> {% endblock %} And here is the AJAX Call for good measure: //dashboard $(document).ready(function(){ console.log('Document Ready') $.ajax({ type: "GET", url : '/electra/playlist', dataType: "json", data: { 'venue': 'venue', 'list': 'list', }, success: function(data){ $("#playlist").html(data); console.log(data) }, failure: function(errMsg) { alert(errMsg); } }); }); For those interested here is the full traceback: Internal Server Error: /electra/playlist Traceback (most recent call last): File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get _response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/views/generic/base.py", line … -
Django REST Framework view permissions not called
I am trying to create a custom permission for my view that allow read and write permissions to the owner of the model in the QuerySet but do not allow any permission/request to other users or un-authenticated ones. Source: https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/ View: class My_classListCreateAPIView(generics.ListCreateAPIView): queryset = Model.objects.all() serializer_class = ModelSerializer permission_classes = [IsModelOwner] Permission: class IsModelOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Permissions are only allowed to the owner of the model and admins. if request.user.is_staff == True: return True return obj.owner == request.user unfortunately it seems that my view is not even calling my custom permission class. (I imported it etc.) If instead of my custom permission class, I use a default one like permissions.isAuthenticatedOrReadOnly that works instead. What am I missing here? Thanks. -
Django multiple sessions for same domain
I'm looking for a way to serve 2 independent Single Page Applications from different paths on the same domain, and have both of these talk to 1 single Django backend. e.g. 2 independent Single Page Applications FOO webapp served at https://app.com/foo/ BAR webapp served at https://app.com/bar/ 1 Django backend served at https://api.app.com/ It seems an odd requirement to me, but that's not in my control. Unless there is a real technical limitation here that's the approach I have to take. I'm unsure how this could work, particularly in terms of sessions. Django uses a cookie to track sessions. This cookie is called sessionid by default, and that can be controlled by the SESSION_COOKIE_NAME setting. I think a sensible approach would be to have 2 separate session cookies, foo_sessionid and bar_sessionid in the example above. I'm not sure if there is a way to do this and would grateful for any insights. -
Shopify Public App Access to Discount Code API
I am using the python-shopify library and django to build a shopify app, using this. I wanted to retrieve all the discount codes currently in place on my development store, using the following code: discounts = shopify.PriceRule.find() But I have the following error being thrown out. This action requires merchant approval for read_price_rules scope python shopify Please help -
find MAX,MIN and AVG of a set in Django
I have an object called meter and it has a set called powerConsumptionReport_set. This is the models.py : class Meter(models.Model): region = models.PositiveSmallIntegerField(null=1) IPAddress = models.GenericIPAddressField(default=0,null=False,blank=False,unique=True) PortNumber = models.IntegerField(default=1024) SerialNumber = models.IntegerField(default=00000000,null=False,blank=False,unique=True) class PowerConsumptionReport(models.Model): meter = models.ForeignKey(Meter, blank=True, null=True, on_delete=models.CASCADE) power = models.FloatField() I need to find Max value of power field from the powerConsumptionReport_set and display it in my template. This is the DetailView i used to show each Meter : class MeterDetailView(DetailView): model = Meter template_name = 'meter/specificMeter.html' And the template is here: <h1 class="card-text text-md-center"> *** here i want to show min value of the set **** - {{ meter.powerconsumptionreport_set.first.power }} </h1> how can i access Max,Min and AVG value of power field from the powerConsumptionReport_set related to each meter. Cheers. -
How can i remove videos from later for individual users?
views.py here in views.py i have tried to make logic for remove any song from watch later but, i am not able to build logic for it.Basically dont know how to bring watch_id(primary key) of my watch later model. def deletewatchlater(request): if request.method=="POSt": user=request.user video_id=request.POST['video_id'] # watch_id=request.POST['watch_id'] wat=Watchlater(user=user,video_id=video_id) wat.delete() messages.success(request,"Song delete from watch later") return render(request,'watchlater.html') def watchlater(request): if request.method=="POST": user=request.user video_id=request.POST['video_id'] watch=Watchlater.objects.filter(user=user) for i in watch: if video_id==i.video_id: messages.success(request,"Song is already added") break else: wl=Watchlater(user=user,video_id=video_id) wl.save() messages.success(request,"Song added to watch later") return redirect(f"/index/subpage/{video_id}") wl=Watchlater.objects.filter(user=request.user) ids=[] for i in wl: ids.append(i.video_id) preserved=Case(*[When(pk=pk,then=pos) for pos,pk in enumerate(ids)]) song=Allmusic.objects.filter(sno__in=ids).order_by(preserved) return render(request,'watchlater.html',{'song':song}) urls.py I have made post request for it when user clicks button remove from watch later than it will send details of user and song_id and watchlater id from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('postComment',views.postComment,name="postComment"), path('',views.home,name='home'), path('index/',views.index,name='index'), path('indexmovie/',views.indexmovie,name='indexmovie'), path('index/subpage/<str:sno>',views.subpage,name='subpage'), path('about/',views.about,name='about'), path('contact/',views.contact,name='contact'), #User Login Logout Signup path('signup',views.handleSignup,name='handleSignup'), path('login',views.handleLogin,name='handleLogin'), path('logout',views.handleLogout,name='handleLogout'), path('search/',views.search,name='search'), #User Saved path('index/watchlater',views.watchlater,name='watchlater'), path('index/history',views.history,name='history'), path('index/likedsongs',views.likedsongs,name='likedsongs'), path('index/deletewatchlater',views.deletewatchlater,name='deletewatchlater'), ] watchlater.html {% extends 'base.html' %} {% block title %} watch Later {% endblock %} {% block css %} <style> </style> {% endblock %} {% block body %} <h1 style="text-align:center;padding-top: 5%; "> WATCH LATER</h1> {% if song|length … -
Django: cannot render an empty modelform in template
I am trying to build a form that would let the user create one or many database table rows at once. Right now, what is being rendered from my view is the entire db table. I understand that it is a basic behavior of a modelform to return the entire db table data, but according to django docs there is a way to override the default behavior (https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/). That's what I tried to do but it does not seem to work, the entire db table keeps being rendered. here is what my view look like: def New_Sales(request): context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount')) if request.method == 'POST': formset = form(queryset= historical_recent_data.objects.none()) if formset.is_valid(): formset.save() for check_form in formset: quantity = form.cleaned_data.get('Quantity') id = form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F(StockOnHand) - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F(stock_reel) - quantity) return redirect('/dash2.html') else: form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount')) context['formset'] = form return render(request, 'new_sale.html', context) and my model: class historical_recent_data(models.Model): id = models.AutoField(primary_key=True, default= 0) Id = models.CharField(max_length=100, verbose_name= 'references') Date = models.DateField() Quantity = models.FloatField(default=0) NetAmount = models.FloatField(default=0) def __str__(self): return self.reference any help on this would be appreciated! -
Unable to login with correct username and password in Django with custom User model
I successfully created superuser and when I try to login it says your password is incorrect. I checked mu code and I tested it with deleting database and migrations and creating them again many times but couldn't figure out what is wrong. Here is my code From models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.validators import MinLengthValidator class UserManager(BaseUserManager): def create_user(self, email, phone_number, first_name, last_name, social_id, password=None, is_staff=False, is_superuser=False, is_active=False): if not email or not phone_number or not first_name or not last_name or not social_id: raise ValueError('fill all the fields') if not password: raise ValueError('must have pasword') user = self.model( email = self.normalize_email(email), phone_number = phone_number, first_name = first_name, last_name = last_name, social_id = social_id ) user.set_password(password) user.is_staff = is_staff user.is_superuser = is_superuser user.is_active = is_active user.save(using=self._db) return user def create_staffuser(self, email, phone_number, first_name, last_name, social_id, password=None): user = self.create_user( email, phone_number = phone_number, first_name = first_name, last_name = last_name, social_id = social_id, password=password, is_staff=True, ) return user def create_superuser(self, email, phone_number, first_name, last_name, social_id, password=None): user = self.create_user( email, phone_number = phone_number, first_name = first_name, last_name = last_name, social_id = social_id, password=password, is_staff=True, is_superuser=True, ) return user class User(AbstractBaseUser): first_name = models.CharField(max_length=50, blank=False) last_name = … -
ContentNotRenderedError: The response content must be rendered before it can be iterated over. Django REST
I am getting an error : The response content must be rendered before it can be iterated over. What's wrong with below line of code..?? if anybody could figure out where i have done mistakes then would be much appreciated. thank you so much in advance. serializers.py class GlobalShopSearchList(ListAPIView): serializer_class = GlobalSearchSerializer def get_queryset(self): try: query = self.request.GET.get('q', None) print('query', query) if query: snippets = ShopOwnerAddress.objects.filter( Q(user_id__name__iexact=query)| Q(user_id__mobile_number__iexact=query)| Q(address_line1__iexact=query) ).distinct() return Response({'message': 'data retrieved successfully!', 'data':snippets}, status=200) else: # some logic.... except KeyError: # some logic.... -
Where the refresh token and access token are stored while using JWT in Django rest framework?
I asked this question on other forums, but couldn't get answer that's why I am asking this question over stack overflow. I don't know whether I can ask this type of question over here or not. Sorry for that. I am trying to implement JWT using djangorestframework-simplejwt for my Django rest application. I noticed that refresh token and access token are not stored in database. Than where are they stored? Thanks in advance. -
Can't get data into my javaskript funktion using django
Hello I tried to get graphs but my buildDHTChart funktion didn't work I'm happy for every help Here is my views.py def sensor_main2(response): data={} sensors=Sensor.objects.all() for sensor in sensors: if 'DHT' in sensor.name: data[sensor.name]=pd.DataFrame({'humidity':Sensorreading.objects.filter(measured_value='humidity',name=sensor.name).values_list('value', flat=True)[:2], 'temperature':Sensorreading.objects.filter(measured_value='temperature',name=sensor.name).values_list('value', flat=True)[:2]}) elif 'ds18b20' in sensor.name: data[sensor.name]=pd.DataFrame({'temperature':Sensorreading.objects.filter(measured_value='temperature',name=sensor.name).values_list('value', flat=True)[:2]}) time=Sensorreading.objects.order_by('time').reverse().filter(measured_value='temperature').values_list('time',flat=True)[:2] return render(response,"sensor/sensor_main2.html",{"data":data,"time:":time}) The data comes from an SQLite3 database my model looks like this: class Sensor(models.Model): pi = models.CharField(max_length=30) name = models.CharField(max_length=30) type_field = models.CharField(max_length=30, db_column='type_') # Field renamed because it ended with '_'. pin = models.IntegerField() location = models.CharField(max_length=30) id_field = models.CharField(max_length=30, db_column='id_') # Field renamed because it ended with '_'. class Meta: managed = False db_table = 'sensor' def __str__(self): return self.name class Sensorreading(models.Model): time = models.DateTimeField() name = models.CharField(max_length=30) location = models.CharField(max_length=30) measured_value = models.CharField(max_length=30) value = models.FloatField() class Meta: managed = False db_table = 'sensorreading' def __str__(self): return self.name And at least my html page, in the beginning i've checked if i get some data from my database and data comes. But for some reason it didn't workt in my funktion at the end {% extends "main/base.html" %} {% block title %}Daten der Sensoren{% endblock %} {% block subtitle %}Daten der Sensoren{% endblock %} {% block content %} <div class="jumbotron"> <div class="container"> … -
Special input field in Django
I dont know how to do this on django, can you please help me do so. i use this field in class: special_number = models.CharField(max_length=17) but need that user enter number in field like this: 00:00:000000000:00 Users enter only number, ":" is enter automatically in field. Any please help? Thanks! -
AWS lambda in python: how to specify a callback function once it has finished?
I'm working with Django 2 and Python 3.6. I need to defer some work to an AWS Lambda function and do it asynchronously. It would be something like rendering (asynchronously) a complex template from its HTML code. Once the asynchronous rendering process has finished, I want to do some extra work in the server (not in the Lambda), like saving the result to the DB, etc. This is the code that should go in the "callback" function. My question is, what would be the way to define that "callback" function that would come into play once the Lambda has finished doing its work? -
Render data passed from Django to Vue
I get my data through axios with this: get_questions: function (){ axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' axios.post('{% url 'sw_app:api_get_questions' %}', this.test) .then(response=>{ this.questions = response.data.questions console.log(response.data.questions) }) } Here's the view function: def do_get_questions(request): data = json.loads(request.body.decode('utf-8')) test_code = data['code'] is_owner = check_test_owner(request, test_code) response = {} if is_owner: # Get Questions questions = models.Question.objects.filter(test__code=test_code) ser_questions = serializers.serialize('json', questions) response['result'] = 'ok' response['message'] = 'Questions fetched!' response['questions'] = ser_questions return JsonResponse(response) else: response['result'] = 'failed' response['message'] = 'You are not the owner of this test!' return JsonResponse(response) It returns this: [{"model": "sw_app.question", "pk": 2, "fields": {"test": 40, "content": "What is the phrase that beginner coders commonly use to display a string on the screen?"}}] models.py for reference: class Question(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) content = models.CharField(max_length=900) def __str__(self): return "Question: {} - Test: {}".format(self.id, self.test.id) Back in my vue (template), I store the questions here: data: { test: { code: '', }, questions: {} }, Now when I do this: <li class="list-group-item" v-for="question in questions" :key="question.pk"> [[ question.content ]] </li> It just display a lot of empty list objects. When I try doing this: <li class="list-group-item" v-for="question in questions" :key="question.pk"> [[ question]] </li> It displays this: Any ideas? Thanks … -
How do I view multiple api's in Django REST api?
So I have two models, and I'm trying to get both models in my api view. So here's the code: @api_view(['GET']) def mainPage(request, pk): thisQuestion = Question.objects.filter(question_number=pk) thisAnswer = Answer.objects.filter(authuser_id=request.user.id, question_number=pk) questionSerialized = QuestionSerializer(thisQuestion, many=True) answerSerialized = AnswerSerializer(thisAnswer, many=True) return Response(answerSerialized.data, questionSerialized.data) Obviously, the problem is in the return part. How do I get both in this case? Thank you very much in advance. -
Assigning a datetime object as the url parameter
I want to give the value of Datetime type to url as parameter using date filter. My url must be such: /account/detail-of-cash-flow/2020-8-10 This command: {{item.date_field|date:'Y-m-d'}} = '2020-8-10'. But, not working when i this commands implement to template url. template.html {% for item in cash_flow_data %} <tr class='clickable-row' data-href="{% url 'account:detail_of_cash_flow' item.date_field|date:'Y-m-d' %}"> <td>{{ item.date_field }}</td> <td>{{ item.EUR }}</td> <td>{{ item.USD }}</td> <td>{{ item.GBP }}</td> <td>{{ item.TRY }}</td> </tr> {% endfor %} urls.py app_name = "account" urlpatterns = [ path('daily-cash-flow/', views.daily_cash_flow, name = "daily_cash_flow"), path('detail-of-cash-flow/<slug:slug>/', views.detail_of_cash_flow, name = "detail_of_cash_flow") ] I hope I was able to explain my problem.