Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UpdateView that creates or increments existing instance
I have a model that keeps track how much items have been "bought" at a certain value. For example, one could think of items as stocks, value as the price they have been bought at. class Inventory(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() value = models.PositiveIntegerField() class Meta: db_table = 'app_version' constraints = [ models.UniqueConstraint(fields=['item', 'value'], name='unique valued items') ] Now, I'm trying to write a class-based Create/UpdateView in which one simply declares which item has been bought at what price. Then, the view should either create a new instance or increment an existing instance's quantity. I already figured out that an UpdateView might be the best start as I can overwrite the get_object method to have this "create or update" behaviour. However, I'm not sure how to do the incrementing. Perhaps I'm also completely on the wrong track and there is a much simpler solution I am missing here. It would be great to get some ideas and input on how to approach this problem. Thank you so much! -
Just getting the status code but not the data, but in postman it does
I want to send an error message through data when some errors occurs in API, here is the API code: @api_view(['GET']) def RespuestaListView(request, idQuestion): try: question = Question.objects.get(pk=idQuestion) except Question.DoesNotExist: return Response(data={'error': 'That question does not exist'}, status=status.HTTP_404_NOT_FOUND) try: answers= Answer.objects.filter(question=question).select_related() except: return Response(data={'error': 'It can't be done'}, status=status.HTTP_409_CONFLICT) if (answers.count() == 0): return Response(data={'error': 'There is no answers for that questions'}, status=status.HTTP_204_NO_CONTENT) res = [] for answers in answers: res.append(AnswerSerializer(answer).data) return Response(data=res, status=status.HTTP_200_OK) If I call this from postman, it receives the error messages in data: Please ignore the spanish call But when I try to do it from a function in reactjs, when one of the handled errors occurs it just does not work, and I just get the status code. -
How to make a GraphQL api request from Django application?
I would like to know how to retreive data using the GraphQl api service and NOT to create the API. -
I am unable to fetch partial data from related table in django
One order have many order items and if i exclude one of its order items, then it will exclude all other order items of that order id. Can somebody please tell me why? Here is order-id = 8056313100 and two order-items that have ids = 8056313101, 8056313102. Here is View.py order = Order.objects.distinct().filter(orderitem__status=request.data['status']).exclude(orderitem__order_item_id=8056313102) serializer = ListOrderSerializer(order, many=True) return Response(serializer.data) Serializer.py class ListOrderSerializer(serializers.ModelSerializer): order_items = ListOrderItemSerializer(many=True, read_only=True) class Meta: model = Order exclude = ('id',) Order-item-id = 8056313101 will also exclude. Please help me. -
Spyne/Django: Add reversed OneToOne field to response
I'm looking to make use of spyne + django to provide a soap api. In django I have two related models with a one to one relation between them. # models.py class MainThing(): number = models.CharField(max_length=32) # plus other CharFields here class RelatedThing(): number = models.CharField(max_length=32) main = models.OneToOneField('MainThing', on_delete=models.CASCADE) I then have a "service" that connects spyne to django: # service.py from .models import MainThing as MainThingModel class MainThing(DjangoComplexModel): class Attributes(DjangoComplexModel.Attributes): django_model = MainThingModel class MainThingService(DjangoService): @rpc(primitive.String, _returns=MainThing) def retrieveThing(ctx, number): return MainThingModel.objects.get(number=number) api = Application(services=[MainThingService], tns='http://a.tns.com/', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) Calling retrieveThing will give a response that includes all the fields from MainThing, but not the OneToOne from RelatedThing. I would like to include the "relatedthing" number in the retrieveThing response. Is there a way to do this? -
Getting None type value from ManytoMany Field in django rest framework
I cannot retrieve answer choice id in ManytoMany field in serializers list or retrieve instead I got quiz.Choice.None and I understand why is that, but if I remove answer = serializers.CharField() this line from serializer. It raised an error when creating Question: { "answer": [ "Incorrect type. Expected pk value, received str." ] } I cannot pass answer from frontend, I expected to retrieve "answer": [2,3] instead of None and I also know that if I remove answer = serializers.CharField() this line from serializer. It solves the problem, But it raises another problem that I cannot pass an answer choice id that is not even created yet. What is the best solution for this type of problem? I also tried answer validations to an empty array. But that's not working even. { "id": 5, "label": "Question 1", "answer": "quiz.Choice.None", "explanation": "New Added fhfd", "mode": 1, "subtopic": 2, "choice": [ { "id": 5, "option": "option 6 Edited New One", "question": 5 }, { "id": 6, "option": "option 5 Hllloo Sakib", "question": 5 } ] } My Model: # Question Mode MODE = ((0, "Easy"), (1, "Medium"), (2, "Hard")) class Question(models.Model): """Question Model""" label = models.CharField(max_length=1024) answer = models.ManyToManyField("Choice", related_name="quesans", blank=True) explanation … -
AttributeError: 'MovieSerializer' object has no attribute 'id' + Serialization
The perfect scenario would be to use the RatingSerializer inside the MovieSerializer but since it is below the actual mvserializer code, i cannot use it. Therefore, I started to serialize the rating object using json.dumps() and it looks very ugly after serialization. serializers.py class MovieSerializer(serializers.ModelSerializer): id = 15414 director = PersonSerializer() rating = serializers.SerializerMethodField() # I want to use here RatingSerializer() def get_rating(self, obj): r = list(Rating.objects.filter(movie_id=self.id).values())[0] r['rating'] = float(r['rating']) return json.dumps(r) class Meta: model = Movie fields = ['id', 'title', 'director', 'rating'] class RatingSerializer(serializers.ModelSerializer): movie = MovieSerializer() class Meta: model = Rating fields = ['id', 'movie', 'rating', 'votes'] result, the rating field is serialized very bad { "id": 16906, "title": "Frivolinas", "director": { "id": 2014, "name": "Iron Eyes Cody", "birth": 1907 }, "rating": "{\"id\": 1, \"movie_id\": 15414, \"rating\": 5.4, \"votes\": 12}" }, is there a way I can use RatingSerializer inside MovieSerializer? Doing this way (my way), i also cannot find the actual id in the get_rating method, i have hard coded it. -
geopy returning "Civitas Vaticana" string instead of actual city name in django
I am using geopy in django. here I am printing this dictionary from geopy and I need only city name from this dictionary: {'city': 'Singapore', 'continent_code': 'AS', 'continent_name': 'Asia', 'country_code': 'SG', 'country_name': 'Singapore', 'dma_code': None, 'is_in_european_union': False, 'latitude': 1.3024, 'longitude': 103.7857, 'postal_code': '13', 'region': None, 'time_zone': 'Asia/Singapore'} here is my code for getting city name: #views.py from geopy import Photon from .utils import get_geo def calculate_distance_view(request): distance = None destination = None obj = get_object_or_404(Measurement, id=1) form = MesurementModelForm(request.POST or None) geolocator = Photon(user_agent='measurements') ip = '185.252.221.75' country,city,lat,lon = get_geo(ip) print('location country', country) print('location city', city) print('location lat, lan ', lat,lon) location = geolocator.geocode(city) print("###",location) result I am getting: location country {'country_code': 'SG', 'country_name': 'Singapore'} location city {'city': 'Singapore', 'continent_code': 'AS', 'continent_name': 'Asia', 'country_code': 'SG', 'country_name': 'Singapore', 'dma_code': None, 'is_in_european_union': False, 'latitude': 1.3024, 'longitude': 103.7857, 'postal_code': '13', 'region': None, 'time_zone': 'Asia/Singapore'} location lat, lan 1.3024 103.7857 ### Civitas Vaticana why I am getting "Civitas Vaticana" as city name instead of Singapore. I am not seeing any kind of string like "Civitas Vaticana" in my city dictionary. how to get city name? anyone please help -
How to send data through a form for processing and prevent the page from refreshing?
I am working on my first django project and I encountered a problem that I have no idea how to solve it. I have tried various code samples but unsuccessfully. I got stuck with the following problem: I have a form which looks like the following: <form action="{% url 'cart-add' %}" method="GET" id="myform"> {% csrf_token %} <label> <input type="hidden" name="{{ product.pk }}"> <input type="number" max="{{ product.quantity }}" min="1" name="quantity" value="1"> <button type="submit" value="">Add to chart</button> </label> </form> When I hit the submit button, the handler, by default, throw me to the cart page, where data is being proccessed. For a better user experience, I want when somebody click "add to cart" button, to not be thrown to another page. For this, I have tried several JQuery and javascript code snippets that I found on internet. It is still not working properly. $(document).ready(function () { $('#myform').on('submit', function (e) { e.preventDefault(); $.ajax({ url: "https://localhost:8080/product_details/" + {{product.pk}}, type: "GET", data: $(this).serialize(), success: function (data) { $("#myform").html(data); }, error: function (jXHR, textStatus, errorThrown) { alert(errorThrown); } }); }); }); The above code is the final result, but it is still not working. NOTE: When I look into page source on browser, the following script … -
How to make id (primary key) of new created objects start from some value?
I have an existing django model in my project, and it's already in production database (PostgreSQL) and has records in it. And what I basically want is to set id (autoincrement pk) of new created objects to have at least 5 digits and start from 5. So for example if I have last record in database with id 1924 I want my next object to have id 51925 (last id + 1 + 50000). So it will be like this: older objects ... 1921 1922 1923 1924 # last in production 51925 # next object to be created must autoincrement from 50001 + previous id 51926 51927 .... and so on Is it possible and what is the best way to do it? thanks -
Uploading an Image returns 400 error using an Django api
I'm trying to upload an image from using fetch after I appended it to formdata const fd = new FormData(); fd.append("image", this.state.offerimg); console.log(fb) const requestOptions = { method: "POST", headers: { "Content-Type": "multipart/form-data", }, body: fd, }; FormData console log Django api: Im trying to store it in firebase storage and Im receiving a bad request, also I'm trying to print the file and its not printing. class AddOfferView(APIView): parser_classes = (MultiPartParser, FormParser,) permission_classes = [AllowAny] def post(self, request): image = request.FILES['image'] print(image) image = storage.child("images/image.PNG" ).put(image) return Response({'userDoc': image}, status=status.HTTP_200_OK) System check identified no issues (0 silenced). April 07, 2021 - 16:30:25 Django version 3.1.7, using settings 'loyalty_app_cms.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Bad Request: /api/add-offer [07/Apr/2021 16:30:34] "POST /api/add-offer HTTP/1.1" 400 104 [07/Apr/2021 16:40:11] "GET /add-products HTTP/1.1" 200 3032 [07/Apr/2021 16:40:11] "GET /static/js/2.2a4e2c0c.chunk.js HTTP/1.1" 304 0 [07/Apr/2021 16:40:11] "GET /static/css/main.22590eba.chunk.css HTTP/1.1" 304 0 [07/Apr/2021 16:40:11] "GET /static/js/main.7dc050bc.chunk.js HTTP/1.1" 304 0 [07/Apr/2021 16:40:13] "GET /manifest.json HTTP/1.1" 200 3032 [07/Apr/2021 16:40:14] "GET /static/css/main.22590eba.chunk.css.map HTTP/1.1" 200 2437 [07/Apr/2021 16:40:14] "GET /static/js/main.7dc050bc.chunk.js.map HTTP/1.1" 200 57177 [07/Apr/2021 16:40:14] "GET /static/js/2.2a4e2c0c.chunk.js.map HTTP/1.1" 200 1544716 Bad Request: /api/add-offer [07/Apr/2021 16:40:25] "POST /api/add-offer HTTP/1.1" 400 104 -
Converting IntegerField to ForeignKey from recovered database in Django
I'm working with a MySQL database that I connected to my django project (using python manage.py inspectdb > app/models.py) but it's not reading the relationships correctly. The ForeignKeys are IntegerFields so I cannot use the handy Django ORM lookup. Here's an example: class ChileStudents(models.Model): """ simplified version of the model """ otec = models.IntegerField(blank=True, null=True) # Here's the issue # More stuff goes here updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'chile_students' class Otecs(models.Model): """ Also a simplified version """ name = models.CharField(max_length=45, blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'otecs' As shown in the example above, the IntegerField points to the OTEC id, this is a simple one-to-many relationship. I tried converting the field into a ForeignKey like this: otec = models.ForeignKey('Otecs', on_delete=models.SET_NULL,blank=True, null=True, db_column="otec_id") But when migrating it just sets the column otec_id to NULL. Is there any way I can "convert" the field into a ForeingKey? -
Python - How to retrieve data with Django Restframework from firebase database (not the SQL db) and send to a client?
I have a Django rest API and I can perfectly fetch data from a my database to a flutter client app. But I would like to fetch data from firebase database to the client via the API. In other words I would like to send data in firebase database via my Django restframework API to the Flutter app. And I don't want to send data from my actual db SQL lite. I'm new to python and django This is what I tried so far.. views.py from rest_framework import generics from myapi import models from .serializers import ApiSerializer class ListTodo(generics.ListCreateAPIView): queryset = models.Myapi.objects.all() serializer_class = ApiSerializer class DetailTodo(generics.RetrieveUpdateDestroyAPIView): queryset = models.Myapi.objects.all() serializer_class = ApiSerializer serializer.py from rest_framework import serializers from myapi import models class ApiSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'topic', 'guides' ) model = models.Myapi models.py from django.db import models # Create your models here. class Myapi(models.Model): topic = models.CharField(max_length=200) guides = models.TextField() def __str__(self): return self.topic urls.py from django.urls import path from .views import ListTodo, DetailTodo urlpatterns = [ path('', ListTodo.as_view()), path('<int:pk>/', DetailTodo.as_view()) ] This code here retrieve a list of users that I would like to send throu API to the Flutter client app users = db.child("users").get() … -
drf ModelViewset does not validate Unique Constraint failed when unique_together is used
I am using djangorestframework==3.12.1 Here is how my code looks like:- models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=14, decimal_places=2) description = models.TextField(blank=True, null=True) def __str__(self): return self.name class Meta: unique_together = ( ("name", "user"), ) serializers.py class ProductSerializer(serializers.ModelSerializer): """serializer for Product objects.""" class Meta: model = models.Product fields = '__all__' read_only_fields = ['user',] views.py class ProductViewset(viewsets.ModelViewSet): queryset = models.Product.objects.all() permission_classes = [permissions.IsAuthenticated] serializer_class = serializers.ProductSerializer Expected Behavior The validators on the Modelserializers must raise an exception as Product with this Name and User already exists. Actual Behavior IntegrityError at /api/v1/product/ UNIQUE constraint failed: projectapp_product.name, projectapp_product.user_id How do I fix this? -
In PDF, font-face appears to be loading from URL, but is not displayed
My Django app uses WeasyPrint to generate PDFs on demand. I am using WeasyPrint 52.4 and Django 3.2. I have been using system fonts, which has been working great. Now I'm trying to use local fonts. For now, I'm loading static assets through localhost, pointing to Django's static server, so I can watch the requests come in and make sure the right things are being loaded. Here is how WeasyPrint is being called: font_config = weasyprint.fonts.FontConfiguration() css = weasyprint.CSS(url='http://localhost:8000/static/kits/static/report.css', font_config=font_config) return weasyprint.HTML( string='<h1>Hello world</h1>', encoding='utf-8', ).write_pdf( stylesheets=[css], font_config=font_config, ) Here is my CSS: @font-face { font-family: 'foobar'; src: url(http://localhost:8000/static/Oxygen-Regular.ttf) format('truetype'); font-weight: 400; } @font-face { font-family: 'foobar'; src: url(http://localhost:8000/static/Oxygen-Bold.ttf) format('truetype'); font-weight: 700; } :root { font-family: 'foobar', sans-serif; color: red; } The text is correctly colored red, so I know the CSS is being loaded. I can see from my server logs that the requests for the fonts are successful, which indicates to me that WeasyPrint is fetching the fonts correctly: 2021-04-07 09:57:32,147 INFO "GET /static/mycss.css HTTP/1.1" 200 5748 2021-04-07 09:57:32,193 INFO "GET /static/Oxygen-Regular.ttf HTTP/1.1" 200 46440 2021-04-07 09:57:32,200 INFO "GET /static/Oxygen-Bold.ttf HTTP/1.1" 200 47096 But the PDF is showing the fallback sans-serif font. What am I missing? -
How to format dinamically generated HTML with django
Im trying to create a sheet of labels to print out with a QR code a logo and phone number, the QR codes are generated sepparatly from an xlsx file and they work. my issue is formatting them in the HTML. Im not sure how to change the for loop so it creates a row for each time an image is loaded onto the label. heres the html part of the code. {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>labels</title> <style> </style> </head> <link rel="stylesheet" type="text/css" href="{% static '/css/style.css' %}"/> <table width="150" cellpadding="2" cellspacing="1"> <tr> {% for item in list_qr_images %} <img src="{% static 'inc.png' %}" align="center"/> <img src="{{ item }}" align="center"> <p style="text-align:left">(718) 280-0000</p> {% endfor %} </tr> <tr></tr> </table> </br> </html> -
Celery: How to access class-based task methods from other task?
I have implemented a class-based task that is executed periodically (celery beat) but I want to run another task (which is not periodic) after an event and call the method of the mentioned periodic task. I searched in the documentation but I didn't find. So I tried it myself and managed to solve it in the following way: class MyTaskClass(Task): def a(self): ... @shared_task(base=MyTaskClass) def periodic_task(): ... @shared_task def task(): periodic_task.a() Is this method acceptable, and is there a better one? -
How to add a dataframe to a django model (sqlite3)?
I have a data frame that has one image column and the rest character columns and is populated with 128 rows. The data in this DataFrame is scraped and will need to be continuously scraped to always have the latest records. mainline_t_shirt = pd.DataFrame({ 'Images': image, 'Titles': title, 'Prices': price, 'link': link, 'Website': 'mainlinemenswear', 'brand': brand // *not sure which file this needs to be added to }) Model in Django - /models.py class T_shirt(models.Model): image = models.ImageField() title = models.CharField(max_length=250) price = models.CharField(max_length=250) link = models.CharField(max_length=250) website = models.CharField(max_length=250) brand = models.CharField(max_length=250) Could anyone provide their expertise in showing how to move the data from the DataFrame into the sqlite3 database in Django? which file do I add this snippet of code to? -
DRF: How to find the model instance with the highest combined value of two fields?
I have a model which looks like this: class Posts(models.Model): title = models.CharField(max_length=100) creation_timestamp = models.DateTimeField(auto_now_add=True) body = models.CharField(max_length=255) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="likes",blank=True) dislikes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="dislikes",blank=True) I have added an endpoint in urls.py, so that when the url .../v1/posts/max-interaction-count is visited, the following function in views.py is run: @api_view(['GET']) def interaction_count_view(request): max_post = None max_interactions = 0 for post in Posts.objects.all(): interactions = post.likes.count() + post.dislikes.count() if interactions > max_interactions: max_post = post max_interactions = interactions return Response({"Post number " : max_post.pk, "interaction_count ": max_post.likes.count() + max_post.dislikes.count()}) This works, returning the id of the post with the maximum sum of likes and dislikes. However, I believe interaction_count_view might not be very scalable because it was written in python, rather than using built-in django methods which use SQL. Is this the case? If so, what is a better approach to counting the number of likes and dislikes associated with a post instance? -
Email field with unique constraint prevents put method of serializer from saving. django rest_framework
When creating an object in my api view it seems fine but whenever I update the object even I didn't change my email field it says user with this Email Address already exists. I am using generics.RetrieveUpdateView for my view. I thought generics.RetrieveUpdateView automatically handles this. What am I missing? my model looks like this: class User(AbstractUser): email= models.EmailField(unique=True) ... my serializer looks like this: class UserListForProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username','email','last_login', 'date_joined','is_active', 'is_student', 'is_staff', 'is_teacher', 'is_registrar', 'is_superuser'] read_only_fields = ('username','date_joined', 'last_login','is_active', 'is_student', 'is_staff', 'is_teacher', 'is_registrar', 'is_superuser') class StaffProfileDetailSerializer(CreateProfileSerializer): user = UserListForProfileSerializer(many= False) class Meta: model = StaffProfile fields = ['user','first_name', 'middle_name', 'last_name', 'gender', 'employee_number', 'date_of_birth', 'mobile_number','dob_month','dob_day','dob_year','address',] read_only_fields = ('date_joined', 'last_login',) my view looks like this: class UserProfileDetail(generics.RetrieveUpdateAPIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] serializer_class = StaffProfileDetailSerializer def get_queryset(self, *args, **kwargs): userid = self.request.user.id return StaffProfile.objects.filter(pk= userid) -
How can I use base.html like a regular template, and render to it
I have my navbar css in my base.html, and then use {% extend base.html %} to add it into my regular template. However, I want to have a login/register option in my navbar (which is in my base.html), and I want to use cookies to decide whether to put login or register in the navbar. How can I have base.html be able to request cookies, when it doesn't have a view? Also, not every webpage on my site has a view, some are a plain html with {% extend base.html %} -
Index/Dashboard/Homepage Best Practice and Customs
I'm currently developing a project to store all of my old MP3 files. This project contains multiple applications(Artist, Album, Song) and I'm simply curious to know if it is common for developers to create a separate application which may be named something like 'Dashboard' and use this to host their homepage, login/logout functionality, search features, recently uploaded items, etc. Or is it more common to just stick your homepage into an existing app? -
Insert into table from arbitrary number of checkboxes in Django
I'm building a Django application that will be used to schedule downloads. I've cleaned some government data that's pretty large, so people won't necessarily want to download all of it at the same time. They might also want to have it delivered via S3 buckets, etc. So I figured the easiest way to get the data to them would be to have a series of check boxes that iterate through what I have available and then let them press a button that would populate a database and have the server where the data they are stored on do the heavy lifting of uploading to a bucket and providing them the link, etc. Where I'm having an issue is I'm having a heck of a time figuring out how to get data from the checkboxes, of all things. Here's what I have tried so far. I've included the snippets from the files I believe to be pertinent: models.py class UserDownload(m.Model): user = m.ForeignKey( settings.AUTH_USER_MODEL, on_delete=m.CASCADE ) download_source = m.TextField(max_length=200) download_configuration = JSONField() download_queued_utc = m.DateTimeField() download_link_generated = m.DateTimeField() download_link = m.TextField() bls-download.html {% extends "base.html" %} {% load static i18n %} {% block title %}Data Sources List {% endblock title %} … -
Comment form not submitting and saving comments anymore
I am a newbie in django following a question and answer website tutorial. After loading the comment form and adding a few comments with it, I added a form for adding more answers to the same question in the details.html file and the comment form stopped submitting & saving comments. I'm not getting any error except: Uncaught SyntaxError: missing ) after argument list I after logging, I got the following error logs: DEBUG 2021-04-07 10:48:25,270 utils 17624 1040 (0.000) SELECT COUNT(*) AS "__count" FROM "main_comment" WHERE "main_comment"."answer_id" = 12; args=(12,) DEBUG 2021-04-07 10:48:25,272 utils 17624 1040 (0.000) SELECT "main_comment"."id", "main_comment"."answer_id", "main_comment"."user_id", "main_comment"."comment", "main_comment"."add_time" FROM "main_comment" WHERE "main_comment"."answer_id" = 12; args=(12,) INFO 2021-04-07 10:48:25,277 basehttp 17624 1040 "GET /detail/4 HTTP/1.1" 200 9643 WARNING 2021-04-07 10:48:25,469 basehttp 17624 1040 "GET /static/bootstrap.min.css.map HTTP/1.1" 404 1689 DEBUG 2021-04-07 10:48:37,751 utils 17624 7732 (0.000) SELECT "main_question"."id", "main_question"."user_id", "main_question"."title", "main_question"."details", "main_question"."tags", "main_question"."add_time" FROM "main_question" WHERE "main_question"."id" = 4 LIMIT 21; args=(4,) DEBUG 2021-04-07 10:48:37,756 base 17624 7732 Exception while resolving variable 'detail' in template 'detail.html'. Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'Question' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most … -
Type error when trying to fetch data Python Django
I am trying to get data from the database based on request with id u_id and x_id but I am not getting any data instead getting an error TypeError: display_data() missing 2 required positional arguments: 'u_id' and 'x_id' can you help? code def display_data(request, u_id, x_id): if request.method == 'POST': widget['data'] = Widget.objects.get(u_id = u_id, x_id = x_id) return widget