Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django return "internal" sign in form
I try to create my own session middleware and my uauth system using Django. I've got the following code: class CheckSessionsExistMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): ... response = self.get_response(request) ... response.status_code = 401 response.reason_phrase = 'Unauthorized' realm = 'some_app' response['WWW-Authenticate'] = f'Basic real={realm}' return response When i set to respone header 'WWW-Authenticate' the string that contains word 'Basic', django returns the following form and i do not understand why: Link to example of sign in form that django returns: https://psv4.userapi.com/c235131/u2000021998/docs/d23/bc9d828c3755/file.png?extra=0qo4COrPeQh3mwjuRs1WoYsB3GVW8WB-Xn01jjtQz7muPVFWRqKjsm0itRqJFhOqjoYoKQGpAqWbG4xNQlJD3_kcs1u0UNct_76s6b1jv0u9oW76cnH2bGBTWGd5hpSQY-OpgxtRj60rtUa0k8EX7ydRHQ Is there a way to disable this behavior? I expected that Django just return to client the header 'WWW-Authenticate' with value 'Basic realm=some_app' without sign in form. -
Extending django's core modules functionality
I want to add some little enhancement to one of the core Django modules. Can somebody guide me to some good resources as to how I can achieve that? A simple example of what I want to do is add an extra if-else condition. -
How do you incrementally add lexeme/s to an existing Django SearchVectorField document value through the ORM?
You can add to an existing Postgresql tsvector value using ||, for example: UPDATE acme_table SET _search = _search || to_tsvector('english', 'some new words to add to existing ones') WHERE id = 1234; Is there any way to access this functionality via the Django ORM? I.e. incrementally add to an existing SearchVectorField value rather than reconstruct from scratch? The issue I'm having is the SearchVectorField property returns the tsvector as a string. So when I use the | operator, eg: from django.contrib.postgres.search import SearchVector instance.my_tsvector_prop += SearchVector(["new", "words"], weight="A", config='english') I get the error: TypeError: SearchVector can only be combined with other SearchVector instances, got str. Because: type(instance.my_tsvector_prop) == str A fix to this open Django bug whereby a SearchVectorField property returns a SearchVector instance would probably enable this, if possible. This update will run asynchronously so performance is not too important. Another solution would be to run a raw SQL UPDATE, although I'd rather do it through the Django ORM if possible as our tsvector fields often reference values many joins away, so it'd be nice to find a sustainable solution. -
Django SQLAlchemy engine issue - data not transferred to db using Pandas
My use case is to take excel data and load it to database.. I am using SQLAlchemy (with Pandas df) to do that, but am not able to do.. When I try with ORM bulk_create, it works, suggesting to me that Django side of stuff (eg template, url, view, model connections) is working fine, and there could be some issue in defining the Alchemy engine?? I need help from you to debug and resolve this.. My code details are as below.. Please note I dont get any errors in vscode terminal, its just that when I click on Add/ replace button, the data does not transfer.. Appreciate your help.. many thanks.. SQLAlchemy engine details (saved in engine.py) from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from django.conf import settings engine = create_engine('postgresql://' + settings.DATABASES['default']['USER'] + ':' + settings.DATABASES['default']['PASSWORD'] + '@' + settings.DATABASES['default']['HOST'] + ':' + str(settings.DATABASES['default']['PORT']) + '/' + settings.DATABASES['default']['NAME']) Session = sessionmaker(bind=engine) session = Session() views.py from .models import Industry from .engine import engine, session import pandas as pd def industry_import_replace(request): df = pd.read_excel('Industry.xlsx') df.to_sql('Industry', engine, if_exists='replace', index=False) return render(request, 'portfolio/partials/imports/industry-import.html',{}) template (html) <form method="post"> <div class="row"> <div class="col col-md-4 col-lg-4"> <table class="table"> <thead> <tr> <th scope="col-md-4 col-lg-4">Imports</th> <th … -
Uncaught TypeError: e.indexOf is not a function while upgrading JQuery version
I got an error while upgrading jQuery version from 2.2.4 to 3.6.3 and Bootstrap from 3.3.6 to 3.3.7. When web page is loaded , it is taking too much time . Can anyone suggest a solution to solve this issue? -
Development on local machine vs VM
I have a project to develop on top of Django. The scrum master suggest developing on VM in order to have the same database with others developers. I suggest letting every developer develop in his local machine for development before going to the prod. Could you please advise me the best way to follow ? Otherwise, what will the characteristics of the VM (RAM, CPU, etc) ? -
Divide blogs according to year in list of queryset
I am building a blog app and I am trying to seperate blogs based on the year they were created. like :- 2022 First Blog Second Blog 2021 Third Blog Fifth Blog It can be in list dictionary like :- [ "2022": { "title": "First Blog", "title": "Second Blog", }, "2021": { "title": "Fifth Blog", "title": "Second Blog", } ] models.py class Blog(models.Model): title = models.CharField(max_length=100, default='') date = models.DateTimeField(auto_now_add=True) views.py def get_blogs(request): blogs_by_year = Blog.objects.annotate( year=TruncMonth('date')).annotate( blogs=Count('title')).values("year", "blogs") return blogs_by_year But it is showing seperate results like <QuerySet [{'year': datetime.datetime(2023, 1, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'blogs': 1}, {'year': datetime.datetime(2023, 1, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'blogs': 1}]> But I am trying to seperate based on year. Should I seperate blogs by year using for loop and then filter according to year and append in list of dictionary ? I have read the DateField truncation page but it didn't worked out. -
i am unable to access django rest api from outside the server [closed]
I am facing an issue while trying to access the django api from outside the server.It is working inside the server but unable to access it from outside, can anyone help how to resolve this issue? i have configured url for the django api as well, its giving 502 error, any other solution for the same. -
Next.js getServerSideProps give 404 on production only
I have reproduced the problem to the simplest form: let's start with the backend: #models.py from django.db import models from django.template.defaultfilters import slugify # new class Article(models.Model): slug = models.SlugField(primary_key=True,unique=True) title = models.CharField(max_length=200) description = models.TextField() def save(self,*args,**kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args,**kwargs) #views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from app import models from app import serializer class ArticleView(ModelViewSet): serializer_class = serializer.ArticleSerializer def get_queryset(self): return models.Article.objects.all() def post(self,request): data = serializer.ArticleSerializer(data=request.data) if data.is_valid(): a = models.Article.objects.create(title=data['title'],description=data['description']) a.save() return Response("succes",status=200) return Response("fail",status=400) #serializer.py from rest_framework import serializers from app import models class ArticleSerializer(serializers.ModelSerializer): slug = serializers.SlugField(read_only=True) class Meta: fields = 'slug','title','description', model = models.Article #settings.py ALLOWED_HOSTS = ['localhost','127.0.0.1'] ACCESS_CONTROL_ALLOW_ORIGIN = '*' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_METHODS = '*' ACCESS_CONTROL_ALLOW_HEADERS = '*' # Application definition INSTALLED_APPS = [ 'app', 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have provided everything related to the backend Now on next js side: i got this (inside pages folder): and the code is like this inside [slug].js import axios from 'axios' export async function getServerSideProps({params}){ try{ let res … -
How to get default text input value from one html to other html form
I'm doing basic login. In one html file I have user input email id text box, once click on send otp button that will redirect to next html with email and otp fields, In email field what ever user gives input in first html page that should automatically get into second html email input field text box. Here is my first html page <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Employee Login </title> <link rel="stylesheet" href="{% static 'style.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <center> <h1> </h1> <h2> </h2> <h3> Employee Feedback Login</h3> </center> <div class="wrapper"> <div class="title-text"> <div class="title login"> Login </div> </div> <div class="form-container"> <div class="form-inner"> <form action="" method="post" class="login"> {% csrf_token %} <div class="field"> <input id = "Employee_Mail" type="text" placeholder="Email Address" name="Employee_Mail" required> </div> <div class="field btn"> <div class="btn-layer"></div> <input type="submit" value="Send OTP" > </div> </form> </div> </div> </div> </body> </html> and my redirect(second html page) <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Employee Login </title> <link rel="stylesheet" href="{% static 'style.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <center> <h1></h1> <h2> </h2> <h3> Employee Feedback Login</h3> </center> <div class="wrapper"> <div class="title-text"> <div class="title login"> Login </div> … -
having problem upgrading 5 year old django project
i am trying to use pip freeze > requirements.txt file and in my requirements.txt. i see HUL written between every word and version there. please help i don't know what to try google not helping much -
urlpattern Regex is not working as expected
I have a Django website and for the times that pages are not ready I want to redirect any URL to a specific maintenance page. So in the urlpatterns of my website I added this regex expecting it to capture anything after / but it's not working. urlpatterns = [ path(r'/.*',maintenance_view,name='maintenance') ] -
django DateTimeField serializer return datetime into string format
I have a serializer that validates datetime fields. import rest_framework.serializers as serializer from django.conf import settings class ValueNestedSerializer(serializer.Serializer): lower = serializer.DateTimeField(format=settings.DEFAULT_DATETIME_FORMAT, input_formats=settings.DATETIME_INPUT_FORMATS, required=True) upper = serializer.DateTimeField(format=settings.DEFAULT_DATETIME_FORMAT, input_formats=settings.DATETIME_INPUT_FORMATS, required=True) class DateRangeSerializer(serializer.Serializer): attribute = serializer.CharField(default="UPLOAD_TIME", allow_null=True) operator = serializer.CharField(default="between_dates") value = ValueNestedSerializer(required=True) timezone = serializer.CharField(default="UTC") timezoneOffset = serializer.IntegerField(default=0) def validate_attribute(self, attribute): return 'device_time' if attribute and attribute.lower() == 'device_time' else 'date_range' The payload is in the format: "date_range": { "attribute": "date_range", "operator": "between_dates", "value": { "lower": "2023-01-06T00:00:00Z", "upper": "2023-02-06T23:59:59Z" } } I tried setting the format to '%Y-%m-%dT%H:%M:%SZ', but this still returns lower and upper values as datetime type. (datetime) 2023-02-06 23:59:59+00:00 How do I get these values as string? -
how to integrate django web login with snowflake 'users' table
i have a django application that carries authentication by requesting a token through MSAL. once i have that token, i will check if that username exists the the local django sqlite db and if it exists, he will be logged into the website. if the username doesnt exist, then the username will be recorded in the sqlite db and the user just need to enter his credentials for authentication and will be logged in. what i would like to do is to replace the sqlite db with a snowflake table, which should only have a username and email column. how can i go about doing it? i am thinking that i need to write a customer user class and specifying the correct table in the class meta, switch the database in settings.py to the correct snowflake database. is there anything else needed? -
How to access variable all over django project?
Hy there, I want to define variable that store queryset suchthat variable to be access all over django function and classes. for eg My project contain different app shop common cart users with in users model, i have from django.conf.settings import get_user_model User=get_user_model() class BlockUser(models.Model): blocked_by=models.ForeignKey(User,on_delete=models.CASCADE) get_blocked=models.ForeignKey(User,on_delete=models.CASCADE) while calling every views function i am checking given user is blocked or not, like in shop views class ShopViewset(viewset.ModelViewset): def get_queryset(self,request): queryset=Shop.objects.all() if request.user.is_authenticated: blocked_user=BlockUser.objects.filter(get_blocked=request.user).values_list('blocked_by', flat=True) queryset=queryset.exclude(user__in=blocked_user) return queryset I am calling blockuser queryset everytime with in common,cart and other views. I just want to access that blockuser queryset all over project by defining in one place with middleware or if possible then from context processor and other but not from common function. -
How to automatically fill all info in the 2nd payment but not 3rd or 4th payments in Stripe?
With the Django's code below, I'm testing payment_method_options.card.setup_future_usage in Stripe Checkout in test mode: # "views.py" def test(request): customer = stripe.Customer.search(query="email:'test@gmail.com'", limit=1) print(customer.has_more) checkout_session = stripe.checkout.Session.create( customer=customer["data"][0]["id"] if customer.has_more else None, line_items=[ { "price_data": { "currency": "USD", "unit_amount_decimal": 1000, "product_data": { "name": "T-shirt", "description": "Good T-shirt", }, }, "quantity": 2, } ], payment_method_options={ # Here "card": { "setup_future_usage": "on_session", }, }, mode='payment', success_url='http://localhost:8000', cancel_url='http://localhost:8000' ) return redirect(checkout_session.url, code=303) For the 1st payment with mytest@gmail.com, I need to manually fill all info as shown below: But, even for the 2st and 3rd payments with mytest@gmail.com, I still need to manually fill all info without automatically filled shown below: Finally, for the 4th payment with mytest@gmail.com, all info is automatically filled as shown below: So, how to automatically fill all info in the 2nd payment but not 3rd or 4th payments in test and live modes? -
How to add condition in django-widget-tweaks checkbox form (checked and disabled if attributes is existed)
I'm using django-widget-tweaks and dynamic-field to render my form. This form is use to crete a new Line. User need to select Department (one line has one department) and Process (one line has many process) forms.py class LineForm(DynamicFormMixin, forms.Form): def process_choices(form): department= form['department'].value() return Process.objects.filter(department=department) name = forms.CharField(label='Line Name', max_length=100) department = forms.ModelChoiceField( queryset = Department.objects.all(), initial = Department.objects.first() ) # process field process = DynamicField( forms.ModelMultipleChoiceField, queryset=process_choices, required=False, label="Process", widget=forms.CheckboxSelectMultiple(), models.py class Process(models.Model): process_id = models.AutoField(db_column='Line_ID', primary_key=True) name = models.CharField(db_column='Line_Name', max_length=30) department = models.ForeignKey(Department, on_delete=models.CASCADE) masterLine = models.ForeignKey(MasterLine, null=True, on_delete=models.SET_NULL) From the relationship in the model, how can I customized the checkbox by adding a condition: if process already have line associated with it, the process will checked and disabled -
How to update several product lines at the same time [closed]
Hello I would like some help I am a django beginner and I am making a stock management application I register the articles in a model and I manage the stock in and out my problem is that I want to update several articles at the same time select article 1 quantity article 2 quantity up to article n and save in base who to update the stock of each product. but I don't know how to do it. Currently I can do for one product. thank you for giving me directions -
Having trouble with notifications feature in Django
Created a notification feature in my django project. I've got all the functionality down and it works except for one thing. I want the template to display a different message depending on what action is committed. All it currently displays is 'The ticket has been updated' instead of 'A new ticket has been assigned to you.' How do I fix this? Here is what i have so far. template <div class="dropdown-content" id="myDropdown"> {% if notifications %} {% for notification in notifications %} {% if notification.notification_type == 'created' %} <a href="#">{{notification.ticket.name}}: A new ticket has been assigned to you.</a> {% else %} <a href="#">{{notification.ticket.name}}: The ticket has been updated.</a> {% endif %} {% endfor %} {% else %} <a href="#">No new notifications</a> {% endif %} </div> models.py for notification class Notification(models.Model): OPTIONS = ( ('created', 'created'), ('updated', 'updated'), ) recipient = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='notifications') ticket = models.ForeignKey(Ticket, on_delete=models.SET_NULL, null=True, related_name='notifications') message = models.TextField() notification_type = models.CharField(choices=OPTIONS, max_length=15, null=True) is_read = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) signals.py for notification @receiver(post_save, sender=Ticket) def create_notification(sender, instance, created, **kwargs): if created: notification_type = 'created' else: notification_type = 'updated' assignees = instance.assignee.all() for assignee in assignees: Notification.objects.create(recipient=assignee, notification_type=notification_type) this is createTicket function inside the views.py @login_required … -
Simple proxy service using Django
The idea of the service is that we can control the traffic and where it goes.The routing rules can be based on URI endpoint, HTTP headers or JSON-RPC fields. Each individual rule can be provided via JSON (or Jsonnet) and stored in Redis. I expected to have django app that can handle traffic and help me to solve a problems during migrations from monolit app to microservices. -
Why is my django function working when I test it in Postman but when I use my frontend its not?
I'm having an issue with creating a session in Django. The biggest issue is when debugging as the function works as expected when I run it in postman but not when I try to use my frontend which is built in React. I checked to make sure the data was being passed as expected and being received by the function in the backend and it is. But for some reason the session isn't working correctly. The code is outlined below. In the views.py of my login app, the session is created in this function to track the user_id so that I can update the MongoDB document later on. @api_view(['POST']) def create_login(request): # parse json body = json.loads(request.body) # get email and password and confirm password email = body.get('email') password = body.get('password') confirm_password = body.get('confirm_password') email_is_valid = False password_is_valid = False error = '' # password must be at least 8 characters and contain digit 0 - 9, Uppercase, Lowercase and Special # character from list (#?!@$%^&*-) password_validation_pattern = re.compile('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$') # compare password to confirm password and regex pattern if password == confirm_password and re.match(password_validation_pattern, password): password_is_valid = True elif password == confirm_password: error = 'password is not valid. Requires at … -
Django project gives me the following error AttributeError: 'SafeExceptionReporterFilter' object has no attribute 'get_safe_settings'
I'm currently creating a wep app using django with react and django toolbar. The same project worked a weeks ago, but now it gives me this error message. This is the first time I'm using django, i have no idea what's the problem. Exception ignored in thread started by: \<function check_errors.\<locals\>.wrapper at 0x0000018E6BC28310\> Traceback (most recent call last): File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\utils\\autoreload.py", line 225, in wrapper fn(\*args, \*\*kwargs) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\management\\commands\\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\management\\base.py", line 376, in check all_issues = self.\_run_checks( File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\management\\base.py", line 366, in _run_checks return checks.run_checks(\*\*kwargs) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\checks\\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\checks\\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\core\\checks\\urls.py", line 23, in check_resolver return check_method() File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\urls\\resolvers.py", line 396, in check for pattern in self.url_patterns: File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\utils\\functional.py", line 37, in __get__ res = instance.__dict__\[self.name\] = self.func(instance) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\urls\\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\utils\\functional.py", line 37, in __get__ res = instance.__dict__\[self.name\] = self.func(instance) File "C:\\Users\\nagyd.virtualenvs\\pythonProject\\lib\\site-packages\\django\\urls\\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\\Users\\nagyd\\AppData\\Local\\Programs\\Python\\Python39\\lib\\importlib_init_.py", line 127, in import_module return \_bootstrap.\_gcd_import(name\[level:\], package, level) File "\<frozen importlib.\_bootstrap\>", line 1030, in \_gcd_import File "\<frozen importlib.\_bootstrap\>", line 1007, in \_find_and_load File "\<frozen importlib.\_bootstrap\>", line 986, in \_find_and_load_unlocked File "\<frozen importlib.\_bootstrap\>", … -
migrate postgresql database to sqlite3 in Django
There have been any suggestions for migrating sqlite3 database to postgresql in Django, but I cannot migrate postgresql to sqlite3. Your suggestion would be highly appreciated. -
Django logging does not work properly and logs are not saved to dedicated files
I'm trying to do logging in Django. I want the all_logs handler to write all logs to a common file. The error_file handler writes logs to the error file, warning_file to the warning file, and info_file to the informative message file. But as a result I see errors in the error_file and I see everything in the info_file: info, warnings and errors. And there is no warning_file at all. Only the handler for recording all_logs works well. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{asctime} | {threadName}({thread}) [{levelname}] {message} ({name} {module}:{lineno})', 'style': '{', }, 'simple': { 'format': '{asctime} [{levelname}] {message} ({name}:{lineno})', 'datefmt': '%H:%M:%S', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'all_logs': { 'class': 'logging.handlers.WatchedFileHandler', 'filename': str(BASE_DIR.joinpath('log', 'all.log')), 'formatter': 'verbose', }, 'error_file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': str(BASE_DIR.joinpath('log', 'error.log')), 'formatter': 'verbose', }, 'warning_file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': str(BASE_DIR.joinpath('log', 'error.log')), 'formatter': 'verbose', }, 'info_file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': str(BASE_DIR.joinpath('log', 'info.log')), 'formatter': 'verbose', }, }, 'loggers': { 'django': { 'handlers': ['all_logs', 'console', 'error_file', 'warning_file', 'info_file'], 'propagate': False, 'formatter': 'verbose' }, # my app 'applications': { 'handlers': ['all_logs', 'console', 'error_file', 'warning_file', 'info_file'], 'propagate': False, 'formatter': 'verbose' }, }, … -
Opinion! Creating Template filters to work with class instance in templates, this works, wondering the most "django" optimal way?
Accessing class methods in templates, this works but was wondering if their was a better way? someclass class Something(): somevar = None def __init__(self, somevar): self.somevar = somevar def set_somevar(self, newvar): self.somevar = newvar def set_weird_and_somevar(self, weird, somevar): self.weird = weird self.somevar = somevar def get_tag(self, tag): templateTag from django import template register = template.Library() @register.filter def class_get_method(value, method): f = method.split('.') method = f[0] del f[0] p = getattr(value, method) if f: return p(*f) else: return p() in template, lets say content is a class instance {{content|class_get_method:'set_weird_and_somevar.wenday_adams.nothervar'}}