Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: No module named django, sys.path fine
I'm trying to configure Django with python manage.py shell And I get the error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/lib64/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib64/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/lib64/python2.7/site-packages/django/apps/config.py", line 123, in create import_module(entry) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named django I've seen a lot of questions about this error, and most of them seem to be centered on the fact that django's path is not included in python's sys.path. Mine is, however. When I run sudo pip install django I get Requirement already satisfied: django in /usr/lib64/python2.7/site-packages And the output for my sys.path is ['', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages'] So the path is absolutely there. What are my options here? This is a remote interpreter using SSH from Pycharm, and it's seriously delaying my work. -
Pycharm django tests settings
Having troubles running tests in PyCharm. manage.py test works fine. But if I run test in PyCharm Django Test getting following error: AttributeError: 'module' object has no attribute 'ROOT_URLCONF' Django tests Run\Debug configuration: DJANGO_SETTINGS_MODULE=project.settings.test Django Preferences Settings: project/settings/test.py Manage Script: project/manage.py Test from django.test import SimpleTestCase from rest_framework import status class AccountTestCase(SimpleTestCase): def test_current_account(self): url = '/api/accounts/current/' response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_301_MOVED_PERMANENTLY) StackTrace Error packages/django/core/handlers/base.py", line 113, in get_response urlconf = settings.ROOT_URLCONF File "/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ return getattr(self._wrapped, name) File "/lib/python2.7/site-packages/django/conf/__init__.py", line 173, in __getattr__ return getattr(self.default_settings, name) AttributeError: 'module' object has no attribute 'ROOT_URLCONF' Would appreciate any help. -
Serving staticfiles in django causes 400 error
I'm trying to deploy my django app to heroku, however, when I try and set debug=False locally, I'm getting a 400 Bad Request. My assumption is that it is the serving of staticfiles that is causing this, given that the only message showing up in my logs are The joined path (/DataTables/datatables.min.css) is located outside of the base path component (/Users/me/development/company/project/app/staticfiles) "GET / HTTP/1.1" 400 26 "GET /favicon.ico HTTP/1.1" 404 85` here is my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'lockdown', 'whitenoise.runserver_nostatic', 'dj_database_url', 'app', 'reversion', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'lockdown.middleware.LockdownMiddleware', ] STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' LOCKDOWN_ENABLED = True LOCKDOWN_PASSWORDS =('xxxxx', 'yyyy') APPEND_SLASH = True # # Logging # LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': … -
Modify an objects value in Views without modifying the data base value with django
I have a small issue with modifying an object before it is returned in Views.py. My situation is that I have to hide/modify certain values from model objects for unsubscribed users. My current code is something like this (pseudo code): ShowList(ListAPIView): def get_queryset(self): """ This view should return a list of all the Shows for the currently authenticated user. """ pk = self.kwargs['pk'] shows = Shows.objects.get(id=pk) return shows What I would like to do is change one object from the ones it got from the query. For example, I want to return 0/null for the object named 'video'. What I have done is: shows.video = 0 shows.save() return shows The problem is that it actually overwrites the object's value in the database level. All I want is to change it temporarily before it is returned. I have also tried permission_classes =(subscription_permission,) but it blocks all the views.py. I want the unsubscribed user to see a preview of what is to be seen for a subscribed user, but not see the video. Thank you! -
Django Test request.method == 'POST' not working
I am working on an example in TDD with python and am trying to accept a post request. Django's Request and response objects page for HttpRequest.method suggests using the following snippet to responde to GET and POST differently if request.method == 'GET': do_something() elif request.method == 'POST': do_something_else() With this in mind, my view is setup like so: from django.shortcuts import render from django.http import HttpResponse from items.models import Item def index_page(request): name = '' if request.method == 'POST': name = request.POST['item'] Item.objects.create(name=name) return render(request, 'items/index.html', {'item': name}) My test file contains the following from django.test import TestCase from django.http import HttpRequest from items.views import index_page from items.models import Item class IndexPageTest(TestCase): def test_index_page_can_save_a_post_request(self): request = HttpRequest() request.POST['item'] = 'MyItem' response = index_page(request) self.assertEqual(Item.objects.count(), 1) self.assertEqual(Item.objects.first().name, 'MyItem') Which yields the following error ====================================================================== FAIL: test_index_page_can_save_a_post_request (items.tests.IndexPageTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/items/tests.py", line 43, in test_index_page_can_save_a_post_request self.assertEqual(Item.objects.count(), 1) AssertionError: 0 != 1 However when I alter the view to the following, the test passes. from django.shortcuts import render from django.http import HttpResponse from items.models import Item def index_page(request): name = request.POST.get('item', '') if name: Item.objects.create(name=name) return render(request, 'items/index.html', {'item': name}) Clearly, my page is repsonding to POST requests … -
Annotating a count of a many to one on the query
I'm trying to annotate the number of times a user is referenced on a table that creates a many to one with another table. My models look similiar to this. class LootType(models.Model): pass class Transaction(models.Model): lootype = models.ForeignKey(LootType) user = models.ForeignKey("User") My query looks like this. Loottype.objects.all()\ .annotate(claimed=Count(Q(transactions__user=user))).values('claimed') The raw sql looks like this SELECT "seek_loottype"."id", COUNT("seek_transaction"."user_id" = 1) AS "total" FROM "seek_loottype" LEFT OUTER JOIN "seek_transaction" ON ("seek_loottype"."id" = "seek_transaction"."loot_type_id") GROUP BY "seek_loottype"."id" However, when I inspect the output what I'm seeing is that instead of counting only transactions that belong to the user, it's counting every grouped transaction belonging to the loot type. That is, it's not filtering the count. Can any explain the proper way to do this with Django's ORM with out using extra? And also explain why the expressions in the count is being ignored? -
django markdown not able to see in Admin page
Django markdown not able to see in Admin. There should be WYSIWYG tools for edition visible when creating new post for blog Django markdown was added to settings See also below **main urls **file """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'about_me/', include('personal.urls')), url(r'^', include('blog.urls')), url('^markdown/', include( 'django_markdown.urls')) #wyswigp# ] blog/admin.py rom django.contrib import admin from blog.models import Post from django_markdown.admin import MarkdownModelAdmin admin.site.register(Post, MarkdownModelAdmin) blog/models.py from django.db import models from django_markdown.models import MarkdownField class Post(models.Model): title = models.CharField(max_length = 140) body = MarkdownField() date = models.DateTimeField() category = models.TextField() def __str__(self): return self.title url from C:\Users\marcin.idzik\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\django_markdown\urls.py """ Define preview URL. """ from django.conf.urls import url from .views import preview urlpatterns = [ url('preview/$', preview, name='django_markdown_preview')] I had to modify above file because dev server didn't run Do you know what might be reason markdown is not visible? I also did migrations but without success Thanks for assistance -
How to generate query in Django?
If I have a list of ID's to filter with, how can I generate the query? For example: [14, 44] would result in query.filter(tags__tag_id=14).filter(tags__tag_id=44) >>> print(Place.objects.filter(tags__tag_id=14).filter(tags__tag_id=44).query) SELECT "places_place"."id", "places_place"."address" FROM "places_place" INNER JOIN "places_placetag" ON ("places_place"."id" = "places_placetag"."place_id") INNER JOIN "places_placetag" T4 ON ("places_place"."id" = T4."place_id") WHERE ("places_placetag"."tag_id" = 14 AND T4."tag_id" = 44) (I don't know what the T4 in the SQL above is but no matter, that's for another question) I have a hacky solution in mind, but it so hacky there must be a better way to do it: tag_ids = [14, 44] query_string = '' for tag_id in tag_ids: query_string += ('.filter(tags___tag_id=' + str(tag_id)) eval(query + query_string) -
How to call image object declared in angularjs script
I am developing a website where i used both django and angularjs. I want to know if it is possible to use the "image" object on my page after declaring it in my angularjs script as shown below. var dishes= [ { name:'Uthapizza', image: "{% static 'images/uthapizza.png' %}", category: 'mains'} ] -
How to abort Django data migration?
I have a datamigration I actually want to roll back if certain condition happen. I know that migrations are automatically enclosed in a transaction, so I am safe just raising an exception, and then trust all changes to be rolled back. But which exception should I raise to abort my Django data migration? Should I write my own exception, or am I fine with raise Exception('My message explaining the problem')? What is best practice? -
Django Apache Redhat Permission denied, call to fopen() failed
/var/log/httpd/error_log says, [Tue Nov 22 12:54:51.763863 2016] [mime_magic:error] AH01512: mod_mime_magic: can't read /var/www/Django_Project/cbtraffic/cbTraffic/cbTraffic/wsgi.py', referer: http://ipaddress/Live [Tue Nov 22 12:54:51.763953 2016] [mime_magic:error] AH01512: mod_mime_magic: can't read /var/www/Django_Project/cbtraffic/cbTraffic/cbTraffic/wsgi.py', referer: http://ipaddress/Live [Tue Nov 22 12:54:51.771547 2016] [:error] (13)Permission denied: client ######## mod_wsgi (pid=39821, process='', application='omadi-trafcbi01.intranet.hdr|'): Call to fopen() failed for '/var/www/Django_Project/cbtraffic/cbTraffic/cbTraffic/wsgi.py'., referer: http://ipaddress/Live I moved my project out of my home folder to /var/www/ in an attempt to fix the permission issues (to no avail). here is what I've added to /etc/httpd/conf/httpd.conf, WSGIScriptAlias / /var/www/Django_Project/cbtraffic/cbTraffic/cbTraffic/wsgi.py WSGIPythonPath /bin/python3/site-packages:/var/www/Django_Project/cbtraffic/cbTraffic <Directory /var/www/Django_Project/cbtraffic/cbTraffic/cbTraffic> <Files wsgi.py> Require all granted </Files> </Directory> I also have a /etc/httpd/sites-enabled/000-default file, <VirtualHost *:80> WSGIScriptAlias / /var/www/Django_Project/cbtraffic/cbTraffic/cbTraffic/wsgi.py <Directory "/var/www/Django_Project/cbtraffic/cbTraffic/cbTraffic"> Require all granted </Directory> WSGIDaemonProcess cbTraffic python-path=/var/www/Django_Project:/bin/python3/site-packages WSGIProcessGroup cbTraffic WSGIScriptAlias / /var/www/Django_Project/cbtraffic/cbTraffic/cbTraffic/wsgi.py </VirtualHost> Here is my wsgi.py file, import os import sys import site sys.path.append("/var/www/Django_Project/cbtraffic/cbTraffic") sys.path.append("/var/www/Django_Project/cbtraffic/cbTraffic/cbTraffic/wsgi.py") from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cbTraffic.settings") application = get_wsgi_application() This is my first time trying to launch Django on Redhat. Any help would be appreciated. -
Django - Weekly Upload Form Limit
I will create a form where registered users can upload images. I can create Models, Forms, Views. My only problem is that I want users to be able to upload 2 files per week. If 2 files are installed, I want the form to be passive. I will be happy if you can help me with how to do the limit. -
Django: Object display name for ModelMultipleChoiceFilter
I am using ModelMultipleChoiceFilter to filter my Car objects, but would like the widget to display the object in a particular format, manufacturer - type (year) instead of __repr__ it displays now. Can I change this directly in the CarFilterSet definition or do I need to write a separate widget? -
Why am I getting docker@postgres ERROR: relation "accounts_myprofile" does not exist?
So I am working on a project Django/Postgres project. When I run docker-compose up, the project launches with Django in one container and Postgres in the other. I am able to view certain URL's of my project, however the ones that query MyProfile model, all result in the following error: docker@postgres ERROR: relation "accounts_myprofile" does not exist I have ran both: docker-compose run web python manage.py makemigrations and: docker-compose run web python manage.py migrate I'm not sure if this matters, but this returns with: Operations to perform: Apply all migrations: admin, auth, cities, contenttypes, django_messages, easy_thumbnails, guardian, sessions, sites, userena Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Attaching my docker-compose and Django settings below. docker-compose web: restart: always build: ./web expose: - "8000" links: - postgres:postgres volumes: - /usr/src/app - /usr/src/app/static env_file: .env environment: DEBUG: 'true' command: python manage.py runserver 0.0.0.0:8000 postgres: restart: always image: kartoza/postgis:9.4-2.1 ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ models.py from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from userena.models … -
Django inheritance obtain typeof child from base class
I have three models like following: from model_utils.managers import InheritanceManager class Product(models.Model): name = models.CharField(max_length=50, blank=False, verbose_name="Type here name",) class Pub(Product): product = models.OneToOneField(Product, parent_link=True, ) seating_capacity = models.IntegerField(null=False, verbose_name="Seating capacity of the Pub",) class Restaurant(Product): product = models.OneToOneField(Product, parent_link=True, ) food_speciality = MultiSelectField(choices = MY_CHOICES) I have implemented django-cart and have attached Product as my product model. I return all the products to my frontend. This basically sends product objects with only product specific attributes to the frontend, and hence it is hard to distinguish which product is Pub and which one is Restaurant. How can I handle this on backend itself? Is there any way to extract/send also the type of products? This is how my view looks like: @api_view(('GET',)) def show(request): cart = Cart(request.session) products = cart.products serializer = ProductSerializer(products, many=True) return Response(serializer.data) It returns for example: [{"id":1,"name":"Shreyas","price":"45000.00000","avg_user_rating":"4.50000","city":1},{"id":4,"name":"Phadake","price":"350.00000","avg_user_rating":"5.00000","city":2}] -
Django ManyToMany Field with an already existing table
What I'm trying to achieve is, having model Person that is created and managed by Django have a ManyToMany field with model Property that was "created" using inspectdb and already exists in the database. (Property contains Geographical data and cannot be managed or changed by Django) When trying to migrate, it raises : ValueError: Related model 'cadastroapp.Property' cannot be resolved Full stack here Worth nothing that I removed from the migration file the step to create model Property, since it already exists and AFAIK there's no way to tell Django this in the model Class models.py (simplified) : class Person(models.Model): objectid = models.AutoField(primary_key=True) properties = models.ManyToManyField( 'Property', through = 'Person_Property', ) class Meta: db_table = 'django_person' class Person_Property(models.Model): cod_person = models.ForeignKey('Person', on_delete=models.CASCADE) cod_property = models.ForeignKey('Property', on_delete=models.CASCADE) class Meta: db_table = 'django_person_property' class Property(models.Model): objectid = models.BigIntegerField(unique=True, primary_key=True) created_user = models.CharField(max_length=765, blank=True, null=True) created_date = models.DateTimeField(blank=True, null=True) last_edited_user = models.CharField(max_length=765, blank=True, null=True) last_edited_date = models.DateTimeField(blank=True, null=True) shape = models.TextField(blank=True, null=True) # This field type is a guess. - ESRI Shape class Meta: managed = False db_table = '"GEO"."PROPERTY"' -
Using Django for a very simple website: is it worth it?
Hello everyone how is it going? I've just started using Django recently, and I've started getting my head around it; I need to build a website about cars, with two major APPS: CarsCatalogue; News Section; I find the fact that I can manage the news from the admin panel extremely useful. I have created the typical model: class Post(models.Model): title = models.CharField(max_length = 140) date = models.DateTimeField() body = models.TextField() def __str__(self): return self.title With the urls.py as follows url(r'^(?P<pk>\d+)$', DetailView.as_view( model = Post, template_name="news/post.html")) url(r'^$', ListView.as_view( queryset=Post.objects.all().order_by("-date")[:25], template_name="news/news.html")), This is great! I can manage the News app Extremely easyly from the admin panel. Now I have a page for each news: news/1; news/2 etc etc; But when i go down to the CarsCatalogue, and I would really need to simplify my life because I have plenty of cars with a personal page each to add, I am instead finding myself needing to modify the urls.py for each car I need to add, and it seems I have to modify the views.py for each car -I am using render- am I right? I mean, does it make sense to have a Views.py with one hundred different functions calling one hundred … -
Annotate queryset with __max lookup of related model
I am using Django 1.10. I have a couple of models that looks like: class Product(models.Model): name = models.CharField(max_length=255) ... class TransitionLog(models.Model): TransitionStates =[ ('state_one', _('State One')), ('state_two', _('State Two')), ('state_three', _('State Three')) ] product = models.ForeignKey(Product) transitioned_to = models.CharField(choices=TransitionStates, null=False, blank=False) transitioned_timestamp = models.DateTimeField(auto_now_add=True) And what I would like to do is annotate the Product QuerySet with the latest transition state, which is the transitioned_to field of TransitionLog. The latest state would be the one with the most recent transitioned_timestamp. I've gotten most of the way there by doing the following: Product.objects.annotate(latest_transition=Case(When(transitionlog__pk=Max('transitionlog__pk'), then='transitionlog__transitioned_to'))) However my concern there is that Max() only looks at the pk and takes the highest one, which would work for my purposes but what I would rather do is get the latest transitioned_timestamp. The problem is I'm not sure how to do a match on the TransitionLog.pk after I find the latest timestamp. I know I could also do this in two queries by getting the log separately and doing the join from there, but I'd like to avoid that as well. Could anyone suggest a way that I could get the most recent by timestamp transition log for a given Product in a single … -
Django Topics page error?
I am having issues trying to connect my topics web page via Django. I've tried changing the {% empty %} to {% endblock %} but it still gives me an error. Please help me. Thanks! enter image description here -
How to write a custom serializer?
I want to perform some data manipulations before sending back a JSON response with DRF. Situation My model is: class ThirdParty(models.Model): label = models.CharField(verbose_name=_("Third party label"), null=False, blank=False, default=DEFAUT_LABEL, max_length=255) class CashFlow(TimeStampedModel): date = models.DateField(verbose_name=_("Due date"), null=True, blank=True) forecasted_value = models.DecimalField(verbose_name=_("Forecasted value"), null=True, blank=True, max_digits=11, decimal_places=2) third_party = models.ForeignKey(ThirdParty, null=False, blank=False, related_name='cashflows') Currently I have two serializers: class CashFlowSerializer(serializers.ModelSerializer): third_party = serializers.PrimaryKeyRelatedField(many=False, read_only=True, allow_null=True) class Meta: model = CashFlow fields = ('id', 'date', 'forecasted_value', 'edited_value', 'third_party') class ThirdPartyReadSerializer(serializers.ModelSerializer): cashflows = CashFlowSerializer(many=True, read_only=True) class Meta: model = ThirdParty fields = ('id', 'label', 'category', 'cashflows',) And my ThirdParty view is correctly returning a nice JSON as: { "id": 15, "label": "Adeo", "category": 7, "cashflows": [ { "id": 1, "date": "2016-11-01", "forecasted_value": "2000.00", "edited_value": null, "third_party": 15 }, { "id": 2, "date": "2017-01-17", "forecasted_value": "3000.00", "edited_value": null, "third_party": 15 }, { "id": 3, "date": "2017-01-31", "forecasted_value": "1000.00", "edited_value": null, "third_party": 15 } ] } Question I want to group the cash flows by month and add their values. Question is: what is the best way to do it? The expected result is: { "id": 15, "label": "Adeo", "category": 7, "cashflows": [ { "date": "2016-11-01", "forecasted_value": "2000.00", "edited_value": null, "third_party": 15 }, { "date": … -
Django JSONField InterfaceError: Error binding parameter - probably unsupported type
I have a model with a JSONField, when I try to save a value to that field I get the error: JSONField InterfaceError: Error binding parameter - probably unsupported type. order_history = request.data.get("history", None) print("order_history: %s" % order_history) print("type(order_history): %s" % type(order_history)) if order_history: order.history = order_history order_serialized = order.save() The console prints this: order_history: {u'Tree of Eternity': u'10min', u'Tree of Ages': u'5min', u'Tree of Life': u'1min'} type(order_history): type 'dict' It is a dict that I'm trying to save the the JSONField, why then am I getting this error? I'm using Django Rest Framework, I don't think that matters. Any advice will help. -
How to integrate angular 2 and Django make sure Django urls play nice with angular routers and perform Update and delete operations?
Here is my url url='http://127.0.0.1:8000/shop/shopping/'; how can I access 'http://127.0.0.1:8000/shop/shopping/id' to be able to edit and delete? -
django strange behavior in include
I have create a very simple django project (python 2.7) with those commands: django-admin.py startproject projet7 cd projet7 django-admin.py startapp app7 mkdir -p app7/api/rest touch app7/api/__init__.py touch app7/api/rest/__init__.py I have created app7/api/rest/urls_api.py: from django.conf import urls urlpatterns = [] def register(view): p = urls.url(view.url_regex, view.as_view()) urlpatterns.append(p) return view and i have add this in projet7/urls.py from django.conf.urls import include from app7.api.rest import urls_api ... urlpatterns = [ ... url(r'^api/', include(urls_api)), ] It works ! Great But if i add this instead, in projet7/urls.py: from django.conf.urls import include from app7.api import rest ... urlpatterns = [ ... url(r'^api/', include(rest.urls_api)), ] It does not work. I do not understand why. It should be the same ? Thanks -
Add Django ForeignKey as drop down selection on admin page
I want to be able to create a model TestCase which has a products field which is a ForeignKey to antoher model Product. I want to be able to create a new Product using the Admin page and then when I create a TestCase I want to be able to select from Products I have already created. A dropbox would be ideal. This is what I have tried: models.py class TestCase(TestBase): def __str__(self): return self.title class Product(models.Model): products = models.ForeignKey(TestCase, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200, default='') def __str__(self): return self.name admin.py class ProductInline(admin.TabularInline): model = Product class TestCaseAdmin(admin.ModelAdmin): inlines = [ProductInline] admin.site.register(TestCase, TestCaseAdmin) Adding a new TestCase on the admin page now has fields to create a Product but I want to select from already created Products instead? Thanks in advance. -
How to know if script was run from django or from cli
I have config.py that can be imported both from cli python script and from Django view.py How to know in config.py - what process imported it? May be there are some special vars in Django? I tried if sys.stdin.isatty(): *** but it seems not doing things I expected. I cant use if __name__ == '__main__': because config.py is imported to the main file in cli. In case of Cli I need parse command-line arguments with argparse. In case of Django I need to import predefined django-config.py