Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing multiple parameters to Django URL - unexpected keyword argument
I wanted to document this question as much as possible in order to be able to detail the origin of the problem. I have the following model named LodgingOffer, to create a lodging offer and detail their information class LodgingOffer(models.Model): # Foreign Key to my User model created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ad_title = models.CharField(null=False, blank=False, max_length=255, verbose_name='Título de la oferta') slug = models.SlugField(max_length=100, blank=True) # ... Another fields ... def __str__(self): return "%s" % self.ad_title def get_absolute_url(self): return reverse('host:detail', kwargs = {'slug' : self.slug }) # I assign slug to offer based in ad_title field,checking if slug exist def create_slug(instance, new_slug=None): slug = slugify(instance.ad_title) if new_slug is not None: slug = new_slug qs = LodgingOffer.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug # Brefore to save, assign slug to offer created above. def pre_save_article_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_article_receiver, sender=LodgingOffer) For this model, I have a DetailView named HostingOfferDetailView . An important objective I want to pursue and for which I ask this question is that in the detail view of an LodgingOffer object, I should be able to contact the owner of that offer (object … -
Django order approval flow
Hello guys i'm new to django,i have tried a lot but didn't get any solution.My task is 'order approval form' .There are 'N' no.of users and user has to fill form with requirements,after filling and submitting its that form data/notification should sent to manager/admin,he can check/delete /approve,if he approves it should go to next state/stage of flow how to do this workflow ? -
Django shell plus invalid arguments in virtualenv
I created a virtualenv to set up for Django upgrade to version 1.8. but when trying to run shell plus I am getting an error about invalid arguments: py manage.py shell_plus Trace: Traceback (most recent call last): File "manage_sched_dev.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 382, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 316, in create_parser help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output') File "c:\python27\Lib\optparse.py", line 1018, in add_option raise TypeError, "invalid arguments" TypeError: invalid arguments I have no clue why this is happening. I tried installing ipython in the virtualenv because I know shell plus uses ipython, but that didn't seem to help. -
Application not able to access the profile pic and posts using DjangoAllAuth
I am trying to access the profile picture and posts of the user using Django-AllAuth. Here is the template where I am trying to load the profile image: <html> <body> Welcome back {{ user.first_name }} {{ user.age }} <img src={{user.cover.source}} height="60" width="60"> <a href="/">Home</a> </body> </html> Here is the view.py def fb_personality_traits(request): # logger.debug('FB Page Loaded') return render(request, 'home/facebook_personality_traits.html') Settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = '/facebook_personality_traits/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'public_profile', 'user_photos'], # 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'js_sdk', 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'cover', 'posts', 'age', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } ACCOUNT_LOGOUT_ON_GET = True Here I am not getting the image. See the below result: What I want to achieve? 1) I want to display the profile image on the screen. 2) I want to get the posts of the user loggedin in the view.py and send it on the screen to display on the template. -
Django-storages save images webp as octet-stream
when I try to save pillow images using django-storages to store in S3, webp images save them as octet-stream. You should also save images in JPG. I leave below my configuration of django-storages AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'public, max-age=2592000', } AWS_DEFAULT_ACL = 'public-read' AWS_QUERYSTRING_AUTH = False So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='WEBP', optimize=False, ) So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='JPEG', optimize=False, ) Thanks! -
Django different types of user
I want to build a simple website with Django, and so far I have made a sign-up form that everyone can sign up and publish some announcement. For next stage I want to make the user can only view the announcement by default, I also want to have another type of user can view and create an announcement. How should I build my user model and sign up forms? Should I use things like permission or AbstractUser? the current sign up forms.py I am using is like from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model class UserCreateForm(UserCreationForm): class Meta: fields = ("username", "email", "password1", "password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" and the views about the announcement is like #show all announcement class AnnouncementListView(ListView): ... #show a specific announcement class PostDetailView(DetailView): ... #create a announcement class CreatePostView(LoginRequiredMixin,CreateView): ... Thanks! -
How to redirect when loading a FormView?
Using the class based view FormView I want to redirect to a different page if a user is already activated. So I've tried overriding the get_form_kwargs function: class UserActivateView(AnonymousRequiredMixin, FormView): ... def get_form_kwargs(self): .... if profile.activated: # User is already activated an can log in messages.info( self.request, 'You are already activated. ' 'Login or click forgot password if you have forgotten' ) redirect(to=reverse_lazy('auth_login')) .... return kwargs Using this method the message is added but the redirect is never done. Am I doing this redirect at the correct place, I've been using ccbv as a reference -
Django migration issue: dynamic_forms missing migration as a dependency
One of my migrations specify a particular dynamic_forms migration as a dependency: dependencies = [ ('dynamic_forms', '0004_auto_20170110_1645'), # other deps ] But that file doesn't exist in the migrations directory under the lib's instalation path. The migrations for the version of dynamic_forms I am using, 0.3.3, are: 0001_initial 0002_auto_20140124_1844 0003_auto_20140916_1433 Since the dependency migration doesn't exist, when running migrate, showmigrations, or any other migration-related task, I am logically getting the following error: django.db.migrations.graph.NodeNotFoundError: Migration some_app.0001_initial dependencies reference nonexistent parent node (u'dynamic_forms', u'0004_auto_20170110_164 5') I tried updating the package to its most recent version, 0.5.3, but it didn't help either because it doesn't have that migration file. I tried faking the migrations for dynamic_forms just to see if it helped somehow: py manage.py migrate dynamic_forms --fake But it didn't even go through because the same missing dependency error occurred. I am not sure how to deal with this and although about I did find some information about missing migrations in the dynamic_forms package I couldn't learn how to solve the issue. -
django-import-export : getting post_export to update models
Please how do i updated exported Company model below using post_export signal. I don't want to export items not exported before. So the best thing is using signals. However, if i print the model in the signal at the end of the code below, I get a type class e.g <class 'app.models.Company'> I know am doing something wrong by saving a model but can't find my way arround. Maybe I'm not understanding the documentation of django-import-export library which is found here. #models.py class Company(models.Model): class Meta: verbose_name_plural = "Companies" company_name = models.CharField(max_length=254, blank=True) website = models.URLField(max_length=254, unique=True) address = models.CharField(max_length=254, blank=True, null=True) imported = models.BooleanField(default=False) exported = models.BooleanField(default=False) user = models.ForeignKey(User) def __str__(self): if self.company_name: return self.company_name return self.domain #admin.py from django.dispatch import receiver from import_export.signals import post_import, post_export class CompanyResource(resources.ModelResource): class Meta: model = Company fields = ('website', 'user', 'country', 'source', 'industry') @admin.register(Company) class CompanyAmin(ImportExportModelAdmin): resource_class = CompanyResource list_display = ('domain', 'website', 'exported', 'added_on') list_filter = ('user', 'country', 'imported', 'exported', 'added_on') import receiver from import_export.signals import post_import, post_export @receiver(post_export, dispatch_uid='ss1') def _post_export(model, **kwargs): print(model) model.exported = True model.save() # This line when included raises Error: "save() missing 1 required positional argument: 'self'" so code breaks here -
How to use model's default value in the serializer?
I have a serializer defined by model's fields in the following way: class MyModel(models.Model): f1 = models.CharField(max_length=10, default='abc') class Serializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['f1'] Bit, running: Serializer({}).data Return an empty object. So how can I use the default value declared in the model? I know I can repeat the field in serializer, like that: class Serializer(serializers.Serializer): f1 = serializers.CharField(default='abc') Serializer({}).data This will return the expected {'f1' : 'abc'}, but I do not want to repeat myself. -
error while using makemigration in django
i am working on a development server running python3.6 and django 1.11 with virtualenv when I use "python manage.py makemigrations" i get this error Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 13, in <module> from django.core.management.base import ( File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/core/management/base.py", line 17, in <module> from django.db.migrations.exceptions import MigrationSchemaMissing File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/db/migrations/__init__.py", line 1, in <module> from .migration import Migration, swappable_dependency # NOQA ImportError: No module named 'django.db.migrations.migration' please help me -
Django annotate Avg on model field
I have these models: class Agency(models.Model): pass class User(models.Model): agency = models.ForeignKey(Agency) class Feedback(models.Model): rating = models.DecimalField() user = models.ForeignKey(User) and I want to annotate a queryset with the average of all ratings. I expected this to work: Feedback.objects.annotate(avg_rating=Avg('rating')).values('rating', 'avg_rating') but it just outputs this: <QuerySet [{'rating': 0.8, 'avg_rating': 0.8}, {'rating': 0.2, 'avg_rating': 0.2}, {'rating': 0.6, 'avg_rating': 0.6}, {'rating': 1.0, 'avg_rating': 1.0}, {'rating': 0.4, 'avg_rating': 0.4}]> As you can see the average should be 3.0. Where am I going wrong? For a bit of clarity, I'm trying to do something like this: agencies = Agency.objects.annotate( avg_rating=Coalesce(Subquery( Feedback.objects.filter(user__agency_id=OuterRef('pk')) .values('rating') .annotate(avg_rating=Avg('rating', output_field=DecimalField())) .values('avg_rating') ), 0) ) where the average rating is per agency. Any ideas? -
Makemigrations error : django.db.utils.OperationalError: no such table
when I makemigrations i get the following error: django.db.utils.OperationalError: no such table: django_site Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python27\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\campaign\models.py", line 5, in <module> from sinUser.models import sinUser, sinUserCategories File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\sinUser\models.py", line 4, in <module> from functionUtility.sendEmails import sendEmailFunctionIsError File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\functionUtility\sendEmails.py", line 12, in <module> HOSTNAME = Site.objects.get_current().domain File "C:\Python27\lib\site-packages\django\contrib\sites\models.py", line 63, in get_current return self._get_site_by_id(site_id) File "C:\Python27\lib\site-packages\django\contrib\sites\models.py", line 35, in _get_site_by_id site = self.get(pk=site_id) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 374, in get num = len(clone) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 232, in __len__ self._fetch_all() File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 894, in execute_sql raise original_exception django.db.utils.OperationalError: no such table: django_site I am newbies python programming some one can help me thank you -
Django 1.11 EmailMultiAlternatives: ValueError: need more than 1 value to unpack
Iam trying to send an email using EmailMultiAlternative. Using Django 1.11, Python 3.4. However I am getting ValueError. Am using the SMTP backend.This is the code: subject = "Hi {} !".format(user.username) sender = settings.DEFAULT_FROM_EMAIL recipients = [user.email, ] html_content = render_to_string('email/hello.html', {'url': url, 'first_name': user.first_name, 'last_name': user.last_name, 'static': HOST + settings.STATIC_URL,}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, sender, recipients) msg.attach_alternative(html_content, "text/html") msg.send(). However I am get the following error: ValueError: need more than 1 value to unpack Complete traceback here: Traceback (most recent call last): File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/edit.py", line 183, in post return self.form_valid(form) File "/home/george/george/project/new_beco/applications/accounts/views.py", line 87, in form_valid msg.send() File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/backends/smtp.py", line 123, in _send from_email = sanitize_address(email_message.from_email, encoding) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/message.py", line 136, in sanitize_address nm, addr = addr ValueError: need more than 1 value to unpack -
Image size change by URL Request like Instagram style
I noticed that Avatar in Instagram (sorry I cant post links): thumbnail (150 x 150) scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s150x150/e15/11821182_168255950173048_11130460_n.jpg low_resolution (320 x 320) scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s320x320/e15/11821182_168255950173048_11130460_n.jpg standard resolution (640 x 640) scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s640x640/sh0.08/e35/11821182_168255950173048_11130460_n.jpg When we change the dimenstion in URL (s640x640 -> s128x128), the dimension of image change automatically. What is it and How can I handle this in Python Django? Is there any package to do this? Thank you! -
Custom inclusion templatetag with djangoCMS render_model
I have created a website with djangoCMS and make heavy use of apphooks, cms plugins, wizards, etc. We have a simple app with just one model holding the core data that should be displayed on the homepage. models.py from django.db import models from django.utils.text import slugify from django.urls import reverse from cms.models.fields import PlaceholderField from djangocms_text_ckeditor.fields import HTMLField class Programme(models.Model): name = models.CharField(max_length=60, unique=True) slug = models.SlugField() icon = models.CharField(max_length=50, unique=True) introduction = HTMLField() overview = PlaceholderField( 'programme_overview', related_name='programmes_overview' ) def __str__(self): return self.name def get_absolute_url(self): return reverse( 'programmes:programme-detail', kwargs={'slug': self.slug} ) def save(self, *args, **kwargs): if not self.pk: self.slug = slugify(self.name) super(Programme, self).save(*args, **kwargs) I decided to create a custom inclusion templatetag for this purpose. templatetags/programmes_tags from django import template from ..models import Programme register = template.Library() @register.inclusion_tag('programmes/programme_list.html') def programme_list(): programmes = Programme.objects.all() return {'programmes': programmes} In the template I use render_model from the cms_tags, because the editors should be able to edit the contents in the frontend. Here is the template: templates/programmes/programme_list.html {% load cms_tags %} {% for programme in programmes %} <div class="col-lg-2 col-md-4 col-sm-6 col-xs-12 text-center flex-item"> <div class="service-box"> <i class="fa fa-4x {{ programme.icon }} wow bounceIn text-primary" style="visibility:visible;"></i> <h3> <a href="{% url 'programmes:programme-detail' programme.slug %}"> … -
Django Form Fields won't show in my template
The form field won't show up in the browser. There is only the submit button showing up. views.py code: def vote(request, pk): # check if request is post if request.method == 'POST': # create a form and populate it with data from request form = forms.Vote(request.POST) if form.is_valid(): fact = Fact.objects.get(pk=pk) fact.votes += int(form.cleaned_data['vote']) fact.save() return HttpResponseRedirect(reverse( 'facts:detail', args=(pk,) )) else: form = forms.Vote() return render(request, 'facts/fact_detail.html', {'form': form}) template(fact_detail.html) code: <form method='POST'> {% csrf_token %} {{ form }} <input type="submit" value="vote" /> </form> Form class(forms.py) code: VOTE_CHOICES = [ (1, 'upvote'), (0, 'downvote') ] class Vote(forms.Form): vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.RadioSelect()) -
Django test deleteview for model with overwritten 'delete' method.
I am writting tests for a django application that contains multiple deleteviews. I test all deleteviews with variations of the following code: #Object exists to begin with response = self.client.get(reverse('roldelete', kwargs={'pk': self.role.pk})) self.assertEqual(response.status_code, 200) #Object Can be deleted can be posted response = self.client.post(reverse('roldelete', kwargs={'pk': self.role.pk})) self.assertEqual(response.status_code, 302) #Object is actually deleted response = self.client.get(reverse('roldelete', kwargs={'pk': self.role.pk})) self.assertEqual(response.status_code, 404) #Query returns an empty result self.assertFalse( Role.objects.filter(pk=self.role.pk).exists()) All of this is working fine, however, in on of my models I've overwritten the default 'delete' method. Basically everytime I delete a 'TenantPurchase' object I want to check for the existence of a linked 'PurchaseRequest' object and delete it as well. I wrote the following code to do so: def delete(self, *args, **kwargs): try: purchase_user = self.user purchase_arrangement_period = self.item #Import here to avoid circular import from arrangement.models import ArrangementBuyRequest linked_buy_request = ArrangementBuyRequest.objects.filter( user=purchase_user, arrangement_period=purchase_arrangement_period) \ .order_by('request_date').last() linked_buy_request.delete() except (ArrangementBuyRequest.DoesNotExist, AttributeError) as e: pass super(TenantPurchase, self).delete(*args, **kwargs) When I test manually on our development server, I behaves as it should. Linked buy Requests are deleted and no errors are thrown. However, all my Unittests for this model fail. It passes the first three tests (assert 200, assert 302, assert 404) But a direct … -
Django loop through list
How do you loop trough a list in django templates with a for loop? my problem is with trying to fetch list.0 list.1 list.2 But when running the code i don't get anything {% for i in range %} {% for key, value in list.i.items %} {{ key }} {{ value }} {% endfor %} {% endfor %} where i should be list.0-2 but it doesn't show anything on screen -
In form view, how to put the template_name on the current page
Everything is in the title, I have a problem with the form error and I think to solve it I have to put the template name on the current page. Thanks =) -
Not able to link the template page of Django
I am trying to make an application using django-allauth; My Django version is 1.11.5. I am trying to display the result on another template: facebook_personality_traits.html Here is the code: settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = 'facebook_personality_traits/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts'], # 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'js_sdk', 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True } } ACCOUNT_LOGOUT_ON_GET = True views.py def fb_personality_traits(request): # logger.debug('FB Page Loaded') return render(request, 'home/facebook_personality_traits.html') urls.py url(r'^facebook_personality-traits/&', views.fb_personality_traits, name="fb_personality_traits"), facebook_personality_traits.html <html> <body> Welcome back {{ user.first_name }} {{ user.last_name}} <a href="/">Home</a> </body> </html> But I could able to make it run effectively. I guess there is some issue where I have declared the url for the site. Here is the snapshot of the error: Kindly suggest me the missed part. -
Can I override Django password form layout?
I have overridden the Django login and registration forms by creating the templates registration/login.html, registration/logout.html, registration/registration_closed.html and registration/registration_form.html. However, the password change forms are in the original style. Unlike the existing forms, it doesn't look like django-registration.registration.auth_urls specifies HTML templates for these password forms. So how can I override them to look like my custom templates? -
How to detect related models get saved in django model and save the instance model
I am working on django, and I am in a situation, that I need to run some function, after all the related models of django model get saved in database. Let say I have a model models.py from . import signals class Video(models.Model): """Video model""" title = models.CharField( max_length=255, ) keywords = models.ManyToManyField( KeyWord, verbose_name=_("Keywords") ) When the new instance of video model is created. I need to 1. All the related models get saved first. a. If the related models are empty return empty or None 2. and then Save this video instance. I tried to do it using post_save signals, but couldn't succeded as there is no gurantee that related models get saved first that this video model. from django.db.models.signals import post_save, pre_delete, m2m_changed from django.dispatch import receiver from .models import Video @receiver(m2m_changed, sender=Video) @receiver(post_save, sender=Video) def index_or_update_video(sender, instance, **kwargs): """Update or create an instance to search server.""" # TODO: use logging system # Grab the id print("Id is", instance.id) # Keywords is empty as keyword instance is saved later than this instace. keywords = [keyword.keyword for keyword in instance.keywords.all()] print(keywords) # [] empty no keywords instance.index() @receiver(pre_delete, sender=Video) def delete_video(sender, instance, **kwargs): print("Delete index object") instance.delete() -
Using `subprocess` in a web service
I'm trying to leverage wkhtmltopdf to make a render-on-the-fly endpoint in a Django web app. The only way I'm aware of if to execute the external tool in a subprocess, for e.g.: from subprocess import Popen, PIPE from rendering.service.settings.local import WKHTMLTOPDF_PATH class HtmlToPdfView(APIView): def post(self, request): process = Popen([ WKHTMLTOPDF_PATH, '--disable-smart-shrinking', '-', '-' ], stdout=PIPE, stdin=PIPE, stderr=PIPE) stdout, stderr = process.communicate(input=bytes(request.data['html'])) return Response({'pdf': stdout}) But I have a general bad feeling about this. Should I worry about things like SIGFAULT? Am I even doing it right? Should I join() or poll() the process to make sure wkhtmltopdf is done with it's execution? Should I use close_fds=True? -
Is it ok to use app config variable as CharField choices?
Is it correct to use a AppConfig variable in model? myapp/apps.py class MyAppConfig(AppConfig): name = 'my_app' my_list = None def ready(self): self.my_list = ( ('a', 'A'), ('b', 'B'), ('c', 'C'), ) anotherapp/models.py AnotherModel(models.Model): options = models.CharField( max_length=1, choices=apps.get_app_config('my_app').my_list)