Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Override Settings for Tests of Django Rest Framework Throttling
I'm trying to test a custom user throttling: def get_user_rate(user): # Returns tupple (user plan quota, total seconds in current month) class SubscriptionDailyRateThrottle(UserRateThrottle): # Define a custom scope name to be referenced by DRF in settings.py scope = "subscription" def __init__(self): super().__init__() def custom_throttle_success(self): """ Inserts the current request's timestamp along with the key into the cache. """ self.history.insert(0, self.now) self.cache.set(self.key, self.history, self.duration) return True def allow_request(self, request, view): """ Override rest_framework.throttling.SimpleRateThrottle.allow_request Check to see if the request should be throttled. On success calls `throttle_success`. On failure calls `throttle_failure`. """ if request.user.is_authenticated: limit, duration = get_user_rate(request.user) # Override the default from settings.py self.duration = duration self.num_requests = limit self.key = self.get_cache_key(request, view) if self.key is None: return True self.history = self.cache.get(self.key, []) self.now = self.timer() # Drop any requests from the history which have now passed the throttle duration while self.history and self.history[-1] <= self.now - self.duration: self.history.pop() if len(self.history) >= self.num_requests: return self.throttle_failure() return self.custom_throttle_success() In settings.py I have added a default throttle rate of 10/second just for security (it is passed first on DEFAULT_THROTTLE_CLASSES): REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.UserRateThrottle', 'api.throttling.SubscriptionDailyRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'user': '10/second', … -
Wagtail: Dynamically load StreamField blocks in the admin EditView
I have a use case where we need dynamic blocks for a StreamField. Unfortunately this doesn't seem possible, since block types are specified in the model's StreamField field. I dug through the FieldPanel, StreamBlock and GroupPanel code and cannot clearly find a way to override the available blocks for the StreamField outside the model definition. This is my current admin EditView, where you can see what I'm trying to accomplish (see the NOTE/FIXME comments below: class EditProductView(EditView): def get_edit_handler(self): summary_panels = [ FieldPanel('title'), FieldPanel('description'), FieldPanel('body'), ] attributes_panel = [ # NOTE/FIXME: This is where we need the custom blocks to load, based # on `self.instance.product_type`. FieldPanel('attributes'), # StreamFieldPanel (which is deprecated) does not work because you can # only set the blocks within the model, when defining the StreamFieldPanel. # I would love to be able to do something like: StreamFieldPanel('attributes', block_types=[ ('test', blocks.CharBlock()), # Like this for example ]) ] settings_panels = [ FieldPanel('categories'), StateMachinePanel('state', sm_prop='sm', heading="State"), ] return TabbedInterface([ ObjectList(summary_panels, heading='Summary'), ObjectList(attributes_panel, heading='Attributes'), ObjectList(settings_panels, heading='Settings'), ]).bind_to_model(self.model_admin.model) Is it possible to override available StreamField blocks in this way, or are there potential issues with json_field DB integrity? -
ensure_csrf_token is not setting the csrf cookie in cookies tab
I have this simple generic view: class GetCSRFToken(views.APIView): permission_classes = [AllowAny, ] @method_decorator(ensure_csrf_cookie) def get(self, request, format=None): return Response('csrf is set') and then, in react, i have this code: useEffect(()=>{ axios.get('http://127.0.0.1:8000/csrf/').then((res)=>{ console.log(res.data) }) },[]) so when react render the component that has the effect above, csrf token is not set in the application tab in cookie section why is that?? -
How to put an object model that has a link as an attribute in a table cell in django
I am doing a simple web page using django. So i have a table that has a list of articles, each article has name, id, summary and link. The idea is to make the article name as a link when you show it up in the table: <table class="table table-striped table-bordered table-hover table-condensed" style="font-family: Arial, Helvetica, sans-serif"> <thead> <tr> <th>Name</th> <th>Id</th> <th>Summary</th> </tr> </thead> <tbody> {% for article in articles %} <tr> <td>{{<a href=article.link>article.name</a>}}</td> <td>{{ article.Id}}</td> <td>{{ article.summary}}</td> <td><a href="{% url 'editArticle' article.id %}">Edit</a> <a href="{% url 'eraseArticle' article.id %}">Delete</a></td> </tr> {% endfor %} </tbody> </table> But then this error appears: Could not parse the remainder: 'article.name' from 'article.name' -
How to use Django ORM to find dangling records?
How would one use the Django ORM to write something similar to the following SQL: SELECT * FROM entities WHERE NOT EXISTS (SELECT 1 FROM apples WHERE apples.entity_id = entities.id) AND NOT EXISTS (SELECT 1 FROM oranges WHERE oranges.entity_id = entities.id) AND NOT EXISTS (SELECT 1 FROM bananas WHERE bananas.entity_id = entities.id) I have several meta tables that refer to an actual record with details but it's possible for those records to have no references, in which case they're "dangling". The problem is that there's over 100 million records so a simple exclude using an in filter doesn't work: Entity.objects.exclude(userid__in=Apple.objects.all().values_list('entity_id')) The SQL statement using NOT EXISTS, on the other hand, executes at lightning speed. I'm currently on Django 2.2 (with plans to upgrade to 4.x within a year). -
Fetch call of 'PUT' method in Django produces a 500 status error
When I try to make a fetch "PUT" request, but no matter what it returns 500 status (Internal Server Error) error. I've been trying to fix this error now for hours, but honestly have no idea what is the actual problem. Here is my code:Index.js (only a useful chunk of it) document.querySelectorAll(".bi").forEach(function (icon) { icon.addEventListener("click", (event) => like(event)); }); function like(event) { const target = event.target; const parent = target.parentElement.parentElement; const id = parent.className.slice(-1); const count = parent.querySelector("#like-count"); const number = parseInt(count.innerText); console.log(`${number+1}`); fetch(`/like`, { method: "PUT", headers: { "X-CSRFToken": getCookie("csrftoken"), "Content-Type": "application/json", }, body: JSON.stringify({ 'id': id, }), }) .then(response => console.log(response)) .then(data => { console.log(data); /* console.log(data.like); if (data.like) { target.id = "icon-svg"; count.innerText = `${number - 1}`; } else { target.id = "icon-svg-q"; count.innerText = `${number + 1}`; } */ }) .catch(error=>console.log(error)); } views.py (only a useful chunk of it) @login_required def like(request): if request.method == 'PUT': js = json.loads(request.body) id = int(js['id']) post=Post.objects.get(pk=id) _user =request.user liked=False for i in post.likes.all(): if i.user == request.user: liked=True if not liked: try: f = Like.objects.get(user=_user, post=post) return JsonResponse({ "result":False, "like":liked }, status=400) except Like.DoesNotExist: f = Like(user=_user, post=post) f.save() return JsonResponse({ "result":True, "like":liked }, status=200) else: try: f = … -
Dynamically create objects from queryset
I have a project running Django and folium. I have unknown list of categories and I need to add markers on a map according to its category. current_map = folium.Map(location=(0, 0), zoom_start=6) # a layer marker will be placed in layer_1 = folium.FeatureGroup(name="Category name 1").add_to(current_map) c = Category.object.all() markers = Marker.objects.all() for marker in markers: folium.Marker( location=(marker.latitude, marker.longitude), popup=folium.Popup(html=popup_html(marker), max_width=280, max_height=320), icon=folium.Icon( color=marker.category.color, icon=marker.category.icon.name, prefix="fa", ), tooltip=marker.category.name, ).add_to(layer_1) This code is OK for one or two categories, but if I have 100 categories then I need to do something like this: layer_1 = folium.FeatureGroup(name="Category name 1").add_to(current_map) layer_2 = folium.FeatureGroup(name="Category name 2").add_to(current_map) ... layer_99 = folium.FeatureGroup(name="Category name 99").add_to(current_map) for marker in markers: folium.Marker( # code omitted tooltip=marker.category.name, ).add_to( # if layer_n.layer_name == marker.category.name than add this marker to layer_n ) I tried this way, but it did not work as I need: def layer(name, to): return folium.FeatureGroup(name=name).add_to(to) for marker in markers: folium.Marker( # code omitted tooltip=marker.category.name, ).add_to(layer(marker.category.name, current_map)) How to make this correct? -
Django: tinymce: Export database data field with text and image to a word file using python-docx
I was using "tinymce" because it allows me to introduce text and image (because I need to write information and show an image), using python-docx library I can export it but when I see my word I don't see an image just the code of the image and HTML tags. My goal is export to a word file the same image and text that I introduced to the database field. Can you help me please? Views.py ''' from docx import Document from docx.shared import Inches, Pt, Mm from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.enum.text import WD_BREAK mi_empresa = mis_empresas.objects.get(id=empresa_id) project = Proyecto.objects.get(id=proyecto_id) vulnerabilidades = Vulnerabilidad_PoC.objects.all().filter(id=proyecto_id) if mi_empresa.cod_empresa == "cod_mi_empresa": ################################################################################# # Document # ################################################################################# document = Document() section = document.sections[0] section.page_height = Mm(297) section.page_width = Mm(210) section.left_margin = Mm(25.4) section.right_margin = Mm(25.4) section.top_margin = Mm(25.4) section.bottom_margin = Mm(25.4) section.header_distance = Mm(12.7) section.footer_distance = Mm(12.7) # Get the user's fullname # Cabezera document_elements_heading = document.add_heading("Titulo con vinheta para que salga en el indice") document_elements_heading.alignment = WD_ALIGN_PARAGRAPH.CENTER # Add empty paragraph document.add_paragraph( "DataName1" + str(project.var1) + "\n" "DataName2 " + str(project.clientes_encargados) + "\n" ) for vuln in vulnerabilidades: document.add_heading(str(vuln.proyecto_id)) ################################################################################# # End of the document # ################################################################################# document_data = io.BytesIO() document.save(document_data) document_data.seek(0) response … -
How to include related model via queryset Django?
I have two models. Post and PostAction. When a user clicks the like button, PostAction will be created. But I have a problem. How can I include the PostAction model in the Post model? MODELS class Post(models.Model): description = models.CharField(max_length=2056) posted_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.FileField(upload_to=path_and_rename, blank=True) created_date = models.DateTimeField(default= datetime.now) class PostAction(models.Model): action_number = models.IntegerField(default=0) # default (0) is for like action. (1) is for saving post date = models.DateTimeField(default=datetime.now) user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="acted_user") post = models.ForeignKey(Post,on_delete=models.CASCADE, related_name="post_for") QUERY # order by descending posts and take take_count posts for initializing take_count = 10 posts = Post.objects.order_by("-created_date")[:take_count].annotate(total_likes=F('post_for')) #?? HTML <div class="card_center my-3"> <span class="card_description">{{post.description}}</span> <b>{{post.total_likes}}</b> </div> -
Concept of changing a user's email
I have a question about the very concept of changing a user's email. It's just a concept without code. When the user wants to change email, he goes to settings and click button "Send a link to change email". After that I am sending a message to user's email which contains link with a token to change email. Link looks like this: {{domain}}/new-email/{{uid}}/{{token}}. On this page user can put the new email and now here is my question: I need to send another message to the new mail with a link to check if that new mail is real. My user model contains just current email field. I need to remember somewhere the new mail so after user click the activation link inside message, the email field will be replaced by the new mail. Where should I store the new mail? Should I create a new field inside user model (replace email by current_email and add new_email) and after user click the activation link the current_email will be replaced by the new_email value and new_email will be set to null again? Or maybe should I store the new mail inside token (which will be inside the activation link URL) without … -
convert multiple files from base64 to pdf in memory
I am receiving several files in base64 format and I need to upload them to aws s3 in pdf format but so far I have tried everything and I still can't do it, is there any way to convert them to pdf without creating a file? i'm using django rest framwork "balance":"base64String", "stateOfCashflow":"base64String", "financialStatementAudit":"base64String", "managementReport":"base64String", "certificateOfStockOwnership":"base64String", "rentDeclaration":"base64String", -
Is there a Django setting, that can prevent javascript from calling external API
I manage a Django project collaborating with different front end programmers. Sometimes in my html template I have <script src="https://example.com/script.js"></script> Is there a way that I in my settings.py define whitelisting external domains that can be called. In this example, if example.com is not whitelisted, calling to that domain should be prevented. -
psycopg2.Operational€rror: connection to server at "127.0.0.1", port 5432 failed: Connection refused
Hello friends and mentors, am trying to deploy a project and these are the error I am facing when I run python manage.py migrate on digital ocean Note that am using windows, most of the commands as PostgreSQL is concerned don't run, I try to fix that with Cygwin but I still can't run them, I have git bash, obuntu WSL but there are commands I cant still, hey I am still rookie 🙈, I will so much appreciate any help for example when i run service postgresql start this in any of those terminal i get bash: service: command not found apps@cajetanglobal-66bd7dcc9b-2jjtd:~$ python manage.py migrate Traceback (most recent call last): File “/workspace/.heroku/python/1ib/python3.10/site-packages/django/db/backends/base/base.py”, line 219, in ensure_connection self.connect() File "/workspace/.heroku/python/1ib/python3.10/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File “/workspace/.heroku/python/1ib/python3.10/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File “/workspace/.heroku/python/1ib/python3.10/site-packages/django/utils/asyncio.py”, line 33, in inner return func(*args, **kwargs) File “/workspace/.heroku/python/1ib/python3.10/site-packages/django/db/backends/postgresql/base.py”, line 18 7, in get_new_connection connection = Database.connect(**conn_params) File "/workspace/.heroku/python/1ib/python3.10/site-packages/psycopg2/init.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync psycopg2.Operational€rror: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? The above exception was the direct cause of the following exception: I … -
Is there a way in Django to mask link in navbar according to the loaded template?
I would like to do a simple thing in Django but cannot find the "Django" way to do it and I am sure that there is one. Let's imagine I have a simple navbar as follow: <ul> <li> <a href="{% url 'home-index' %}">Home</a> </li> <li> <a href="{% url 'blog-index' %}">Blog</a> </li> </ul> When I am at the 'blog-index' url, I want to hide this specific link in the navbar. Thanks for your help -
How to display an item from a dataframe in html by django?
I'm using Django and I'm using the following structure for the database: class Main(models.Model): date = models.DateTimeField(default=datetime.datetime.now()) timestamp = models.DateTimeField(auto_now_add=True) main_title = models.CharField(max_length=100) title = models.CharField(max_length=100) changeover_time = models.FloatField() cycle_time = models.FloatField() available_time = models.FloatField() FPY = models.FloatField() class Meta: ordering = [Lower('title')] def __str__(self): return self.title -- In my VIEWS I have the following code: def home(request): item = Main.objects.all().values() df = pd.DataFrame(data=item) df_gb = df.groupby(['title']).agg( {'cycle_time': 'mean'}) mydict = { "df": df_gb.to_html() } return render(request, 'teste.html', context=mydict) -- In my Html Template (teste.html) I have the following code: {% extends 'base.html' %} {% load static %} {% block 'body' %} <ul class="list-group"> <li class="list-group-item">C/O: <span class="badge bg-primary rounded-pill">{{df|safe}} </ul> {% endblock %} -- The results are : C/O: cycle_time title Product Conference 2.0 Product Descharging 7.0 Storing 1.0 Typing 3.5 buying 3.0 -- Displays all averages, using all data from my database, filtering by titles. it works ok But I need to display in the html a data relative to a title. For example, I want to display only the average relative to the title "Typing" I've already tried using for and I can't display this value isolated in my HTML . -- {% extends 'base.html' %} {% … -
Using variables across django templates 2
I have a program that i upload a word document and the document is converted into an html page. I'm using docx2txt to get the images and text from the document. This saves the images to a tempImages folder. I'm trying to then go through this folder and save the images to a django database. Everything else is working fine but django is not saving the images in the correct folder. please help -
Postgres suddenly raise error '/usr/lib/libpq.5.dylib' (no such file)
when I run Django project or any code related to Postgres : Referenced from: '/Users/mahmoudnasser/.local/share/virtualenvs/wyspp_backend-PwdII1PB/lib/python3.8/site-packages/psycopg2/_psycopg.cpython-38-darwin.so' Reason: tried: '/opt/homebrew/opt/postgresql/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file) I tried many solutions online but none of them worked. Note: I use MacOS -
I want to pass user upload image directly another function for extract text in dingo
views.py def index(request): # lastimage = Imageadd.objects.latest('image') # print(lastimage) # imagefile = lastimage.image # image = cv2.imread(imagefile) if request.method == 'POST' and request.FILES['pic']: image = request.FILES['pic'] # image = cv2.imread(image) # print(image) de = Detect_Text(image) # t = all_text(de) # print(t) obj = Imageadd(image=image) obj.save() return redirect('index') return render(request,'index.html') ex.py def Detect_Text(image_file): def rotate( image: np.ndarray, angle: float, background: Union[int, Tuple[int, int, int]] ) -> np.ndarray: old_width, old_height = image.shape[:2] angle_radian = math.radians(angle) width = abs(np.sin(angle_radian) * old_height) + abs(np.cos(angle_radian) * old_width) height = abs(np.sin(angle_radian) * old_width) + abs(np.cos(angle_radian) * old_height) image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) rot_mat[1, 2] += (width - old_width) / 2 rot_mat[0, 2] += (height - old_height) / 2 return cv2.warpAffine(image, rot_mat, (int(round(height)), int(round(width))), borderValue=background) image_0 = cv2.imread(image_file) grayscale = cv2.cvtColor(image_0, cv2.COLOR_BGR2GRAY) resize = cv2.resize(grayscale, None, fx=0.8, fy=0.8) angle = determine_skew(resize) rotated = ndimage.rotate(resize, angle, reshape=True) rotated2 = ndimage.rotate(rotated, -0.5, reshape=True) success, encoded_image = cv2.imencode('.jpg', rotated2) # cv2.imshow("", rotated2) # cv2.waitKey(0) content = encoded_image.tobytes() image = vision.Image(content=content) response = client.text_detection(image=image) document = response.full_text_annotation bounds = [] for page in document.pages: for block in page.blocks: for paragraph in block.paragraphs: for word in paragraph.words: for symbol in word.symbols: x = symbol.bounding_box.vertices[0].x y = symbol.bounding_box.vertices[0].y … -
django module installed by python pip not found for apache mod wsgi python version
my apache log shows AH00163: Apache/2.4.52 (Ubuntu) OpenSSL/3.0.2 mod_wsgi/4.9.0 Python/3.10 configured and when i start python3 repl Python 3.10.6 (main, Aug 10 2022, 11:40:04) [GCC 11.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django_tgbot >>> django_tgbot <module 'django_tgbot' from '/home/admin/.local/lib/python3.10/site-packages/django_tgbot/__init__.py'> but the python3.10 started by mod wsgi cannot load the module in django [Mon Sep 26 20:47:58.471013 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] mod_wsgi (pid=294801): Failed to exec Python script file '/var/www/django/tgweb/tgweb/wsgi.py'. [Mon Sep 26 20:47:58.471122 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] mod_wsgi (pid=294801): Exception occurred processing WSGI script '/var/www/django/tgweb/tgweb/wsgi.py'. [Mon Sep 26 20:47:58.473468 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] Traceback (most recent call last): [Mon Sep 26 20:47:58.473563 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] File "/var/www/django/tgweb/tgweb/wsgi.py", line 19, in <module> [Mon Sep 26 20:47:58.473579 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] application = get_wsgi_application() [Mon Sep 26 20:47:58.473599 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] File "/usr/local/lib/python3.10/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Sep 26 20:47:58.473610 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] django.setup(set_prefix=False) [Mon Sep 26 20:47:58.473628 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] File "/usr/local/lib/python3.10/dist-packages/django/__init__.py", line 24, in setup [Mon Sep 26 20:47:58.473639 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] apps.populate(settings.INSTALLED_APPS) [Mon Sep 26 20:47:58.473656 2022] [wsgi:error] … -
Inherit model or make separate ones?
I have a model called "Phones" which has: screen size, RAM, etc. I have another one called "Laptops" which has: screen size, RAM, and Keyboard (QWERTZ, QWERTY, etc.). I could make a main model with basic fields like Name and Price. I want to just select a "Laptop" or a "Phone", without having unnecessary fields (e.g.: keyboard type for phones, or rear camera for laptops). Should I make all fields and leave unneeded ones empty (would look silly to have "RAM" and "Keyboard type" and "Rear camera mpx" for a Mug)? Or should I make separate models for each? But then how could I combine query results (search for "Xiaomi" returning from the different models like phones, laptops, bikes, vacuum cleaners, etc.)? -
Why are my requests forbidden in production but works fine on my local server?
I deployed my website on railway.app just 2 days ago, but earlier today I noticed I can't submit any forms to the server. I just get a 403 error (Forbidden). But I can submit forms when it is running on my local host (127.0.0.1). I am using Django and this is how my html looks like: <form id="subscribe"> {% csrf_token %} <div class="mb-3"> <input id="email" name="email" type="email" placeholder="Enter E-mail"> </div> <input type="submit" value="subscribe"> </form> I submit the form using (pure) JavaScript, I do this so the page doesn't reload. Here's my JavaScript code: document.querySelector("#subscribe").onsubmit = event => { event.preventDefault(); subscribe(); } function subscribe() { if (document.querySelector("#email").value === "") { return false; } else { const email = document.querySelector("#email").value; } const aj = new XMLHttpRequest; const csrfToken = document.querySelector("input[name='csrfmiddlewaretoken']").value; aj.onreadystatechange = () => { if (aj.readyState === 4) { if (aj.status === 409) { // Do something console.log("Conflict"); } else if (aj.status === 200) { // Do something console.log("Success") } else { // Do something console.log(`${aj.status} error occurred!`); } } } data = JSON.stringify({ email: email }); aj.open("POST", "/subscribe", true); aj.setRequestHeader("Data-type", "json"); aj.setRequestHeader("Content-type", "application/json"); aj.setRequestHeader("X-CSRFToken", csrfToken); aj.send(data); } I do not think it is necessary for me to share my code … -
Django How to see the session data insted of the object reference
Im trying to start using session in django, Im trying to see the data in my session but im just getting the object reference not the data console: <cart.cart.Cart object at 0x7f6994753160> views.py def cart_view(request): cart = Cart(request) print(cart) if request.user.is_authenticated: return render(request, 'cart/cart_page.html') else: return redirect('account:login') cart.py class Cart: def __init__(self, request): self.session = request.session cart = self.session.get('cart') if not cart : cart = self.session['cart'] = {} #cria a sessão cart self.product = cart -
function print doesn't work in skulpt.min.js on django
I try to use skulpt in my django project i'm testing juste the instruction : print("hello") like this: <script src="{% static 'js/skulpt.min.js' %}" type="text/javascript"></script> <script src="{% static 'js/skulpt-stdlib.js' %}" type="text/javascript"></script> function runit(prog) { // var prog = document.getElementById("yourcode").value; // var mypre = document.getElementById("output"); // mypre.innerHTML = ''; prog = prog; prog = "print('hello')"; Sk.canvas = "mycanvas"; Sk.pre = "output"; Sk.configure({ output: outf, read: builtinRead, __future__: Sk.python3 }); try { var mypre = document.getElementById("output"); mypre.innerHTML = ""; eval(Sk.importMainWithBody("<stdin>", false, prog)); } catch (e) { // alert(e.toString()) var mypre = document.getElementById("output"); mypre.innerHTML = mypre.innerHTML + e.toString(); } } function outf(text) { var mypre = document.getElementById("output"); var bonneReponse = document.getElementById("trace_output").value.replace("&nbsp", " "); mypre.innerHTML = mypre.innerHTML + text; } } function builtinRead(x) { if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined) throw "File not found: '" + x + "'"; return Sk.builtinFiles["files"][x]; } ExternalError: TypeError: Cannot read properties of undefined (reading 'write') on line 1 when i switch to python 2 using skulpt.js instead of skulpt.min.js it works -
Live search in Django admin?
How would I implement live search in Django's admin panel? I want the change_list page to function with Ajax and return the search results without refreshing the page. Does Django expose any ModelAdmin methods that can implement such behaviour? I.e. change the response type from a regular HttpResponse to JsonResponse? -
DRF post nested object
I`m trying to post this json object { "name": "Country Name", "description": "Description here...", "generalInfo": { "capital": "Capital", "population": "Population", "highestPeak": "HighestPeak", "area": "Area" }, "timelineData": [ { "name": "Name 1", "ruler": "Ruler", "dateStart": "dateStart", "dateEnd": "dateEnd", "description": "description" }, { "name": "Name 2", "ruler": "Ruler", "dateStart": "dateStart", "dateEnd": "dateEnd", "description": "description" }, { "name": "Name 3", "ruler": "Ruler", "dateStart": "dateStart", "dateEnd": "dateEnd", "description": "description" } ] } But I`m receiving this error ValueError at /countries/ Cannot assign "OrderedDict([('capital', 'Capital'), ('population', 'Population'), ('highestPeak', 'HighestPeak'), ('area', 'Area')])": "Country.generalInfo" must be a "GeneralInfo" instance. Request Method: POST Request URL: http://127.0.0.1:8000/countries/ Django Version: 4.0.3 Here are my models.py: class GeneralInfo(models.Model): capital = models.CharField(max_length=200) population = models.CharField(max_length=200) highestPeak = models.CharField(max_length=200) area = models.CharField(max_length=200) class TimelineData(models.Model): name = models.CharField(max_length=200) ruler = models.CharField(max_length=200) dateStart = models.CharField(max_length=200) dateEnd = models.CharField(max_length=200) description = models.TextField(default='Description here...') class Country(models.Model): name = models.CharField(max_length=200, db_index=True) description = models.TextField(default='Description here...') generalInfo = models.ForeignKey(GeneralInfo, on_delete=models.CASCADE) timelineData = models.ManyToManyField(TimelineData) I have also overridden the create method for CountrySerializer and here are my serializers.py: class TimelineDataSerializer(serializers.ModelSerializer): class Meta: model = TimelineData fields= '__all__' class GeneralInfoSerializer(serializers.ModelSerializer): class Meta: model= GeneralInfo fields = '__all__' class CountrySerializer(serializers.ModelSerializer): timelineData = TimelineDataSerializer(many=True) generalInfo = GeneralInfoSerializer() class Meta: model= Country fields = …