Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle MethodNotallowed exception in django rest framework by creating seperate file for exceptions
In my Django RestApi project I want to apply Exceptions errors. I create a separate file (common.py) for all my exceptions file is located out side the project where our manage.py file located. this is in my file: HTTP_VERB_STRING = { 'get': 'get', 'post': 'post', 'put': 'put', 'patch': 'patch', 'delete': 'delete', } Also I set it in settings.py: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler', Now In my view I create a modelviewset. In modelviewset we get all built in functions to perform oprations like (put, patch, delete, create, update) but in this view I don't need put, patch, and delete. So I want to block this and want to give exception on it I tried this : from rest_framework import viewsets from common_strings import HTTP_VERB_STRING class MeterReadingModelViewSet(viewsets.ModelViewSet): queryset = MeterReadingModel.objects.all() serializer_class = MeterReadingModelSerializer def update(self, request, pk=None): raise MethodNotAllowed(method=HTTP_VERB_STRING['put']) def partial_update(self, request, pk=None): raise MethodNotAllowed(method=HTTP_VERB_STRING['patch']) def destroy(self, request, pk=None): raise MethodNotAllowed(method=HTTP_VERB_STRING['delete']) But giving error on MethodNotAllowed is not defined. Why this is happenning? -
ManyToManyField value in Django REST Framework
So when I am routing to api/ to view my models I am not seeing what I expected to see. I wanted to see the names of the strats that I grouped in Strat_Basket model in the variable basket but instead I see their ids which is generated by DJANGO automatically. I want to see the names rather than numbers in the strat_basket view. It is more informative that's why. models.py class Strats(models.Model): name = models.CharField(max_length=64) class Strats_Basket(models.Model): name = models.CharField(max_length=64) basket = models.ManyToManyField(Strats, blank=True, related_name='list') serializers.py: class StratsSerializer(serializers.ModelSerializer): class Meta: model = Strats fields = ('id', 'name') class Strats_BasketSerializer(serializers.ModelSerializer): class Meta: model = Strats_Basket fields = ('id', 'name', 'basket') views.py: class StratsView(viewsets.ModelViewSet): serializer_class = StratsSerializer queryset = Strats.objects.all() class Strats_BasketView(viewsets.ModelViewSet): serializer_class = Strats_BasketSerializer queryset = Strats_Basket.objects.all() urls.py: router = routers.DefaultRouter() router.register(r'strats', views.StratsView, 'strats') router.register(r'strats_basket', views.Strats_BasketView, 'strats_basket') API OUTPUT: strats: [ { "id": 1, "name": "strat1" }, { "id": 2, "name": "strat2" }, { "id": 3, "name": "strat3" }, { "id": 4, "name": "strat4" }, { "id": 5, "name": "strat5" }, { "id": 6, "name": "strat6" } ] strats_basket: Instead of 1,2,4 I want to see strat1, strat2, strat4. [ { "id": 1, "name": "Basket 1", "basket": [ 1, 2, … -
How to convert datetime like `2021-06-25 15:00:08+00:00` to local timezone datetime.datetime python?
I have many datetime.datetime object like 2021-06-25 15:00:08+00:00 where the timezone is different for different data.Eg.another data is 2021-06-24 06:33:06-07:00 .I want to save all of them by converting into a local tmezone.How can I do that? -
Django 'ManyToManyDescriptor' object has no attribute 'count'
I am writing an application where users can add events and other users can add likes to them. I'm stuck at the point where Django needs to sum up all likes for all posts. Based on similar answers, I tried the code below for one event: views.py @login_required(login_url='/oauth2/login') def Events(request, *args): ... likes = EventModel.likes.count() return render(request, 'base/events.html', {..., 'likes': likes}) models.py class EventModel(models.Model): ... likes = models.ManyToManyField(User, related_name='event_likes') But when I refresh it returns an error 'ManyToManyDescriptor' object has no attribute 'count' How can I count all likes for all posts? I think it is too naive to execute loops and write them all in, for example, a dictionary. Here is how the site looks like. I am happy to provide more details regarding my problem. -
Django Setting for Default Related Name Pattern
The Django documentation: Models page mentions that the default related_name for foreign keys uses the pattern f"{ModelClass.__name__.lower()}_set" (or childb_set in the specific example). Is there a way to configure Django to convert CapWords to cap_words (instead of capwords) when creating these default related_names? For example, take the following models: from django.db import models class BlogChannel(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class ArticleAuthor(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class TextEntry(models.Model): blog_channel = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() article_authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline Accessing BlogChannel records through TextEntry is intuitive: >>> text_entry = TextEntry.objects.first() >>> blog_channel = text_entry.blog_channel But the reverse is not: >>> blog_channel.text_entry_set # should be `blog_channel.textentry_set` --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-19-0402bfca7d1f> in <module> ----> 1 blog_channel.text_entry_set AttributeError: 'BlogChannel' object has no attribute 'text_entry_set' Rather than modifying every foreign key field of every model to specify a related_name that uses underscores, I'm curious if there is a setting or something to effect this style change. -
How to change span value inside dynamically rendered table with Django using AJAX response
So I have a website with Django. I have a products page that when I add to cart that specific item using a "Add to Cart" button, the item gets added as an order item based on the item primary key. Now I have a Cart page where I can view the specific products that are already an order item this is dynamically rendered using this piece of code: My cart.html page <tbody> {% for order in orders %} <tr> <th scope="row"> <div class="order-quantity"> <span id="order_quantity">{{order.quantity}}</span> <button data-url="{% url 'add' order.id %}" class="edit-quantity" id="plus">+</button> <button data-url="{% url 'subtract' order.id %}" class="edit-quantity" id="subtract">-</button> </div> </th> <td><img src="{{order.item.product_image.url}}" alt="" width="70" height="70"></td> <td>{{order.item.product_name}}</td> <td> <span>&#8369;</span> {{order.total_item_price}}</td> </tr> {% endfor %} </tbody> Now notice that I have an add quantity button with a data url because I wanted to change the span quantity automatically with AJAX response. Now I figured out how to console log the specific quantity when an order item is clicked for example if I click on the order item Nike, on my console I will see the order quantity but I can't figure out how to change the span text because it is dynamically rendered. Please help! my Cart page … -
Variable image paths in xhtml2pdf with django
I need to display images with variable path, because, the user input's the image.. If I provide a url like <img height='200px' src="http://127.0.0.1:8000/media/images/photo.jpeg" alt="Image of student"> it works, but then, it does not work when I change it to <img src="{{ result.image_of_student.url }}" alt="Image of student"> How do I make this work, as each url is different. In the tutorial, they used <img src={{ result.image_of_student.path}} alt="Image of student"> which worked for them but not for me -
why does heroku server does not play my mp4 video
here i am using Django in backend. on my local machine there is not an problem but when i upload it on Heroku it shows all the files but video is messing.? <video width="540" autoplay muted loop> <source src="{% static 'home/img/Inbodyshot.mp4' %}" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video> -
Select all fields except one Django
There is a class-based view and I want to know how I can use all fields except the user field in the fields instead of '__all__' and also I don't want to write all the fields in a list because there are too many fields and I want to exclude one item. here is the code: class TaskCreate(LoginRequiredMixin, CreateView): model = Task fields = '__all__' # ! here success_url = reverse_lazy('Tasks') def form_valid(self, form): form.instance.user = self.request.user return super(TaskCreate, self).form_valid(form) many thanks in advance. -
How to zip dynamically generated pdfs using weasyprint then returning it as a response in django?
Here is my view to generate a pdf: def download_pdf(request, id): document = Document.objects.get(id=id) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=document_name.pdf' response['Content-Transfer-Encoding'] = 'binary' html_string=render_to_string('portal/pdf/document.html', {'document': document}) html = HTML(string=html_string, base_url="/") result = html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response Now how do I generate multiple pdfs when I decide to Document.objects.filter(some parameter) then sending it as a zip? -
How can I add an extra property to django-rest-framework's ModelSerializer?
I am creating my first django API with django-rest-framework. I have a list of Posts. Each post can have many Likes. Therefore, I have added a ForeignKey to the Like model, which points to its corresponding Post. When I retrieve the information of a post, I'd like to get the number of likes that this post has. Here is my url: path(BASE_URL + "get/slug/<slug:slug>", GetPost.as_view()), This is my view: class GetPost(generics.RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostSerializer lookup_field = "slug" And this is my serializer: class PostSerializer(serializers.ModelSerializer): likes_amount = serializers.SerializerMethodField(read_only=True) def get_likes_amount(self, post): return post.likes class Meta: model = Post fields = '__all__' Unfortunately, as soon as I add the extra property likes-amount to the serializer, the API endpoint stops working and I get the following error: Object of type RelatedManager is not JSON serializable. I'd like to know how I can extend the ModelSerializer with extra fields like the number of likes of my Post, so that I can get. I have read the documentation but haven't found any information on that topic. -
JavaScript function not working on form submission
I've got an HTML form, and when it is submitted, I want a JavaScript function I have defined to run. However, no matter what, the function I've written is not recognised. Here is the HTML form: <form id="compose-form"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" class="btn btn-primary"/> </form> And then here is my JavaScript code: document.addEventListener('DOMContentLoaded', function() { // #compose is the id of the div the form #compose-form is in document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('#compose-form').addEventListener('submit', () => send_email(event)); }); function send_email(event) { event.preventDefault(); // Note this isn't the actual content of my function, but even this simple code doesn't work alert('Hello'); return false; } function compose_email() { document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Note: this function does work completely. document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; } WHAT I'VE TRIED: I've moved the functions above the event listener in my JavaScript I've alternately removed both the event.preventDefault(); and the return false;, removed both, kept both. I've tried defining the function separately, as I have it here, and doing the code as an anonymous function I've … -
Django image file uploading from URL: django.security.SuspiciousFileOperation.response_for_exception (99) Detected path traversal attempt
I am using Django 3.2 I want the user profile images to be partitioned in the following manner: MEDIA_ROOT /users /profile image.jpg I am allowing users to create a profile, and the profile image is retrieved from a URL. I am able to extract the file from the URL and save it into a temporary file locally, and then to load the binary contents into the ImageFile field. However, I am getting a django.security.SuspiciousFileOperation.response_for_exception error being raised. This is the error message I get: django.security.SuspiciousFileOperation.response_for_exception (99) Detected path traversal attempt in /path/to/user/profile/image This is the code I have so far (imports excluded for brevity): models.py def get_upload_path(instance, filename): user_profile_image_dir = f"{settings.MEDIA_ROOT}/users/profile" #os.makedirs(user_profile_image_dir, exist_ok=True) # Is it ok to dynamically create sub directories under MEDIA_ROOT? return os.path.join(user_profile_image_dir, filename) class MyUser(AbstractUser): profile_pic = models.ImageField(null=True, blank=True, upload_to=get_upload_path) def save_image_from_url(image_field, url): with requests.get(url) as response: assert response.status_code == 200 content_type = response.headers.get('content-type') if 'image' in content_type: file_ext = content_type.split('/')[-1] img_tmp = NamedTemporaryFile(suffix=f".{file_ext}", delete=True) img_tmp.write(response.content) img_tmp.flush() img = File(img_tmp) file_basename = os.path.basename(img_tmp.name) image_field.save(file_basename, img) else: # Not an image file pass I have two questions: Why is the exception being raised, and how can I get rid of it, so that I can load the … -
employee/job/create/ 'str' object is not callable
I don't know where to look for this error in my code: views.py: from django.views.generic import ListView, CreateView, DeleteView, DetailView, UpdateView from .models import Employee,Event,detailEvent,Department, Poste from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse, reverse_lazy # ----------------------------------------------------- Views for postes. class PostelistView(LoginRequiredMixin, ListView): template_name = "postes/post_list.html" context_object_name = "Poste" def get_queryset(self): # initial queryset of leads for the entire organisation queryset = Poste.objects.all() return queryset class PosteCreateView(LoginRequiredMixin, CreateView): template_name = "postes/post_create.html" form_class = "Poste" def get_success_url(self): return reverse_lazy("employee:post_list") def form_valid(self, form): instance = form.save(commit=False) instance.save() self.Poste = instance return super(PosteCreateView, self).form_valid(form) my models.py from django.utils.translation import ugettext_lazy as _ class Poste(models.Model): intitule = models.TextField(_("Name"),max_length=250, default='') Where is a str is called ? error seems ending with: File "/Users/PycharmProjects/gusta/venv/lib/python3.8/site-packages/django/views/generic/edit.py", line 33, in get_form return form_class(**self.get_form_kwargs()) TypeError: 'str' object is not callable -
Django Hashids - Override 3rd Party Serializer
I'm fairly new to Django and I'm experimenting with Hashids in a new project. I'm using django-hashid-field, django-rest-framework, django-allauth, and dj-rest-auth. I've added DEFAULT_AUTO_FIELD = 'hashid_field.HashidAutoField' to settings.py in order to generate hashids for all the models, and I've explicitly declared the primary keys and PrimaryKeyRelatedFields in my serializers as per django-hashid-field documentation. Everything is running fine except when I run the following command docker-compose exec web python manage.py generateschema > openapi-schema.yml to generate the schema, I get this error: File "/usr/local/lib/python3.8/site-packages/hashid_field/rest.py", line 14, in bind raise exceptions.ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: The field 'pk' on UserDetailsSerializer must be explicitly declared when used with a ModelSerializer I've tried to override UserDetailsSerializer in accounts.serializers.py with no luck. After going through the dj-rest-auth package to find UserDetailsSerializer I've tried: from dj_rest_auth.serializers import UserDetailsSerializer class UserDetailsSerializer(UserDetailsSerializer): pk = HashidSerializerCharField( source_field='dj_rest_auth.serializers.UserModel.pk') I get this error: File "/usr/local/lib/python3.8/site-packages/hashid_field/rest.py", line 35, in __init__ raise ValueError(self.usage_text) ValueError: Must pass a HashidField, HashidAutoField or 'app_label.model.field' My files: # accounts.models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models import uuid from django.core.validators import RegexValidator, MaxLengthValidator class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise … -
How to perform more/less than filter based on user choice using django-filter
I'm building an app using Django and django-filter. In the DB I have a table with a column named TOTALOFFERAMOUNT, it has integer values (I'm using -1 value to represent that this total offer amount is indefinite) Now for filtering, I use django-filter to filter results based on three fields, one of them is TOTALOFFERAMOUNT. I want to give the possibility that the user when enters a value for TOTALOFFERAMOUNT can decide if he wants the results to be less than or more than or 'Indefinite' Like the picture below: So I want to know how can I implement this. -
Installing 3 Django applications on a shared web server trough cPanel
I am trying to install my applications on a shared web server running phusion Passenger but after a week I am still unable to complete this "simple" task. I wrote a working Django application and now I hae to upload it on my shared web server so I wrote this simple passenger_wsi.py file: #--------------------------------------------------------------------------- # \file passenger_wsgi.py # \brief # # \version rel. 1.0 # \date Created on 2021-05-16 # \author massimo # Copyright (C) 2021 Massimo Manca - AIoTech #--------------------------------------------------------------------------- from DjHello.wsgi import app application = app and this is my DjHelloWorld.wsgi : """ WSGI config for DjHello project. It exposes the WSGI callable as a module-level variable named app. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ #!/opt/alt/python38/bin/python3.8 import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') app = get_wsgi_application() -
Hello, guys. I trying to run my first app in Django, have followed all instructions but isn't working, don't know where is the problem
Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(file).resolve().parent.parent Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-u%xm5q1bi(6t8iretu5s8(sv(0=ip!x-qk7wu1&ef=bhl^2i' SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] Application definition INSTALLED_APPS = [ 'hello', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Markdowned content not reflected in my html template (<em><strong>)
In my Django project, I am using markdownify to convert my markdown to HTML. I have a problem while rendering the HTML content to my template. some tags like <em>, <strong> are not getting reflected. I have tried using the safe filter as suggested in this stackoverflow post but I find no changes! Is there any other filter I can use or any method to render correctly in settings.py MARKDOWNIFY = { "default": { "STRIP": True, "BLEACH": True, "MARKDOWNIFY_LINKIFY_TEXT": True, "WHITELIST_TAGS": [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'em', 'i', 'li', 'ol', 'p', 'strong', 'ul' ], "WHITELIST_ATTRS": [ 'href', 'src', 'alt', ], "WHITELIST_STYLES": [ 'color', 'font-weight', ], "LINKIFY_TEXT": { "PARSE_URLS": True, "PARSE_EMAIL": True, "CALLBACKS": [], "SKIP_TAGS": ['pre', 'code',], }, "WHITELIST_PROTOCOLS": [ 'http', 'https', ], "MARKDOWN_EXTENSIONS": [ 'markdown.extensions.fenced_code', 'markdown.extensions.extra', ] }, } in my template: <div class="col-8"> {{ entry|markdownify|safe }} </div> the content: #This is the H1 tag for Heading but these are working - paragraph - all the headers - list tag things not getting converted - *Italics not working* - **And also bold text** In my template,this is what i get This is the H1 tag for Heading but these are working paragraph all the headers list tag things not … -
Django Celery Recursive Error With tasks.py, Not With views.py
I've created a recursive function to get all children of a certain object. def get_all_children(self): children = [self] try: child_list = self.children.all() except AttributeError: return children for child in child_list: children.extend(child.get_all_children()) return children It works fine when I call this function in my views.py file. But it gives me a RecursionError: maximum recursion depth exceeded in comparison when I call the same function in my celery tasks.py file -
django.db.utils.DataError: value too long for type character varying(4)
I added fields to my model but it's causing errors on migrate in production. I looked at various proposals on fixing this but couldn't get them working. Possible I'm not implementing them well. Would somebody be knowing the exact cause for this???? This is the error message. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 104, in database_forwards schema_editor.add_field( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 487, in add_field self.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 142, in execute cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", … -
Should I include /data folder created by docker-compose to Git?
I'm new to docker and docker compose. To be quiet honest, I'm new to programming in general. Currently I'm following a course in Web Development with Python (Django) and JavaScript. One of the project hinted that we should try to use docker. I use docker-compose to start Django server and connect them to a Postgres database. This configuration is copied from Docker documentation in Django version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db This resulted in a creation of a folder called /data under the root. Should I add this to the repository? Should I even use volumes for database? (In the course tutorial, the database part only include: services: db: image: postgres Thanks in advanced. -
How do I send QuerySets with Django using AJAX?
So, I have submitted a form using AJAX to a Django application but I am finding it a bit difficult to send the output back to my site... trips = Trip.objects.all() context = { "view":"trip", "listofTrips":zip(tripsData, tripsUserData), "noOfTrips":len(tripsData), "searched":True, } So I have QuerySets as well as ZIP files to send, and I cannot save it anywhere as the zip file is a queryset and saving it then downloading it would reduce my performance greatly. So is there any method by which I can get that done without refreshing...We can't use a JsonResponse since I get a (500) server error...so how can I send my data? Thanks! -
Django ORM substitute a field value with a calculation on it
I have this query in mu Django project: def calc_q(start_d, end_d, pr_code): start_d = start_date end_d = end_date pr_code = proj_code var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", "var_val", ) well i would to substitute the "var_val" value with a calculation on it's value, so i create a method like this one: def test_calc(c_val): return c_val*3 and i modify my ORM code : def calc_q(start_d, end_d, pr_code): start_d = start_date end_d = end_date pr_code = proj_code var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", test_calc(ast.literal_eval("var_val")[0]), ) i use ast becaus my var_val value is a string rappresentation of a list ("[112, 92]" for example) So when i run my code again i get: raise ValueError(f'malformed node or string: {node!r}') ValueError: malformed node or string: <_ast.Name object at 0x0000026C3F986DF0> How can i add a calculated field value diectly on my ORM code? So many thanks in advance Manuel -
Python console input from html form using django
i have a personality analysis python script, but I want to make it runs in html and get the input form from html page, and the shows the result back in html page. I already use a django framework to run html page. But i don't know how to connect it with python script I have have attached the python script. # -*- coding: utf-8 -*- import csv import os import pickle import re import string from collections import Counter import pandas as pd import tweepy from nltk.corpus import stopwords from nltk.stem import * from nltk.stem.snowball import SnowballStemmer from nltk.tokenize import word_tokenize from sklearn.feature_extraction.text import TfidfVectorizer from unidecode import unidecode ckey = 'ld6wr3Gt5ZdrKzQ4NGYCFCVA7' csecret = 'ErvYLR40biJWD0kr4wpjUUBK8vKDhGzdCwyzgiUOKdlyeYmaTG' atoken = '585075150-wFq2hQhw8x7oHEKjS4W9xVpsX3UGOtZvNblvSjuo' asecret = 'CwqO7p3esu6K45fNvQytitvXpCbrnKeRgGajs2qUsu74J' auth = tweepy.OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) emoticons_str = r""" (?: [:=;] # Eyes [oO\-]? # Nose (optional) [D\)\]\(\]/\\OpP] # Mouth )""" emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) "]+", flags=re.UNICODE) regex_str = [ emoticons_str, r'<[^>]+>', # HTML tags r'(?:@[\w_]+)', # @-mentions r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs r'(?:(?:\d+,?)+(?:\.?\d+)?)', # numbers r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and ' r'(?:[\w_]+)', # other words …