Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF APIClient Delete data arrives in request.data, not request.query_params
I use DRF's APIClient to write automated tests. And while is was writing the first delete test, I found it very strange that the data passed through arrived in request.data, while if I use Axios or Postman, it always arrives in request.query_params. Any explanation as to why this is, and preferably a method to use APIClient.Delete while the data arrives in query_params would be great! My test: import pytest from rest_framework.test import APIClient @pytest.fixture() def client(): client = APIClient() client.force_authenticate() yield client class TestDelete: def test_delete(client): response = client.delete('/comment', data={'team': 0, 'id': 54}) And my views from rest_framework.views import APIView class Comments(APIView): def delete(self, request): print(request.query_params, request.data) >>> <QueryDict: {}> <QueryDict: {'team': ['0'], 'id': ['54']}> Looked into DRF's APIClient. Feeding towards params doesn't seem to help. The delete method doesn't seem to have direct arguments that could help as well. So I'm a bit stuck. -
I am not getting expected result when I am multiplying price with quantity
I am working on a billing application. When I need to generate a bill, I open the CREATE form and I enter the quantity and price of two items. The quantity, price and total of both the items are stored in the django. suppose i want to change the quantity in Bill then i have made a similar form i call edit form. So when I edit the quantity and price of both the items in the edit form, then the first item's multiplication is getting correct but the second item's multiplication is getting wrong. You can see the problem in the rectangular box error Image <script> var item = {{itemid}}; var itemname = "{{itemname|escapejs}}"; services = itemname.replaceAll("'",'"') a =JSON.parse(services) itemid_list = '<option value="">Select Item</option>'; console.log((a)) console.log((a.length)) for(var x=0; x<item.length; x++){ itemid_list = itemid_list+ "<option value='"+item[x]+"'>"+a[x]+"</option>" } console.log(itemid_list) const maxPoints = 5; let count = 1; // Adds new point const deleteThisPoint = (target) => { target.parentNode.remove(); var sum = 0; $('input.extended_total').each(function() { var num = parseInt(this.value, 10); if (!isNaN(num)) { sum += num; } }); $("#totalcount").text(String(sum)); }; const addNewPoint = (target) => { const parentContainer = target.parentNode.parentNode; const addIn = parentContainer.querySelector('.multiple-points'); const childCounts = addIn.childElementCount; if(childCounts > maxPoints - … -
How to update post in Django with out using Django forms
I want to update a post in Django, but I don't want to use Django forms for this is there any way to do that. -
Python -Django - send rest request get http client get error - TypeError: expected string or bytes-like object
I create a Django App and send rest http request to Plaid. if I start up django alone(python manage.py run server), it works fine. But if I use Nginx + Gunicorn + Django, I will get error. The error message is: File "/var/www/sp_plaid/api/views.py", line 91, in create_link_token response = client.link_token_create(p_request) File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 769, in __call__ return self.callable(self, *args, **kwargs) File "/usr/local/lib/python3.9/dist-packages/plaid/api/plaid_api.py", line 6863, in __link_token_create return self.call_with_http_info(**kwargs) File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 831, in call_with_http_info return self.api_client.call_api( File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 406, in call_api return self.__call_api(resource_path, method, File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 193, in __call_api response_data = self.request( File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 452, in request return self.rest_client.POST(url, File "/usr/local/lib/python3.9/dist-packages/plaid/rest.py", line 264, in POST return self.request("POST", url, File "/usr/local/lib/python3.9/dist-packages/plaid/rest.py", line 150, in request r = self.pool_manager.request( File "/usr/lib/python3/dist-packages/urllib3/request.py", line 78, in request return self.request_encode_body( File "/usr/lib/python3/dist-packages/urllib3/request.py", line 170, in request_encode_body return self.urlopen(method, url, **extra_kw) File "/usr/lib/python3/dist-packages/urllib3/poolmanager.py", line 375, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 394, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 234, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "/usr/lib/python3.9/http/client.py", line 1279, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.9/http/client.py", line 1320, in _send_request self.putheader(hdr, value) File "/usr/lib/python3/dist-packages/urllib3/connection.py", line … -
IntegrityError FOREIGN KEY constraint failed - Django custom user model
I am new to creating custom user models in Django, so bear with me. My problem is that I get a IntegrityError at /admin/accounts/customuser/add/ FOREIGN KEY constraint failed when I delete a user in Django admin. This also happens when I try to add a user in Django admin. Code models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def _create_user(self, email, password, **kwargs): if not email: raise ValueError("Email is required") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError("Superuser must have is_staff True") if kwargs.get('is_superuser') is not True: raise ValueError("Superuser must have is_superuser True") return self._create_user(email, password, **kwargs) class CustomUser(AbstractUser): username = None first_name = None last_name = None email = models.EmailField(_('email address'), blank=False, null=False, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] full_name = models.CharField(_('full name'), max_length=1000, null=True, blank=True) user_id = models.CharField(_('session id'), max_length=10000, null=True, blank=True) verification_code_time = models.IntegerField(_('time left for session id'), null=True, blank=True) … -
Group name not taking spaces django-channels
I am working on a chat app with django channels, everthing is working but messages don't get send when room name has spaces or other special carachter, ideally I'd like to be possible to the user to have spaces in their room name. /* consumers.py: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from web socket async def receive(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username, 'timestamp': timezone.now().isoformat() })) @sync_to_async def save_message(self, username, room, message): if len(message) > 0: Message.objects.create(username=username, room=room, content=message) routing.py: websocket_urlpatterns = [ path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()), ] urls.py: urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] index.html: <script> document.querySelector('#room-name-input').focus(); document.querySelector("#room-name-input, #username-input").onkeyup = function(e) { if (e.keyCode === 13) { document.querySelector('#room-name-submit').click(); } }; document.querySelector('#room-name-submit').onclick = function(e) { var … -
AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint'
Sys: Windows 11 Prof; Python v3.9.7 I've tried to install Wagtail Colour Picker but I got this error message back. Do I need to install or remove something? Please Help ! models.UniqueConstraint(fields=['page'], condition=Q(status__in=('in_progress', 'needs_changes')), name='unique_in_progress_workflow') AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint' -
Is there a method to create a Django token for user objects with no last_login timestamp?
I have a Django app that contains advertisement recipients with no login timestamps (since they do not need to have an account anyways), is there a method to customize the Django default token generator to exclude the timestamp requirement? -
Strange behaviour when rendering X-Axis ticks
I'm rendering a chart with matplotlib through panda's df.plot() method, but somehow the tick labels on the X-Axis seem to be messed up. There seems to be a layer of numeric text above my "real" tick labels. I have no idea where this comes from. Strangely enough, this only happens in our production and staging environment, not in dev. Maybe it also has to do with gunicorn or django's dev server. Has somebody made this experience before? Here's the plot result: and this is the output when I clear the ticks with .set_xticks([], []): Here's a portion of my code, there's some abstraction but I think it should be understandable. self.data is a pandas dataframe. It outputs base64-encoded png data: class Line(ChartElement): def draw(self): self._plot = self.data.plot(kind='line', color=self.colors) self._rotation = 'vertical' self._horizontalalignment='center' # self._plot.set_xticks([], []) # ... class ChartElement(): # ... def base64(self): self.draw() figfile = BytesIO() if not self._plot: raise ValueError("Plot not generated.") if self._legend: self._plot.legend(self._legend, **self._legend_args) #plt.legend(self._legend, loc='upper center', bbox_to_anchor=(0.4, .05), ncol=5, fancybox=False, prop={'size': 6}) plt.setp(self._plot.get_xticklabels(), rotation=self._rotation, horizontalalignment=self._horizontalalignment, fontsize=8) self._plot.set_ylabel(self.y_title) self._plot.set_xlabel(self.x_title) #plt.figure() fig = self._plot.get_figure() fig.autofmt_xdate() if self.size and isinstance(self.size, list): fig.set_size_inches(inch(self.size[0]), inch(self.size[1])) fig.savefig(figfile, format='png', bbox_inches='tight') figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()) plt.clf() plt.cla() plt.close('all') plt.close() return figdata_png.decode('utf8') -
dictsort or dictsortreverse doesn't work second time in same template of Django, How can I do that?
Here is my template code in template.html file {% for obj in dictionary|dictsort:"name" %} do something {%endfor%} {% for obj in dictionary|dictsort:"age" %} do other thing {%endfor%} but in second iteration there is nothing hapening, on the first iteration everything is ok. -
How to achieve this type of API in Django rest framework
I am new to the Django rest framework and I am wanting to acheive this kind of API: { question_no: "1", question: "How many sides are equal in a scalene triangle?", options: [ { que_options: "3", selected: false, isCorrect: true }, { que_options: "2", selected: false, isCorrect: true }, { que_options: "0", selected: false, isCorrect: true }, ], }, How can I achieve the above type of API? I have tried to make make it work with the following code but it doesn't work: from django.db import models # Create your models here. class AnswerOptions(models.Model): option= models.CharField(max_length=500) isCorrect = models.BooleanField(default=False) class Quiz(models.Model): question = models.TextField() options = models.ManyToManyField(AnswerOptions) -
Django PDF parser on POST request
I hope for your help. Because I have been struggling with this problem for a long time. A POST request comes from the frontend with one PDF file, after which I need to take a screenshot of the first page and extract its metadata and save it all in the database. at the moment I have overridden the POST method and am intercepting the JSON which contains the PDF. I pass this file to my parsing function. But other than the file name, the function cannot find the file. What could be the problem? view import fitz as fitz from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import FileSerializer def parce_pdf(test): doc = fitz.open(test) # open document pixel = doc[0] # page pdf pix = pixel.get_pixmap() # render page to an image pix.save("media/page.png") # store image as a PNG print(doc.metadata) class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) # test = request.data['file'].content_type test = request.data['file'] # print(request.data.get) print(test) print(request.accepted_media_type) parce_pdf(test) print(file_serializer) # print(test) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer from rest_framework import serializers from .models import File class … -
Django admin wont let me log in with a custom user model
I've done a custom user model and when I try to log in to django admin it says "Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.". I've tried creating a superuser using python manage.py createsuperuser but it returns: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 61, in execute return super().execute(*args, **options) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 156, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' I've tried creating a user through CustomUser.objects.create(email=email, ...) I've tried checking if it is a staff, superuser and active. All of these returned True. Code Models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ class CustomUser(AbstractUser): username = None first_name = None last_name = None email = models.EmailField(_('email address'), blank=False, null=False, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] full_name = models.CharField(_('full name'), max_length=1000, null=True, blank=True) user_id = models.CharField(_('session id'), max_length=10000, … -
Why Inline elements are disappearing when I use a filter through the get_queryset() in model.Admin?
I have a problem with Inline elements disappearing. It is linked to my overriding of get_queryset. I don't understand the mechanism which is behind. Any help would be great. I have two models like this : class Aventure(models.Model): title = models.CharField(max_length=30) sub_title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) archive = models.BooleanField(default=False) def __str__(self): return self.title class Scene(models.Model): title = models.CharField(max_length=30) description = models.TextField() aventure = models.ForeignKey(Aventure, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title And two model.Admins like this : class AventureAdmin(admin.ModelAdmin): readonly_fields = ('author',) list_display = ('title', 'author',) inlines = [ SceneInline, ] # allow to save the logged in user to be set has the author def save_model(self, request, obj, form, change): # dans le cas où l’utilisateur n’est pas renseigné if getattr(obj, 'author', None) is None: obj.author = request.user obj.save() # Allow to show only the 'Aventure' instances where the author is the logged in user. def get_queryset(self, request): qs = super().get_queryset(request) print(qs) if request.user.is_superuser: return qs return qs.filter(author=request.user) class SceneInline(admin.TabularInline): list_display = ('title', 'author',) model = Scene show_change_link = True extra = 0 fields = ('title', 'author') And when the queryset is filtered on the author (means I am not superuser), the inline scene elements … -
How can we check on every login using stripe, Is payment of that specific user is successful?
How can we check on every login using stripe in DJANGO, Is payment of that specific user is successful? Because you know sometimes the payment is disrupted by the client or it may get unsuccessful after some time of successful payment of some reasons? -
Django - Wagtail: How to add classes to generated HTML elements from RichTextField
Using Wagtail 2.16.1, I have a BlogPage model that contains a body field which is a RichTextField. When I put {{ page.body|richtext }} into the template, the HTML that is rendered contains various html elements, as expected. I'd like to specify (tailwind) classes for these elements. E.g. every <p> element in a richtextfield should have <p class="mx-2 my-3">, h2 elements should have <h2 class="mt-5">, etc. -
Cannot add Django range filter to template
I am trying to get working the range-slider code from https://hackernoon.com/django-tutorial-creating-a-range-slider-filter-tt28359e I have got as far as creating views, models, templates adding some data to the Peoples model and displaying it. The code that works correctly displays the data from People model in a simple table. However, I cannot get the filter working. I have had to change some names in the sample code because of name conflicts with pre-existing items in my existing Django application. The first set of code works to display all the records from the model Peoples: #views.py from .models import People from .filters import PeopleFilter def Peopleindex(request): # display all the records from the People model/table all_people = People.objects.all() return render(request, 'pollapp2/Peopleindex.html', {'all_people':all_people}) template: <table border='1' style="width:50%; text-align:center"> <thead> <tr> <th> Name </th> <th> Surname </th> <th> Age </th> </tr> </thead> <tbody> {% for person in all_people %} <!-- for person in all_people --> <!-- for person in people_filter.qs --> <tr> <td> {{ person.name }} </td> <td> {{ person.surname }} </td> <td> {{ person.age }} </td> </tr> {% endfor %} </tbody> </table> The above correctly displays in an HTML table, all records from the Peoples model. Then when I try to modify the code to … -
Django multi-domain view set up / Django Sites. help needed
I'm trying to understand how to set up a Multisite codebase with Django (no external addons like Wagtail). I created several dummy domains and registered them on etc/hosts "example.com", "example2.com". They now both respond as if it's "localhost". I'm trying to find a way to make them go to different pages/views according to their different domains. I went through https://docs.djangoproject.com/en/4.0/ref/contrib/sites/ Sites documentation and am still stuck. The view that I'm trying to make work is this: def my_view(request): # current_site = request.get_host current_site = Site.objects.get_current() if current_site.domain == 'example2.com': html = "<html><body>Hello World at Example2 two</body></html> " + "current_site.domain=" + current_site.domain Site.objects.clear_cache() return HttpResponse(html) pass elif current_site.domain == 'example.com': html = "<html><body>Hello World at Example1 one</body></html> " + "current_site.domain=" + current_site.domain Site.objects.clear_cache() return HttpResponse(html) pass else: html = "<html><body>Hello World</body></html> " + "current_site.domain=" + current_site.domain Site.objects.clear_cache() return HttpResponse(html) pass I also tried changing the domain like below(It was done within a python shell within a pipenv shell), however it doesn't change it automatically by the domain address and will set it permanently to whichever one I saved: ((django-todo-react) ) ➜ backend git:(master) ✗ ./manage.py shell Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", … -
What are the risk for Secret KEy in Django?
I have a question regarding Django and Secret Key. Unfortunately, I've did a commit to a public repositary with secret key visible. Then I got a message: GitGuardian has detected the following Django Secret Key exposed within your GitHub account. I then immediatelly deleted this repo from my github but still worried if something can happen to me. The app was just hello world on my localserver. I red some articles that it is very dangerous but I am not sure if someone can hack me by this. Can you advise? Thanks. -
Django-Reactjs : No Access-Control-Allow-Origin header is present on the requested resource
I'm trying to load an image from an image url and try to crop that image. Access to image at 'https://example.com/image.png' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I'm using React and Django. app.js import { useState,useCallback,useRef, useEffect} from 'react'; import React, { Component } from "react"; import ReactCrop from "react-image-crop"; import 'react-image-crop/dist/ReactCrop.css' function App() { const [crop, setCrop] = useState({ aspect: 1.7777777777777777, height: 84.92083740234375, unit: "px", width: 325.97037760416663, x: 0, y: 140.07916259765625} ); function onImageLoad() { const image = new Image(); image.src = "https://example.com/image.png"; image.crossOrigin = "Anonymous"; const canvas = document.createElement('canvas'); const scaleX = image.naturalWidth / image.width; const scaleY = image.naturalHeight / image.height; const ctx = canvas.getContext('2d'); const pixelRatio = window.devicePixelRatio; canvas.width = crop.width * pixelRatio * scaleX; canvas.height = crop.height * pixelRatio * scaleY; ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); ctx.imageSmoothingQuality = 'high'; image.onload = function() { ctx.drawImage( image, crop.x * scaleX, crop.y * scaleY, crop.width * scaleX, crop.height * scaleY, 0, 0, crop.width * scaleX, crop.height * scaleY ); } const base64Image = canvas.toDataURL("image/jpeg", 1); setResult(base64Image); console.log(result); } useEffect(() => { onImageLoad(); }, []); return ( { result && <div> <h2>Cropped Image</h2> <img alt="Cropped Image" src={result} … -
'Connection aborted.', ConnectionResetError 10054 error in django while trying to make a post request with files
I'm working on a django project for which I'm using an external API service. I have to send image files in the payload as well. When making a post request to the service, I'm getting this error: ConnectionError ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) Some key points are: The request works perfectly fine on Postman. The error appears only when I attach FILES in the payload, without which it works fine. -
Accessing the "many" side from the "one" side effectively
Considering the following models: class ManySide(django.db.models.Model): one_side = models.ForeignKey( to=OneSide, on_delete=models.PROTECT, related_name="related_one_side" ) class OneSide(django.db.models:model): # not containing any field relevant here def many_side_elements(self): pass # ? What should I include in method many_side_elements so that calling it from a OneSide Model instance would list a queryset of ManySide elements? Official docs imply that given o is a OneSide isntance, o.many_side_set.all() should work but it returns an error in shell. My current solution is the following: from django.apps import apps [...] def many_side_elements(self): ManySideModel = apps.get_model('<app_name_here>', 'ManySide') val = ManySideModel.objects.filter(one_side=self) But I'm concerned it's ineffective since it requires importing the other Model. Actually it caused a circular dependency error message in my project, hence the get_model usage. Is there any better way? Or xy_set should work in the first place? Then what am I doing wrong? -
No module named '_overlapped'
Working on a masters project and a fellow course mate has developed a web application using Django on a windows computer and has sent the file to us. I am trying to run the server on my MacBook terminal but when I run it, get the error "ModuleNotFoundError: No module named '_overlapped'. I have installed trollius as recommended in a previous post but hasn't worked for me. any help? -
The value I got from the jQuery is NoneType in django
I want to implement a function that updates the graph and displays the number of updates when the button is pressed. However, when I try to get the parameter in view.py using jQuery, it returns NoneType instead of the intended value. What is the problem? Also, I don't know if this is related, but when I use console.log() in a jQuery function, there is no output on the console of the browser developer tools. This doesn't seem to have anything to do with the error-only mode or the filter I entered in Console. The error is TypeError at /graph/update_graph int() argument must be a string, a bytes-like object or a number, not 'NoneType' Thank you. Here is the code views.py from xml.etree.ElementInclude import include from django.shortcuts import render from django.http import JsonResponse from . import graphdata def index(request): fig = graphdata.get_scatter_figure() plot_fig = fig.to_html(fig, include_plotlyjs=False) return render(request, 'graph/index.html', {'graph':plot_fig}) def update_graph(request): graph = graphdata.get_scatter_figure() grahp_html = graph.to_html(graph, include_plotlyjs=False) cnt = int(request.POST.get('count')) # <-- This is the error point cnt += 1 data = { "graph": grahp_html, "count": cnt, } return JsonResponse(data) index.html <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <!-- plotly JS Files --> <script … -
Two forms, one view, one ONE-TO-MANY relationship, how to get the id, the FK - DJANGO
First of all, just a disclaimer, i'm only posting because none of the topics here on the stack helped me, not even the related suggestions when i named this topic... I'm new to django, I'm working on opening a support ticket, I've been struggling with this problem for two days.... Is it possible to assign a value to the field defined in model.py by view.py? My problem is having two model classes, two forms with one-to-many relationship, which are rendered on the same page and must be saved when clicking a button only My models: class Ticket(models.Model): objects = None user_id = models.ForeignKey(User, null=False, blank=False, on_delete=models.DO_NOTHING) created_at = models.DateTimeField('Created at', auto_now_add=True) class MessageTicket(models.Model): objects = None ticket_id = models.ForeignKey(Ticket, null=False, blank=True, on_delete=models.DO_NOTHING) status = models.CharField(default=TicketStatus.TO_DO) content = models.TextField(null=True, default='') The point here is that 'ticket_id' in the 'MessageTicket' class should receive the 'id' of the last 'Ticket' saved, but as both are saved at the same time I'm not able to pull the last 'id' of the 'ticket'. My view, where saved in the database: As I said above I went through some forums and tried some things (in second 'IF'), I didn't leave them here to keep the code …