Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django StreamingHttpResponse ConnectionAbortedError
I've tried to use django to stream my camera and it does work well. But when I close the web page in my browser, django starts to throw errors. I've tried try except but doesn't work. Is there some way that I can do to at least prevent django from crashing and make it work normally? Here is the code(omit the import sentences): class VideoCamera(object): def __init__(self): with open('config.json', 'r') as f: conf = json.load(f) self.video = cv2.VideoCapture(conf['rtspURL']) def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() return image def gen(camera): while True: frame = camera.get_frame() ret, jpeg = cv2.imencode('.jpg', frame) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n\r\n') @gzip.gzip_page def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()),content_type="multipart/x-mixed-replace;boundary=frame") def monitor(request): return render(request, 'monitor.html') And here are the errors throwed: Traceback (most recent call last): File "C:\Environment\Anaconda3\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Environment\Anaconda3\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Environment\Anaconda3\lib\wsgiref\handlers.py", line 279, in write self._write(data) File "C:\Environment\Anaconda3\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Environment\Anaconda3\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [12/Sep/2018 11:19:06] "GET /monitor HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 11826) Traceback … -
makemigrations reponses No changes detected when app_label is specified
I have 2 mysql databases and I want to create a new model to the second one (analysis_db), but after running makemigrations, it says "No changes detected". Here are my codes In settings.py ( I added myapp to INSTALLED_APPS ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DB_DEFAULT_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': DB_HOST, 'PORT': '', 'OPTIONS': { 'sql_mode': 'traditional', } }, 'analysis_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DB_ANALYSIS_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': DB_HOST, 'PORT': '', 'OPTIONS': { 'sql_mode': 'traditional', } } } DATABASE_ROUTERS = ['my_project.routers.TestRouter'] In routers.py class TestRouter: """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): if model._meta.app_label == 'analysis_data': return 'analysis_db' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'analysis_data': return 'analysis_db' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'analysis_data' or \ obj2._meta.app_label == 'analysis_data': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'analysis_data': return db == 'analysis_db' return None In models.py class TestModel(models.Model): id = models.AutoField(primary_key=True) val1 = models.IntegerField() val2 = models.IntegerField() class Meta: app_label = 'analysis_data' db_table = 'test_table_on_db' However, if I remove app_label = 'analysis_data' from models.py, and run makemigrations again, it works, … -
Django models and Celery periodic tasks
I am working on a IoT projects with Django.I don't like to do tedious coding.The problem here is I have a model name Period like this: class Period(models.Model): number = models.PositiveIntegerField(primary_key=True) start_time = models.TimeField() end_time = models.TimeField() In addition, i want my Celery beat to do something at Period.end_time and I add this code. Code in mysite/app/tasks.py. @app.on_after_configure.connect def setup_periodic_tasks(): all_periods = Period.objects.all() for period in all_periods: hour = period.end_time.hour minute = period.end_time.minute add_periodic_task( crontab(hour=hour, minute=minute), do_some_thing.s() ) Here is the other files: #mysite/mysite/celery.py from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartschool.settings') app = Celery('smartschool') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) #mysite/mysite/__init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__=['celery_app'] #mysite/mysite/settings.py ##Celery part. CELERY_BROKER_URL = 'amqp://' CELERY_RESULT_BACKEND = 'rpc://' CELERY_ACCEPT_COTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Ho_Chi_Minh' CELERY_IMPORT = ('timetable.tasks') CELERY_BEAT_SCHEDULE = { #'test': #{ … -
dynamic choice field in admin django
I am trying to add dynamic choices in my admin form. My model definition is: class teams(models.Model): team_lead_choice = ((' ', 'Select Team'),) team_name = models.CharField(max_length=20, primary_key=True) team_description = models.CharField(max_length=20) team_lead = models.CharField(max_length=20) slug = models.SlugField(max_length=20, unique=True, default=None) def __str__(self): return self.team_name def save(self, *args, **kwargs): self.slug = slugify(self.team_name) super(teams, self).save(*args, **kwargs) and my admin is: class TeamsForm(forms.ModelForm): team_lead_choices = (('', 'Select Team lead'),) team_lead = forms.ChoiceField(choices=team_lead_choices) def __init__(self, team_lead_choices=(), *args, **kwargs): super(TeamsForm, self).__init__(*args, **kwargs) users = User.objects.values_list('username', flat=True).filter(is_staff=True, is_superuser=False) \ .order_by('username') team_lead_choices = (('', 'Select Team lead'),) for u in users: team_lead_choices += ((u, u),) self.fields['team_lead'].choices = team_lead_choices class Meta: model = teams fields = ('team_name', 'team_description', 'team_lead') class TeamsAdmin(admin.ModelAdmin): list_display = ['team_name', 'team_description', 'team_lead'] fields = ['team_name', 'team_description', 'team_lead'] search_fields = ['^team_name', '^team_lead'] form = TeamsForm it correctly updated the field with drop down choices but when i try to add new values in admin form. On saving, it empties all the fields and gives error "field is required" enter image description hereenter image description here -
Celery immediately exceeds memory on Heroku
I'm deploying a Celery process to Heroku and every time it starts, it immediately starts to rack up memory usage and crash after it exceeds the maximum. I only have one task called "test_task" that prints once per minute. This is Django app using Celery with a Redis backend hosted on Heroku. Proc file: web: daphne chatbot.asgi:channel_layer --port $PORT --bind 0.0.0.0 --verbosity 1 chatworker: python manage.py runworker --verbosity 1 celeryworker: celery -A chatbot worker -l info Heroku logs: app[celeryworker.1]: [INFO] 2018-09-11 23:06:36,710 : Scheduling celery jobs... app[celeryworker.1]: [INFO] 2018-09-11 23:06:36,880 : adding minute task app[celeryworker.1]: app[celeryworker.1]: -------------- celery@f46a12fb-1666-449a-b287-2ce90f95cf2c v4.2.0 (windowlicker) app[celeryworker.1]: --- * *** * -- Linux-4.4.0-1027-aws-x86_64-with-debian-jessie-sid 2018-09-11 23:06:37 app[celeryworker.1]: -- * - **** --- app[celeryworker.1]: ---- **** ----- app[celeryworker.1]: - ** ---------- [config] app[celeryworker.1]: - ** ---------- .> app: chatbot:0x7f1c2a5ad5d0 app[celeryworker.1]: - ** ---------- .> transport: redis://east-1-4.ec2.cloud.redislabs.com:13275// app[celeryworker.1]: - ** ---------- .> results: disabled:// app[celeryworker.1]: - *** --- * --- .> concurrency: 8 (prefork) app[celeryworker.1]: -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) app[celeryworker.1]: --- ***** ----- app[celeryworker.1]: -------------- [queues] app[celeryworker.1]: .> celery exchange=celery(direct) key=celery app[celeryworker.1]: app[celeryworker.1]: app[celeryworker.1]: [tasks] app[celeryworker.1]: . companies.tasks.test_task app[celeryworker.1]: heroku[celeryworker.1]: Process running mem=616M(120.4%) heroku[celeryworker.1]: Error R14 (Memory quota … -
How do I differentiate between Django messages in templates while using nested modals?
So I've racked my brain for about 2 days now trying to figure out how to get this to work, and even the cheap work-arounds have failed, or have introduced other problems. At the heart of my issue, I believe, I have nested modals and a custom bootstrap form in both: the first for login, and the second for signup. Let's assume in one case I want to do all my validations server-side, and possibly get full control over each of the error validation messages, as well as how and where they should appear respective to their input. How do I do that using django.contrib.messages? If could use some of Bootstrap 4's built-in methods for validation as a first line of defense, or data-validate-on-blur to work like how it does with Zurb Foundation's Abide, even better. As it stands, and with the various work-arounds I've found on Stack Overflow, i.e. using jQuery to toggle the modal (not the prettiest as it reloads the page), the best I've been able to do still bleeds my messages in between modals and/or my redirect views. I've read threads on how to clear Django messages, and thought that might be a fix, so if … -
django model field depend on the value of another field
The use case of my application is I will have various fields to fill and among them one is Industry field and another is Segment Field for brand. The industry field is like category that brand falls into. So, if i choose the industry as Health Care for XYZ brand then the segment field should show the items like 'Ayurveda', 'Dental Clinics' (all health care related items). Basically, its like sub-category. Here is a sample model class Industry(models): name = models.CharField() # value will be filled from admin side class BusinessModel(models): industry = models.ForeignKey(Industry, blank=False, null=False, related_name='industry', on_delete=models.CASCADE) # segements = models.ForeignKey() total_investment = models.CharField() # will be choice field This is a simple model and I have not created Segment model as I am not sure how to approach to this problem. I am just curios to know, if for such case, do i have to something special in models.py or in the view side. Such type of things get arise during development phase, thus, I want to be clear on problem solving pattern in django. -
Django - is possible to use function views that are not registered in URL.py as pure functions?
I have a Add to Cart button in a detail view. It works fine, but the problem is I don't want it to redirect to any other page after I add some books to my cart. I just want it stay in the current page. Also is possible to just make a function somewhere which can be called by the button? book/templates/book/detail.html: <form method="get" action="{% url 'cart:add_to_cart' %}"> {% csrf_token %} <select name="quantity"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> <input name="bookID" value=" {{ book.id }} " hidden> <button type="submit"> Add to Cart</button> </form> cart/views.py: def add_to_cart(request): q = request.GET.get('quantity') book_id = request.GET.get('bookID') if book_id and q: <some code to edit BooksInCart model here> else: return BooksInCart.none() cart/urls.py: app_name = 'cart' urlpatterns = [ path('(I dont want it to direct', views.add_to_cart, name='add_to_cart'), path('<int:id>', views.ItemListView.as_view(), name='items'), ] -
use two models in Django class based view
I am trying to retrieve the latest id from the TemporaryModel or confirmation number from the ProductionModel. The intention is to compare them and use the larger one. But I always get none from the ProductionModel. I cannot figure out why, could anyone please help? Below code is part of the code from a Django createview class: def get_context_data(self, **kwargs): context = super(TemporaryModelCreate, self).get_context_data(**kwargs) latestobjectId = None try: latestIdFromTemporaryModel = TemporaryModel.objects.latest("id") latestIdFromProductionModel = ProductionModel.objects.latest("id").ConfirmNumber except: latestIdFromTemporaryModel = None latestIdFromProductionModel = None if latestIdFromTemporaryModel is None and latestIdFromProductionModel is None: latestobjectId = 1 elif latestIdFromTemporaryModel is None and not(latestIdFromProductionModel is None): latestobjectId = latestIdFromProductionModel+1 else: latestobjectId = latestIdFromTemporaryModel+1 context['latestobjId'] = latestobjectId return context -
Is it possible to missmatch opening and end tags in xml on purpose?
So, a few literary students tried to digitaly edit some text and unfortunatly they've ended up with a few hundred pages of <author> H.P.Lovecraft <authorEnd> <placeTime> Arkham <placeTimeEnd> I'm now writing a django application to shape those into something somewhat usefull. I do have a working function to check and replace them, but it's really clumsy and awkward. Now I'm wondering, if you could replace < /author> somehow with < /authorEnd> and use an xml-parse to process the whole thing. Thanks. -
how to use value for loop in text content in django
I have textfield value that is populated in by the user. I want to create my own "tag" of sorts so that when present, I can loop through its return value. Here is example of content that my be entered by the user: my awesome content starts (-- assets --) ending portion of my content I'm thinking a template tag would be used for this do something along the lines of: {{ mycontent|check_if_assets_present }} Then this would print something like: my awesome content starts Asset 1 Asset 2 Asset 3 ending portion of my content How can I accomplish this in a django template? -
Django: make stringed byte-string back to original
Good day. Now I make some application with new users model and email as login. And simple confirmation with users email. The plan is: User enters his or her data, email is first of course. Next He receives some code (formed as urlsafe_base64_encode(force_bytes(users_email))). This code is planned to be entered by hand or with copy-paste in confirm field. And users account is active. In python console this chain works good. The problem is: when user enters by hand or copy-paste the code from email raises DjangoUnicodeDecodeError with 'utf-8' codec can't decode byte... You passed in b'm\xb5\xa5\xad\xb... comments. Some analysis shows that in post function the code arrives as string "b'bla-bla-bla". But not as byte-string b'bla-bla-bla', which is good for getting original string with force_text(urlsafe_base64_decode(the_code)). Any ideas to convert the string object with b starting symbol to more comfortable byte-string object? Or there is another way to make some secret encoding/decoding based on user-name (user-email) ? Thanks anyway. -
Python3 Django: Getting Invalid Salt Error With Bcrypt
So was just trying to make a basic login and registration boiler plate with custom validations. But for some reason I am continuously getting an invalid salt error when it comes time to try and log in. Might I add, the way have my bcrypt set up has worked in prior projects.. But when I upgrade to Python3, for some reason it gets this error for me.. I started putting print statements throughout the entire app, and narrowed it down to my Login Form Validator. Here are the outputs:----- test display of logpassword: rrrrrr user password: b'$2b$12$B3O9.UiaswKJvXkKAG2o9uqMHi5XrRBSyvDIPYwEa/o4AgyoGDww.' what the encoded password we are seeing? b"b'$2b$12$B3O9.UiaswKJvXkKAG2o9uqMHi5XrRBSyvDIPYwEa/o4AgyoGDww.'" what is the encoded password from logpassword? b'rrrrrr' TEst 2 post data encode: b'rrrrrr' compare this with the following code below, and you'll see that the password is hashing correctly from the registration. However, the post data entered, when encoded, is not hashing/encoding it properly to be compared with the hashed password in the DB. Any help is greatly appreciated, as I've been stuck on this for quite some time.. Code: - Views.py Ill only post the relevant functions--- from django.shortcuts import render, redirect from django.contrib import messages from django.urls import reverse from time import … -
Pip install and Easy install Django and VirtualEnv not working
I am trying to install virtualenv and django and i keep getting errors.I tried using the whql file of virtualenv but still, no solution.My windows firewall is also turned off.This is the error message for virtualenv,The same thing happens when i try installing flask also. C:\Windows\system32>easy_install virtualenv Searching for virtualenv Reading https://pypi.python.org/simple/virtualenv/ Download error on https://pypi.python.org/simple/virtualenv/: [WinError 10061] N o connection could be made because the target machine actively refused it -- Som e packages may not be found! Couldn't find index page for 'virtualenv' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.python.org/simple/ Download error on https://pypi.python.org/simple/: [WinError 10061] No connectio n could be made because the target machine actively refused it -- Some packages may not be found! No local packages or working download links found for virtualenv error: Could not find suitable distribution for Requirement.parse('virtualenv') C:\Windows\system32>pip install virtualenv Collecting virtualenv Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connec tion broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip. _vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0 x0298DD70>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/virt ualenv/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connec tion broken by … -
Strange HTML and CSS behavior
One of my clients has been encountering this issue when she goes onto the app. I was wondering if anyone had any idea how to get it to show normally? Im not sure if this is a code issue or her computer. Everything is getting bunched together -
Django project global name 'user' is not defined
NameError at /friendship/profile/ global name 'user' is not defined \views.py in profile_view, line 51 def profile_view(request): p = Profile.objects.filter(user=user).first() u = p.user sent_friend_requests = FriendRequest.objects.filter(from_user=p.user) rec_friend_requests = FriendRequest.objects.filter(to_user=p.user) friends = p.friends.all() I keep getting this error its in the view its a django view it says that the problem is in the u = p.user I get this error, NameError at /friendship/profile/ global name 'user' is not defined -
csrf.py _reject: Forbidden (CSRF token missing or incorrect.)
I am getting a 403 forbidden error and WARNING csrf.py _reject: Forbidden (CSRF token missing or incorrect.) is django logs. Here is my html- function req() { var server_id = $( "#server option:selected" ).val(); $.post("/sp/add_req", JSON.stringify({ cir: {{ cir }}, server_id: server_id, csrfmiddlewaretoken: {{ csrf_token }}}), function (data) { console.log(data) }); } and views.py- def add_request(request): .... return JsonResponse({'success': True}) I have the 'django.middleware.csrf.CsrfViewMiddleware' in settings. What is wrong and how to solve this? -
Should I use Django and Django Rest Framework in the project or create 2 project
We want to use Django Rest Framework for a project so that we won't code another backend when we will build a mobile app. The project is a big one and we do not want to get lost. What is the best solution? And please why? : Integrate Rest in Django app Divide Django and Rest in 2 different apps -
Which is the best way to create tag model?
I'm creating a ecommerce website, i created a user, a product model and now i have to create a tags . I found two ways: the first one each tag have many products. the second one each product have many tags. class Product(models.Model): tags = models.ManyToManyField(Tag, related_name='Product') class Tag(models.Model): products = models.ManyToManyField(Product, blank=True) First method http://tinystruggles.com/2015/06/04/django-api-resource-with-tags.html Second one https://github.com/codingforentrepreneurs/eCommerce/blob/master/src/tags/models.py -
Iterative forms using Django models data
I have a model where students sign up in a group (students/models.py) class Student(models.Model): name = models.CharField(max_length = 500) number = models.IntegerField(default = 0) group = models.IntegerField(default = 1) Now, I want to take assistance every day using another model (assistance/models.py): class Assistance(models.Model): date = models.DateField(timezone.now) name = models.CharField(max_length = 500) yes_no = (('Yes', 'Yes',), ('No', 'No',)) assistance = (choices = yes_no, max_length = 50) I want to generate this model after select a group number and fill it for every student in that group. How can I do that? Thanks -
form validation Not Working Django and print just on message
form validation Not Working Django and print just on message ... message : form is not valid! why? please answer my question! i am a django Beginner!! mycode in form.py: efrom django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms.widgets import CheckboxSelectMultiple from blog.models import Category from wsgiref.validate import validator class PostForm(forms.Form): title = forms.CharField(max_length = 100, min_length= 1,) slug = forms.SlugField(allow_unicode=True) message = forms.CharField(widget = forms.Textarea) banner = forms.ImageField() category = forms.ModelChoiceField(queryset=Category.objects) authors = forms.ModelChoiceField(queryset=User.objects, widget=CheckboxSelectMultiple) def clean(self): cleaned_data = super(PostForm, self).clean() slug = cleaned_data['slug'] if not "sepehr" in slug: raise forms.ValidationError("here we have some errors !") return cleaned_data and my code in views: class HoemView(generic.TemplateView): template_name = 'blog2/create.html' def get(self, request): form = PostForm() context = { 'form':form } return render(request, self.template_name, context) def post(self, request): form = PostForm(request.POST, request.FILES) if form.is_valid(): return HttpResponse('form is valid!') return HttpResponse('form is not valid!') -
How to show multiple images from models through loop in django templete
I am trying to create a page where I can show product details with an image from my data models using a loop in Django model, but when I go item list it's work for details except image, in image section, it shows alt text. please help me. my models: class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=150) category = models.ForeignKey(Category, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) model_pic = models.ImageField(upload_to = 'static/media/') def __str__(self): return self.name my views: def item_list(request, category_id): category_name = Category.objects.get(pk=category_id) list_items = Item.objects.filter(category=category_name) context = { 'list_items': list_items, } return render(request, 'inventory/item_list.html', context) my templete: {% for item in list_items %} <tr> <td>{{ forloop.counter }}</td> <td>{{ item.name }}</td> <td>{{ item.category }}</td> <td>{{ item.is_active }}</td> <td><a href="{% url 'item_delete' item.pk %}">Delete</a></td> <td><img src="{{ item.model_pic.url }}" alt="Photo"></td> </tr> {% endfor %} output:enter image description here -
How to declare a dynamic link in django template?
What I want to do is to create a list within another. Example home/4/5/ etc Also if I want to change the name from path it gives an error saying no reverse. path('findstudent/', views.FindStudent.as_view(), name='findstudent'), path('findstudent/<int:pk>/', views.FindStudentdetail.as_view(), name='findstudent'), path('findstudent/<int:pk>/<int:pk_alt>/', views.FindStudentresult.as_view(), name='findstudent'), @method_decorator(login_required, name='dispatch') class FindStudent(ListView): template_name = 'Dashboard/findStudent.html' model = Student fields = ['sbtc'] def get_queryset(self): batch = Student.objects.values_list('sbtc').distinct() return batch @method_decorator(login_required, name='dispatch') class FindStudentdetail(ListView): template_name = 'Dashboard/findStudentdetail.html' model = Student fields = ['all'] def get_queryset(self): student = Student.objects.filter(sbtc=self.kwargs['pk']) return student @method_decorator(login_required, name='dispatch') class FindStudentresult(ListView): template_name = 'Dashboard/findStudentresult.html' model = Result fields = ['all'] def get_queryset(self): result1 = Result.objects.select_related('Student') result = Result.objects.filter(id=self.kwargs['pk_alt']) return result The problem is here: How can I define the path/url in the template! <div class="form-group"> {% for student in object_list %} <li><a href="{% url **'Dashboard:findstudent'** %}">{{student.sroll}} {{student.snam}}</a></li> {% endfor %} </div> -
Using asyncio.create_subprocess_shell within Django channels Consumer
Whenever a client (i.e. consumer) connects to my Django server, I want to execute a command in the command line: from channels.generic.websocket import AsyncWebsocketConsumer import asyncio class Consumer(AsyncWebsocketConsumer): async def do_command(self): process = await asyncio.create_subprocess_shell('sudo /bin/systemctl start ssh') await process.wait() print("command has finished") async def connect(self): asyncio.get_event_loop().create_task(self.do_command()) print("Finished scheduling do_command task") When I run the above code, I see that "Finished scheduling do_command task" is printed every time a client connects to my server. However, "command has finished" never gets printed. Why is that? The issue seems to be specifically with the await process.wait. For some reason, the command never finishes executing (i.e. process.returncode is always None). However, the following code works fine: import asyncio async def do_command(): process = await asyncio.create_subprocess_shell(cmd='sudo /bin/systemctl start ssh') await process.wait() print("Finished process.wait") print(process.returncode) loop = asyncio.get_event_loop() task = loop.create_task(do_command()) asyncio.get_event_loop().run_until_complete(task) loop.close() print("Finished Go Task") returns: Finished process.wait 0 Finished Go Task Why does "command has finished" never get printed? -
Get_Slug_Field() example for multiple slugs in Django 2.1?
I want to find a way to add multiple slugs from different models to one view. Either with get_slug_field and get_object; or other ways are appreciated as well.. But please, take into consideration that this is Generic View in which I am looking for the solution.