Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle deletion of model objects included in custom field
I have a somewhat complex structure of models and fields, where a Workout model object has my own custom field LiftsField. This field handles conversion of objects of the class Lifts, which is a collection of LiftSerie objects. The LiftSerie objects are in turn containers of a LiftActivity MODEL class object and some other things that are not important here. Workout: class Workout(models.Model): datetime = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) lifts = fields.LiftsField(null=True) cardios = fields.CardiosField(null=True) def __str__(self): return str(self.datetime)+" "+self.user.email __repr__ = __str__ LiftsField: class LiftsField(JSONField): """Field representing a models.Lifts object""" def from_db_value(self, value, expression, connection, context): if value is None: return value return parse_lifts(value) def to_python(self, value): if isinstance(value, models.Lifts): return value if value is None: return value return parse_lifts(value) def get_prep_value(self, value): if not value: return value lifts_pre_json = [serie_object.pre_json() for serie_object in value.series] return json.dumps(lifts_pre_json) Lifts: class Series(object): """Series is a list of AbstractSerie objects""" def __init__(self, series, serie_class): self.series = [] for serie in series: if type(serie) != serie_class: raise TypeError("List passed to constructor should only contain "+serie_class.__name__+" objects.") self.series.append(serie) class Lifts(Series): def __init__(self, series): """ Series is a list of LiftSeries """ super().__init__(series, LiftSerie) LiftSerie: class AbstractSerie(object): def __init__(self, activity): """activity is an Activity""" … -
Django + AJAX - POST 404 (Not Found)
I'm trying to implement a like functionality in my Django app using AJAX but, when I try to do that I'm getting an POST http://localhost:8000/forum/like/ 404 (Not Found). All I wanna do is to add/remove users from the likes list without refreshing the entire page. views.py @require_POST def toggle_like(request): if request.method == "POST": user = request.user slug = request.POST.get('slug', None) question = get_object_or_404(Question, slug=slug) if question.likes.filter(id=user.id).exists(): question.likes.remove(user) else: question.likes.add(user) context = {'likes-count': question.likes.count} return HttpResponse(json.dump(context), content_type='application/json') urls.py from django.urls import path from . import views app_name = 'forum' urlpatterns = [ path('like/', views.toggle_like, name='toggle-like'), ] question.html {% block javascript %} <script> $('#like').click(() => { $.ajax({ method: 'POST', url: "{% url 'forum:toggle-like' %}", data: { 'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: (response) => { alert(response.message); }, error: (response, error) => { alert(response.responseText); } }) }) </script> {% endblock %} {% block content %} <p>Likes: {{ question.likes.count }} <input type="button" id="like" name="{{ question.slug }}" value="Like" /></p> {% endblock %} -
Error 500 in production just when debug is set to False
I am using Django 1.11 in my application. I've implemented the authentication using django-registration and created a profile model to store some user infos: class Profile(models.Model): ... user = models.OneToOneField(User) nick = models.CharField(max_length=50) level = models.PositiveIntegerField(null=True) avatar = models.CharField(max_length=500, null=True, blank=True) ... This model is being created/saved with signals: def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) def save_user_profile(sender, instance, **kwargs): instance.profile.save() post_save.connect(create_user_profile, sender=User) post_save.connect(save_user_profile, sender=User) Well, I am not allowing users to upload images, as you see. The workflow of choosing an avatar image is: User access profile configuration page This page has a button that opens a modal with image options, the user has to choose one. User select an image. User click to save changes. What I am saving at profile's avatar field is a string that have to be concatenate to the static url, for instance, if the image path is: 127.0.0.1:8000/static/account_settings/avatar-images/man2.jpeg I am saving: account_settings/avatar-images/man2.jpeg I've being through this workflow in production with debug set to True (impossible to make with debug = False because of the error 500). So, I've opened the user public profile page and it gives me the same error. But I've found the root of the problem in this template: … -
How to have optional parts of a django url and reverse to it [duplicate]
This question already has an answer here: Django optional url parameters 4 answers This is my url: url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/(?P<id>[0-9]*)$', views.AddWorkoutView.as_view(), name = 'add_workout'), It is for adding workouts to the database. If the id is provided, the server should: Check if a workout with the id exists in database If it exists, destroy the found item and replace it with the one who's data has been posted to the view. If it doesn't exist, simply add the new workout to the database without destroying any existing workout object. In one of my templates, called addworkout.html, I have a form where the workout data is inserted. It has the following opening tag: <form id="workoutform" action="{% url 'workoutcal:add_workout' date.year date.month date.day %}" method="post"> As you can see, I haven't provided any id argument in the reverse url. This is because in addworkout.html the user can only add new workouts, so no existing workout id is necessary. However, this attempt at reversing the url generates an error: NoReverseMatch at /workoutcal/add/2018/1/2/ Reverse for 'add_workout' with arguments '(2018, 1, 2)' not found. 1 pattern(s) tried: ['workoutcal/add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/(?P<id>[0-9]*)$'] Since I have written a regex star next to the id number in the url, there shouldn't be any requirement … -
AuthToken in Django Rest FrameWork: non_field_errors
I m trying to integrate token based authentication in DRF but when I hit api-token-auth/ using {"username":"test","password":"123456789"} as mentioned in the doc it is required to return me the Token but I m getting { "non_field_errors": [ "Unable to log in with provided credentials." ] } I have used rest_framework.authtoken in my installed apps also token is getting generated once the user is registerd and save in authtoken_token table .Also in my urls.py of root I m using urlpatterns += [ url(r'^api-token-auth/', authviews.obtain_auth_token), ]. Any help would be appreciated. Also attaching the code urls.py urlpatterns += [ url(r'^api-token-auth/', authviews.obtain_auth_token), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'users' ] users/urls.py from rest_framework.routers import DefaultRouter from . import views as user_views from django.conf.urls import url ,include router = DefaultRouter() router.register(r'user', user_views.UserViewSet,base_name="user") urlpatterns = router.urls -
Reset IDs of a specific model in Django App
I am right now in development on local and I would like to reset the ID of one of my models called question. I created many questions and deleted them but the count still continue to go up. I know that in production I will get a blank database but I need to do some testing to rest the ID starting at 1 of that specific model only I read about flush but not sure how to use it .. Could someone give me a hand on that please ? Thx you ;) -
django tastypie resource queryset filter doesn't work if resource is pulled into another
Models class Quote(models.model): quote_ref = models.TextField(null=True, blank=True) order = models.Foreignkey('Order', related_name='quotes') version models.DecimalField(null=True, blank=True) requested_date = models.DateField(null=True, blank=True) expiry_date = models.DateField(null=True, blank=True) closed_date = models.DateField(null=True, blank=True) class Order(models.model): order_ref = models.CharField(null=True, blank=True) cost models.DecimalField(null=True, blank=True) order_date = models.DateField(null=True, blank=True) delivery_date = models.DateField(null=True, blank=True) ....... ....... Resources class RequestsResource(ModelResource): quotes = fields.ToManyField('api.resources.QuoteIndexResource', 'quotes', full=True, null=True) class Meta: queryset = Order.objects.all() resource_name = 'request' class QuoteIndexResource(ModelResource): class Meta: queryset = Quote.objects.all().filter(closed_date__isnull=True) resource_name = 'index_quote' If I use the QuoteIndexResource on its own the filter on the querysetworks but if it is pulled into RequestsResource then the filter doesn't have any effect on the data. Is there a way to make the .filter(closed_date__isnull=True) work in this scenario? -
How to use multiple attributes in algolia search using Django . Show multiple courses
How to use multiple attributes in algolia search using Django . Show multiple courses { "course_": [ { "interest_min": 11, "other_fees": 0, "tution_fees": 56000, "interest_max": 14, "duration_max": 7, "payment_month_min": 4573, "total": 56000, "payment_month_max": 2567, "course_name": "Mtech", "hostel_fees": 0, "duration_min": 5, "course_type": "Full Time", "duration": "4" }, { "interest_min": 7, "other_fees": 465, "tution_fees": 35456, "interest_max": 14, "duration_max": 5, "payment_month_min": 2414, "total": 41385, "payment_month_max": 483, "course_name": "Mca", "hostel_fees": 5464, "duration_min": 2, "course_type": "Full Time", "duration": "2" } ], "name": "A. K. Choudhury School Of Information Technology, Kolkata", "slug": "a-k-choudhury-school-of-information-technology-kolkata", "country": "India", "location_type": "Domestic", "type": "College", "address": "Kolkata", "image": "images/a-k-choudhury-school-of-information-technology-kolkata_M9cCiHQ.jpg", "institute_type": "Private", "cities": "noida", "college_facilities": "Sports Transportation", "approved_by": "University Of Calcutta, Kolkata", "established": "2005-01-05", "state": "Up", "objectID": "2" } How to use multiple attributes in algolia search using Django . Show multiple courses using instantsearch.js in django -
Localhost not showing views
I am making a django app for storing files and I'm not seeing any errors on the runserver console but when I decide to go to localhost I get this error.Screenshot of localhost Which is odd because my urls.py is structured like this. urlpatterns = [ url('admin/', admin.site.urls), url(r'^$', index, name='index'), url(r'^(?P<slug>[\w\-]+)/$', document, name='document') ] And my models.py class Document(models.Model): title = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, max_length=255) case_number = models.IntegerField() description = models.TextField(max_length=500) lawyer_name = models.CharField(max_length=250) case = models.FileField(upload_to='uploads/%Y/%m/%d/') def __str__(self): return self.title I'm using Django 1.11 and Python 3.6.2 -
Django filter foreign key with list
class Word(Model): word = CharField() categories = ManyToManyField('Category') class Category(Model): name = CharField() What is the query to get all words that have at least two categories: General and Garden? -
in Django passing form variable to model for auto create?
i'm newbie in django recently i have problem with my code and would like to ask how to pass referral_id from extended userform to MemberProfile model so that i can create automaticly when user model created. here is my code: models.py class MemberProfile(models.Model): member = models.OneToOneField(User, on_delete=models.CASCADE) referral_id = models.CharField(max_length=10) def create_profile(sender, **kwargs): if kwargs['created']: member_profile = MemberProfile.objects.create(member=kwargs['instance']) post_save.connect(create_profile, sender=User) forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'referral_id'] def save(self, commit=True): user = super(UserForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.username = self.cleaned_data['username'] if commit: user.save() return user please give advice how to solve my problem thanks -
Django tests not finding my tests
When I run tests, django runs 0 tests. This is my project structure: manage.py - app/ - main_app/ - test/ - tests_v1 - tests_v2 I use this command: python manage.py test --pattern="tests_v*.py" Django runs 0 tests in 0 seconds. What am I missing? -
Combining Django F, Value and a dict to annotate a queryset
I have a scenario where I want to annotate a queryset with externally prepared data in a dict. I want to do something like the following: value_dict = {"model1": 123.4, "model2": 567.8} qs = ModelClass.objects.annotate( value=Value(value_dict.get(F('model__code'), 0)) ) The results currently show all as 0 as the F() doesn't seem to be the best way to look up the dict seeing as it doesn't return a string and it is resolved further down the track. Your help and suggestions would be much appreciated I'm currently on Python 3.6 and Django 1.11 -
Logical operations in django filter
I need to get my queryset where: (a="a" AND b=None) OR (a=None AND b="b") I know about Q objects in django, but this syntax doesn't works: cls.objects.filter(models.Q(a="a", b=None) | models.Q(a=None AND b="b")) I am absolutely sure my database contains expected objects. But all I get is the empty queryset. I guess there is some problem with syntax here. But where? -
Accessing Django Templates after modifing the Django layout structure
I re-organized Django,the following way: config - settings - base.py - local.py urls.py wsgi.py also apps: - apps(level0) - acc(level_1) - users(level_2) - templates - users - acc_control(level_2) -att(level_1) - notes (level_2) - notifications (level_2) - mark(level_1) - config (level0) - templates(level0) Some apps are directly in apps folder, ex mark, others are in other subfolders, ex users BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] My issue is regarding templates access, because I receive the following error: \apps\acc\users\templates\users\templates\users\detail.html (Source does not exist) is repeating the internal folder; In the View the template is set as: template_name = 'users/templates/users/detail.html' I tried also: template_name = '/users/detail.html' -
Migration error in django models.py database
My app is installed correctly and its models.py reads: from django.db import models class Album(models.Model): artist = models.CharField(max_lenght=250) album_title = models.CharField(max_lenght=500) genre = models.CharField(max_lenght=100) album_logo = models.CharField(max_lenght=1000) class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_lenght=10) song_title = models.CharField(max_lenght=250) But whenever I run python manage.py migrate, I get the following error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\dougl\desktop\django websites\twenty_one_pilots\downloads\models.py", line 3, in <module> class Album(models.Model): File "C:\Users\dougl\desktop\django websites\twenty_one_pilots\downloads\models.py", line 4, in Album artist = models.CharField(max_lenght=250) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\db\models\fields\__init__.py", line 1042, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'max_lenght' What could be wrong? I'm still a beginner and I'm still learning about … -
What are the video streaming solutions and corresponding Django packages available for the online coaching web app? [on hold]
We are creating a Web App for online IELTS coaching. What are the video streaming solutions and corresponding Django packages available for the same? -
Python Django threaded comments ordering
I am creating a django comments app. I have created model Comments class Comments(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add = True) likes = models.IntegerField(default = 0) path = models.CharField(validators=[validate_comma_separated_integer_list], max_length = 100, blank = True, editable = False) depth = models.PositiveSmallIntegerField(default = 0) The way i store path tree is that: First comment will have path [1]. Reply to first comment will have path [1,2] Second comment will have path [3] Second reply to first comment will have path [1,4]. And so on. So something like this should happen. [1] [1,2] [1,4] [3] I display it by fetching using the following line: comment_list = Comments.objects.order_by('-path') The problem is it displays newest comment first like this: [3] [1] [1,4] [1,2] How do i correct it so that it prints oldest comment first? -
nginx file upload freezes
I'm testing a django website deployment. The site works without any issues when I connect directly to my gunicorn localhost and run it in debug mode (so that django handles file uploads itself). When I access the site with debug mode turned off through nginx (it binds to the same gunicorn localhost) everything works just as well, except file uploads. Whenever I try to upload a file > 1MB, the upload freezes at some point (with a 1.3MB file, my browser freezes at 70%). I've installed nginx into a conda virtual environment (conda install --no-update-dependencies -c anacoda nginx). Here is the etc/nginx.conf file: # nginx Configuration File # https://www.nginx.com/resources/wiki/start/topics/examples/full/ # http://nginx.org/en/docs/dirindex.html # https://www.nginx.com/resources/wiki/start/ # Run as a unique, less privileged user for security. # user nginx www-data; ## Default: nobody # If using supervisord init system, do not run in deamon mode. # Bear in mind that non-stop upgrade is not an option with "daemon off". # daemon off; # Sets the worker threads to the number of CPU cores available in the system # for best performance. # Should be > the number of CPU cores. # Maximum number of connections = worker_processes * worker_connections worker_processes auto; ## Default: … -
create new does returns 'list' object has no attribute 'create'
I am trying to create a autocomplete input which can create a new object. class CellLineAutocomplete(autocomplete.Select2QuerySetView): create_field = 'cell_line_name' model = CellLine def has_add_permission(self, request): return True def get_queryset(self): if self.q: return CellLine.objects.filter(cell_line_name__icontains=self.q) return [] def get_result_label(self, item): return item.cell_line_name When clicking the create option I receive the following error: Traceback (most recent call last): File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/dal/views.py", line 48, in dispatch return super(ViewMixin, self).dispatch(request, *args, **kwargs) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/dal/views.py", line 116, in post result = self.create_object(text) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/dal/views.py", line 92, in create_object return self.get_queryset().create(**{self.create_field: text}) AttributeError: 'list' object has no attribute 'create' I access the code of the autocomplete git repo: def create_object(self, text): """Create an object given a text.""" return self.get_queryset().get_or_create( **{self.create_field: text})[0] and edited it to work for me: def create_object(self, text): """Create an object given a text.""" return self.model.objects.get_or_create( **{self.create_field: text})[0] Is there a better way to solve my … -
display console output inside a template in Django
I'm working on a project in which I'm using Python(3.6) and Django(1.10), from few days I'm struggling to display the console output inside a Django template but couldn't find any solution. For example code below prints various statements to the console, I want to display these messages to the Django templates. if form.is_valid(): deployment = form deployment.user = request.user deployment.project = form.cleaned_data['project'] deployment.deploymentName = form.cleaned_data['deploymentName'] deployment.zone = form.cleaned_data['zone'] deployment.cluster = form.cleaned_data['cluster'] deployment.sourceFile = form.cleaned_data['sourceFile'] deployment.save() # Start awd deployment from here tempdir = tempfile.mkdtemp() saved_unmask = os.umask(0o077) temp_dir_path = os.path.join(tempdir) archive_path = os.path.join(settings.MEDIA_ROOT, 'archives/', deployment.sourceFile.name) print(archive_path) # Extract uploaded archive inside temporary dir patoolib.extract_archive(archive_path, outdir=temp_dir_path) # Try to retrieve path of dockerfile directory docker_glob = os.path.join(temp_dir_path, "*", "Dockerfile") print(docker_glob) docker_file = glob.glob(docker_glob)[0] docker_folder = os.path.dirname(docker_file) print(docker_folder) docker_client = docker.from_env() print("Start Building your docker image...") docker_client.login(username='arycloud', password='Abd37214@cloud') docker_client.images.build(path=docker_folder, gzip=False, tag=deployment.deploymentName) image = docker_client.images.get(deployment.deploymentName) shutil.rmtree(tempdir) img_id = image.short_id print(img_id) # prepare tag for image tag = deployment.deploymentName.lower() docker_api_client = docker.APIClient( base_url='unix://var/run/docker.sock') tagged = docker_api_client.tag(image=img_id, repository='arycloud/istio_dep', tag=tag, force=True) if tagged is True: print('image has been tagged!') print('Pushing....') pushing_image = docker_client.images.push(repository='arycloud/istio_dep', tag=tag) print(pushing_image) -
How to Remove duplicate data by field ‘agent__id’ and 'account', and count the field 'agent__id' by the same data
I want to Remove duplicate data by field ‘agent__id’ and 'account', and count the field 'agent__id' by the same data 。 My code is follow: list(AgentPayLog.objects.values('agent__id', 'account'). distinct().values('agent__id').annotate(agent_count=Count(F('agent'))). values('agent__id', 'agent_count')) the data is following: account_id agent_id 30001 1 30001 2 30001 2 the code print is following: agent_id agent_count 1 1 2 2 I want the data is following: agent_id agent_count 1 1 2 1 -
Disable double click in auto generated select tag
Greeting, I've successfully created a select field that looks exactly like in django admin manytomany field in my html page EXAMPLE. but now i want to disable on double click function from this field, I've tried dozen of method already from previous asked question in this site and I've already disable the entire page double click function but I still able to double click, can anyone help me with this thanks, below is my code : html : <div class="field"> <select name="settings-user" id="id_settings-user" multiple="multiple" class="selectfilter" data-field-name="User" data-is-stacked="0"> <option value={{ form.user }}</option> </select> </div> javascript : <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/third_party/jquery/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="/static/admin/js/SelectBox.js"></script> <script type="text/javascript" src="/static/admin/js/SelectFilter2.js"></script> <script> $(document).ready(function(){ $("*").dblclick(function(e){ e.preventDefault(); }); }); </script> -
How to check Post request of this format using Postman
I am checking json object post request using postman.The data is in format { "user": { "first_name": "akash", "last_name": "gondhale", "username": "akash@gmail.com", "email": "akash@gmail.com", "groups": [], "is_active": true }, Every time I am sending request I am getting error in postman is { "user": [ "This field is required." ] } How to send this fields as a Post request using Postman to Django server -
Execute windows script with python to startup django server and open browser
I'd like to write a python script to do following things. startup Django local server(manager.py runserver) Open browser and direct to http://127.0.0.1:8000 After Close the windows console, kill the python background task. For now, my script is something like below cmd = "python manage.py runserver" subprocess.call(cmd, shell=True) time.sleep(5.0) cmd = 'start "" "http://127.0.0.1:8000"' subprocess.Popen(cmd, shell=True) This script worked. But I'd like ask the proper ways to do this. For example, How to check "manager.py runserver" command has finished and startup, then open browser, instead sleep 5 Seconds. Can I detect Django server console be closed and do some tasks like kill process.