Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Directory indexes are not allowed here. How to fix this?
I am using VueJS for fronend and Django for backend. I changed the conf of Vuejs such that when we run npm run build the compiled files goes to static/dist directory of Django. I also added the urls in urls.py as shown from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.views.generic import TemplateView from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('users/',include('users.urls')), path('accounts/',include('django.contrib.auth.urls')), path('',TemplateView.as_view(template_name='index.html')), ] urlpatterns = urlpatterns + staticfiles_urlpatterns() when I go to http://127.0.0.1:8000 index .js is returned which contains the VueJS index file. So the above url goes to http://127.0.0.1:8000/static/dist and the server runs normally. But when I reload the page I am getting the below error. Page not found (404) Directory indexes are not allowed here. Request Method: GET Request URL: http://127.0.0.1:8000/static/ Raised by: django.contrib.staticfiles.views.serve Any idea on how to resolve this error? settings.py: """ Django settings for e_cell_server project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - … -
Image передается некорректно при request put django
Картинка получена через форму: class CustomUploadFileForm(forms.Form): file = forms.FileField()) Помимо картинок через эту же форму загружаются и файлы любых других форматов. Я пытаюсь загрузить картинку, полученную из формы, через API OpenstackSwift Swift, картинка загружается, но при просмотре этой же картинки после загрузки вместо картинки я вижу черный фон с небольшим белым квадратом, файлы остальных форматов (pdf, text и тд) загружаются и просматриваются нормально. В чем может быть ошибка? Прилагаю сам джанговский запрос. class CustomUploadView(FormView): ... form_class = ObjectStorageCreateObjectForm def form_valid(self, form): ... file: InMemoryUploadedFile = self.request.FILES['file'] headers = {'Content-Type': file.content_type, 'X-Auth-Token': ...} requests.request( method='PUT', url=..., headers=headers, verify=..., files={'file': file} ) return super().form_valid(form) -
How to retrieve model fields in Django ModelForm?
I'm trying to retrieve 'category' and 'EN_name' fields as a ChoiceField into my ModelForm, but I'm not getting the choices that I put in my model, it's showing me empty select field with no choices. What I want is to create a form that takes: 'category', 'EN_route' and 'EN_name' from Medicine model, 'notes' from Prescription model, 'dose', 'dose_unit', 'frequency' and 'duration' from MedicinePrescription model These are my model.py classes: This is Medicine model class: class Medicine(models.Model): CATEGORY = ( ('All', 'All'), ('Vitamins', 'Vitamins'), ('Analgesics', 'Analgesics'), ('Antacids', 'Antacids'), ('Antianxiety', 'Antianxiety'), ('Antifungals', 'Antifungals'), ('Antihypertensives', 'Antihypertensives'), ('Antipyretics', 'Antipyretics'), ) category = models.CharField(max_length=100, null=True, choices=CATEGORY) stock = models.PositiveIntegerField(null=True) dose = models.FloatField(null=True) EN_name = models.CharField(max_length=100, null=True) EN_brand = models.CharField(max_length=100, null=True) EN_formula = models.CharField(max_length=100, null=True) EN_doseUnit = models.CharField(max_length=50, null=True) EN_route = models.CharField(max_length=50, null=True) AR_name = models.CharField(max_length=100, null=True) AR_brand = models.CharField(max_length=100, null=True) AR_formula = models.CharField(max_length=100, null=True) AR_doseUnit = models.CharField(max_length=50, null=True) AR_route = models.CharField(max_length=50, null=True) def __str__(self): return self.EN_name Prescription model class: class Prescription(models.Model): STATUS = ( ('Active', 'Active'), ('Inactive', 'Inactive'), ) visit = models.ForeignKey(Visit, null=True, on_delete=models.SET_NULL) status = models.CharField(max_length=100, choices=STATUS) expiration_date = models.DateTimeField(auto_now_add=True, null=True) notes = models.CharField(max_length=1000, null=True) def __str__(self): return self.status This is MedicinePrescription model class: class MedicinePrescription(models.Model): medicine = models.ForeignKey(Medicine, null=True, on_delete=SET_NULL) prescription = models.ForeignKey( … -
Django : How to mock queryset chain filter method call?
I am new to python and Django, I have the following method def sample(self, queryset, key_list, row): if(key1 in key_list) queryset = queryset.filter(key1=row.key1) if(key2 in key_list) queryset = queryset.filter(key2=row.key2) if(key3 in key_list) queryset = queryset.filter(key3=row.key3) return queryset I have to write Unit test for this method, I want to mock queryset.filter chain. I initially thought of returning the mocked method when filter is called @patch(mypro.models.objects) def test_sample(self, mock_obj): sample = Mock() sample.key1 = 'Test' sample.key2 = 'Test' mock_obj.filter.return_value = sample actual_output = self.samplepro.sample(mock_obj, key_list, row) self.assertequal(sample.key1, mock_obj.key1) self.assertequal(sample.key2, mock_obj.key2) But I get assertion error, is there any way to mock queryset filter chain ? This is not the actual source code, but a simplified version. -
Django Radio buttons
I was trying to understand how to apply forms.ChoiceField to a html Radio button. Ive managed to create a form to show either yes or no as an answer but I dont know how to apply it to my exhisting HTML radio buttons: And so I want to attach the form to that HTML page, and when i select yes or no i want it to update the model. So far this is what i get in my page: But I cant even click on it. So my model is the following: Model: class datas(models.Model): country = models.CharField(_('country'), max_length=200, default='') qs_login = models.CharField(_('qs_login'), max_length=200, default='') Status = models.CharField(_('Status'), max_length=200, default='') seller_id = models.CharField(_('seller_id'), max_length=200, default='') Task_ID = models.CharField(_('Task_ID'), max_length=200, default='', primary_key=True) associate_queue = models.CharField(_('associate_queue'), max_length=200, default='') associate = models.CharField(_('associate'), max_length=200, default='') metric_wk_no = models.CharField(_('associate'), max_length=200, default='') associate_action = models.CharField(_('associate_action'), max_length=200, default='') correct_associate_action = models.CharField(_('correct associate action'), max_length=200, default='') Associate_Key_Driver = models.CharField(_('Associate_Key_Driver'), max_length=200, default='') Sub_Key_driver = models.CharField(_('country'), max_length=200, default='') Defect_Area_Associate = models.CharField(_('Defect Area Associate'), max_length=200, default='') QA_Comments_on_Associate_Action = models.CharField(_('country'), max_length=400, default='') Metric_name = models.CharField(_('Metric name'), max_length=200, default='') # SIV investigator_task = models.CharField(_('investigator_task'), max_length=200, default='') investigator_queue = models.CharField(_('investigator_queue'), max_length=200, default='') investigator = models.CharField(_('investigator'), max_length=200, default='') verification_action = models.CharField(_('verification_action'), max_length=200, default='') correct_investigator_action = … -
request.session in different views using curl
I have a backend built with Django. Problem:- I am sending phone number via POST and storing in session via request.session['phone_number'] in one view and trying to get the same in another view but facing Key Error What could be the issue? Also via Postman its working fine but via curl or axios I'm getting this error. -
How to rediect to redirect url in Django, Python, Keycloak
@method_decorator(login_required, name='dispatch') class ResetCredential(RedirectView): url = '/oidc/logout' def get(self, request): return redirect('https://docs.djangoproject.com/') I want to call first this < url = '/oidc/logout' > because I want to logout first and then https://docs.djangoproject.com/ -
Correct Practice - Change whole web application to REST API or create a REST API section
I currently have an existing Django based web application, but I am now planning to create an Android app. I need authentication and data from the server so I will be using Django Rest Framework. Just wondering, is it better to change the whole application to REST API or just create a .../api section? -
Get selected text from ckeditor in django python
Are there any good ways to get the selected text from a ckeditor RichTextField as a python string in django? Apologies if this question has been asked before but I could not find any results when it came to ckeditor and django. -
pythonanywhere django deployment Error running WSGI application
Hi this is the error i get when attempting to load my site on pythonanywhere, i am also using aws S3 to load my static files and Postgresql fr my db but i am yet to do any sort of configuration for this on pythonanywhere in case that helps with the solution Please any help would be greatly apprciated, thank you 2021-08-04 12:53:54,120: Error running WSGI application 2021-08-04 12:53:54,128: ModuleNotFoundError: No module named 'django_sass' 2021-08-04 12:53:54,128: File "/var/www/fulodev_pythonanywhere_com_wsgi.py", line 38, in 2021-08-04 12:53:54,128: application = get_wsgi_application() 2021-08-04 12:53:54,128: 2021-08-04 12:53:54,128: File "/home/fulodev/.virtualenvs/myenv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-08-04 12:53:54,128: django.setup(set_prefix=False) 2021-08-04 12:53:54,129: 2021-08-04 12:53:54,129: File "/home/fulodev/.virtualenvs/myenv/lib/python3.9/site-packages/django/init.py", line 24, in setup 2021-08-04 12:53:54,129: apps.populate(settings.INSTALLED_APPS) 2021-08-04 12:53:54,129: 2021-08-04 12:53:54,129: File "/home/fulodev/.virtualenvs/myenv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate 2021-08-04 12:53:54,129: app_config = AppConfig.create(entry) 2021-08-04 12:53:54,130: 2021-08-04 12:53:54,130: File "/home/fulodev/.virtualenvs/myenv/lib/python3.9/site-packages/django/apps/config.py", line 224, in create 2021-08-04 12:53:54,130: import_module(entry) and this is my wsgi file import os from django.core.wsgi import get_wsgi_application import sys from dotenv import load_dotenv project = os.path.expanduser('/home/fulodev/portfolio_project/project') load_dotenv(os.path.join(project, '.env')) path = '/home/fulodev/portfolio_project/project' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' application = get_wsgi_application() settings file ALLOWED_HOSTS = ["fulodev.pythonanywhere.com"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "portfolio_project.apps.PortfolioProjectConfig", 'django_sass', 'ckeditor', 'crispy_forms', 'ckeditor_uploader', 'storages' ] … -
I keep getting attribute Error in python anytime I try to install a python package
C:\Users\OMONIYI\Documents\Vico\django\To-do app\todo_app>pip install gunicorn Traceback (most recent call last): File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\OMONIYI\AppData\Local\Programs\Python\Python36\Scripts\pip.exe\__main__.py", line 4, in <module> File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\main.py", line 9, in <module> from pip._internal.cli.autocompletion import autocomplete File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\autocompletion.py", line 10, in <module> from pip._internal.cli.main_parser import create_main_parser File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\main_parser.py", line 8, in <module> from pip._internal.cli import cmdoptions File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\cmdoptions.py", line 23, in <module> from pip._internal.cli.parser import ConfigOptionParser File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\parser.py", line 12, in <module> from pip._internal.configuration import Configuration, ConfigurationError File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\configuration.py", line 27, in <module> from pip._internal.utils.misc import ensure_dir, enum File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\utils\misc.py", line 38, in <module> from pip._vendor.tenacity import retry, stop_after_delay, wait_fixed File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\tenacity\__init__.py", line 186, in <module> class RetryError(Exception): File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\tenacity\__init__.py", line 193, in RetryError def reraise(self) -> t.NoReturn: AttributeError: module 'typing' has no attribute 'NoReturn' Please, I need help with this. I just finished my first django project, and I'm trying to install some python packages so I can host it on heroku. But anytime I try to, it keeps giving me this error. Python version is 3.6, django version is 3.1.5 -
Get Post Value in Django
I would like to achieve getting a value from a post. I have the following in my views.py: def foo(request): number = request.POST.get('number') print(number) return HttpResponseRedirect(reverse('index')) The HTML is as follows: {% for i in model %} <a class="btn btn-warning" href="{% url 'ms_app:foo' %}" method="POST" name="number" value="{{ i.number }}"">RESTART</a> {% endfor %} The output is none: [05/Aug/2021 12:14:23] "GET /ms_app/customers/1 HTTP/1.1" 200 11714 None [05/Aug/2021 12:14:24] "GET /ms_app/esp_rsrt/ HTTP/1.1" 302 0 [05/Aug/2021 12:14:24] "GET / HTTP/1.1" 200 2650 I feel like this is a simple thing that I am doing wrong. I am very new to Django and new to asking questions here, so if I have done something wrong, please let me know so I can correct it. -
Get real time data to django models from a external webpage
I have a Django app and some of the models I want to get data in real-time from external sources. class Register(models.Model): student_id=models.IntegerField() temperature=models.TextField(max_length=300) The data I want this model to hold can only be accessed in another URL. I have tried to create a web scrapy to get real-time data but it is not efficient. If there is an efficient way to handle this let me. -
How to use django cors with vue (axios)?
I just using vue and with axios going to get data from django, but it gives CORS error, how i can fix it? Console Error My settings.py file: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False # Application definition INSTALLED_APPS = [ ...... 'rest_framework', 'corsheaders' ] MIDDLEWARE = [ ..... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware' ...... ] -
Is it possible to show loading message in django admin when deleting objects?
I have added some code in the pre_delete signal that deletes the images from aws s3 bucket. Because of this, delete is taking more time which would obviously happen. But I want to show some loading message till the object deletes and redirect to the model tabular view again. How can I add that loading message ? -
Can't reopen Django File as rb
Why does reopening a django.core.files File as binary not work? from django.core.files import File f = open('/home/user/test.zip') test_file = File(f) test_file.open(mode="rb") test_file.read() This gives me the error 'utf-8' codec can't decode byte 0x82 in position 14: invalid start byte so opening in 'rb' obviously didn't work. The reason I need this is because I want to open a FileField as binary -
How do you join nested queries in Django
I am trying to frame a Django query for a normal sql that looks like this: SELECT d.id, sum(d.assess), sum(d.view) from (SELECT id, name, group_concat(status) as group, CASE WHEN(GROUP_CONCAT(status) = 4 THEN 1 ELSE NULL) as assess, CASE WHEN(GROUP_CONCAT(status) = 5 THEN 1 ELSE NULL) as view FROM <tables> Group by id,name) d join <table> e on e.id = d.related_id GROUP BY 1; The inner query (the one that does the GROUP_CONCAT) can be formed using a Django Queryset but Im not able to use that output as a Nested Query so that I can join with the main table. Since GROUP_CONCAT is already an aggregate function(which is implemented in Django using annotate functions), I am not able to do another annotate on those fields. This would avoid doing the outer query but understand why its not possible as you cannot do a GROUPING on a GROUP. I wanted to find out if there is a way to do the above, basically running a queryset as a JOIN Table so it can be used as in the setup above. I have tried: a) Subquery: Dint work as my inner query returns multiple rows (one Group_concat for each grouping) so it … -
How do I integrate specific attribute in Django
If I used this line in the PowerShell: Get-AzureADUser -ObjectId "elton.tan@straitsconstruction.com").ExtensionProperty["employeeId"] I will get the employee id How do I integrate this into Django? **This is my graph helper.py** graph_url = 'https://graph.microsoft.com/v1.0/' def get_user(token): # Send GET to /me user = requests.get( '{0}/me'.format(graph_url), headers={ 'Authorization': 'Bearer {0}'.format(token) }, params={ '$select': 'displayName,mail,mailboxSettings,userPrincipalName,department, employeeId' }) return user.json() **This is my HTML** <p>{{user.employeeId}} </p> -
handle group by in mongo engine without raw query
I want to group my documents by month of field date(documents have field createdAt that type is date) and counted them with the mongo engine in Django! I can do it using pipeline and raw query but I want to know is there any way to handle it without raw query like annotate in Django ORM -
buffer size in Django using uWSGI and Nginx
i have a test project which made using: Django 3.2.6 uWSGI 2.0.19.1 nginx/1.18.0 (Ubuntu) i was trying to implement SSE 'Server Sent Events' ,to push the some data to a user, i was able to make send the data, but i face a problem with the buffer size. in other words, the data i was trying to send was small data like this below: def sse_test_data(request): def event_stream(): while True: sleep(.2) yield f"data: {datetime.time(datetime.now())}\n\n" return StreamingHttpResponse(event_stream(), content_type='text/event-stream') and i had to wait the buffer size to reach a specific size 'limit' in order to send 'flush' the data. when i was trying to inspect the buffer size should be reached to be sent i found that it was 6000/characters so any data its size below that size it waits another data in the buffer till the whole data size reach 6000/characters and then it is sent as a block i am really new with SSE and buffering as all, i tried to read about , in order to get around this issue but i couldn't have something to solve this issue so my question is, How to control the buffer size 'make it less or more' ? How to force … -
Accessing a ManyToManyField's contents for a Django template
I'm making a low-spec e-bay clone, I'm trying to implement a watchlist function but the problem is I can't access the ManyToManyField in the Watchlist model so I can use the contents of the field in the template I'm using. To display each user's watchlist to them, so far I only get this result: but I need to get a result like so: Code I'm using: watchlist.html {% extends "auctions/layout.html" %} {% load static %} {% block title %} {{name}}'s Watchlist {% endblock %} {% block body %} <h2>{{name}}'s Watchlist</h2> {% for listing in watchlist %} <div class='listing'> <h3>{{ listing.list_title}}</h3> {% if listing.img_url == "" %} <a href='#'><img src="{% static 'auctions/img404.png' %}" class='img-fluid'></a> {% else %} <a href='#'><img src="{{ listing.img_url }}" class="img-fluid" alt='image of {{ listing.list_title }}'></a> {% endif %} <p> {{ listing.desc }} </p> <p> Current Bid: ${{ listing.start_bid }} </p> {% if listing.category == "" %} <p>Category: No Category Listed</p> {% else %} <p>Category: {{ listing.category }}</p> {% endif %} <a href='#' class='btn btn-primary' id='go'>Go To Listing</a> </div> {% endfor %} {% endblock %} views.py def render_listing(request, title): if request.method == "POST": form = BidForm(request.POST) bid = int(request.POST['new_bid']) listing = Auction_Listing.objects.get(list_title=title) comments = Auction_Comments.objects.all().filter(auction_id=listing) if bid < listing.start_bid: … -
how to add lastmod field in index sitemap django
I need to add lastmod attribute to sitemap index. And it looks like django.contrib.sitemaps.views.index doesn't include lastmode though Here is my sitemap.xml: <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" <sitemap> <loc>localhost:8000/sitemap-pages.xml</loc> </sitemap> </sitemapindex> my urls.py sitemaps_pages = { 'pages': sitemaps.PageViewSitemap, 'life': sitemaps.LifeViewSitemap, 'lifes': sitemaps.LifesSitemap, 'novosti': sitemaps.NewsViewSitemap, 'novost': sitemaps.NewsSitemap, 'catalog': sitemaps.CatalogViewSitemap, 'categories': sitemaps.CategorySitemap, 'regions': sitemaps.RegionSitemap, 'times': sitemaps.TimeSitemap, 'material': sitemaps.MaterialSitemap, 'products': sitemaps.ProductsSitemap, } path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps_pages}, name='django.contrib.sitemaps.views.sitemap'), path('sitemap.xml', index, {'sitemaps': sitemaps_pages}, name='django.contrib.sitemaps.views.sitemap'), sitemaps.py class ProductsSitemap(sitemaps.Sitemap): protocol = 'https' try: priority_filter = strip_tags(Info.objects.get(name='priority_filter').value) frequency_filter = strip_tags(Info.objects.get(name='frequency_filter').value) except Exception: priority_filter = '0.5' frequency_filter = 'daily' priority = priority_filter changefreq = frequency_filter limit = 1000 def items(self): return Product.objects.all() def location(self, item): return str(item.url) def lastmod(self, item): if item.url == '/': return Product.objects.latest('updated_at').updated_at else: return item.updated_at How do i solve the problem? -
Django Rest Framework: How to randomize Queryset while keeping the pagination and search functionality?
Premise: Imagine I have 100 items in the database and each time the user opens the application I want to display 10 random items, and as the user scrolls down more items get added. I started by creating a "ListAPIView" using a "PageNumberPagination" class: class ItemListView(generics.ListAPIView): queryset = Item.objects.all() serializer_class = ItemListSerializer pagination_class = ItemListPagination class ItemListPagination(PageNumberPagination): page_size = 20 This will give me always the same 10 items, so to randomize it I overwrote the "get_queryset" method and used a seed to randomize the queryset. class ItemListView(generics.ListAPIView): serializer_class = ItemListSerializer pagination_class = ItemListPagination def get_queryset(self): objects = list(Item.objects.all()) seed = self.request.GET.get('seed') # get the seed from the request query params random.seed(seed) # set seed random.shuffle(objects) # randomize objects random.seed() # reset seed return objects This works as expected but as soon as I introduce the SearchFilter backend, it errors out because is expecting a QuerySet and not a list. class ItemListView(generics.ListAPIView): serializer_class = ItemListSerializer pagination_class = ItemListPagination filter_backends = [SearchFilter] search_fields = ['name'] def get_queryset(self): objects = list(Item.objects.all()) # Get queryset and convert it to list seed = self.request.GET.get('seed') # get the seed from the request query params random.seed(seed) # set seed random.shuffle(objects) # randomize objects random.seed() # reset … -
Django Form validation(Not showing submitted Data)
As you see I can try to show only odd numbers on the screen. But after submission, the data not showing on the screen. Here the HTML code {% if form_submited %} <p>Field: {{ field }}</p> {% endif %} Here form.py file from django import forms from django.core import validators def even_or_not(value): if value%2==1: raise forms.ValidationError("Please Insert an Even Number!") class user_form(forms.Form): number_field=forms.IntegerField(validators=[even_or_not]) **Here views.py file ** from django.shortcuts import render,HttpResponse from home.models import Musician, Album from home import forms # Create your views here. def index(request): musician_list = Musician.objects.order_by('first_name') diction={'text_1':'This is a list of Musicians', 'musician':musician_list} return render(request,'index.html',context=diction) # return HttpResponse("this is homepage") def form(request): new_form=forms.user_form() diction={'test_form': new_form, 'heading_1': "This form is created using django library "} if request.method == "POST": new_form = forms.user_form(request.POST) diction.update({'test_form':new_form}) if new_form.is_valid(): diction.update({'field': new_form.cleaned_data['number_field']}) diction.update({'form_submited':"Yes"}) diction={'test_form': new_form,'heading_1':"This form is created using django librery "} return render(request, 'form.html',context=diction) -
how call a function with in the class in djagno shell
class Test: def m1(): pass def m2(): pass I have this class in the test.py(Django-Project) file how to call the m2 function in Django. shell. how to call this function in Django shell. I am trying like this: >> python manage.py shell >> from appname.filename import <class_name|function_name> But it thrown an error like this: ImportError: cannot import name <class_name|function_name>. anyone help me out with this. Thanks in advance.