Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do we need set enviroment variables in wsgi.py and manage.py not in settings.py?
I read tips for setting enviroment variables in python project and usually enviroment variables set in settings.py, but for Django project recommended to set environment valiables in wsgi.py and manage.py. What is advantages of this solution (instead of setting variables in settings.py)? from dotenv import load_dotenv # Load environment variables from .env file. load_dotenv(verbose=True) -
Migrate command create all tables on second DB - Django
I have an app (ali) on my project (website) and I wanted it to have its own database. The problem is, when I run python manage.py migrate --database=ali, the command recreates all tables within my ali database; whereas the expected result would be to have only the ali_search database. Settings: # website.settings ... INSTALLED_APPS = [ 'base.apps.BaseConfig', 'ali.apps.AliConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'django_comments', 'mptt', 'tagging', 'zinnia', ] .... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'website', 'USER': 'website', 'PASSWORD': 'website', 'HOST': 'localhost', 'PORT': '5432', }, 'ali': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'ali', 'USER': 'ali', 'PASSWORD': 'ali', 'HOST': 'localhost', 'PORT': '5432', } } DATABASE_ROUTERS = [ 'ali.routers.AliRouter', ] .... Router: # ali.routers class AliRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'ali': return 'ali' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'ali': return 'ali' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'ali' or \ obj2._meta.app_label == 'ali': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'ali': return db == 'ali' return None Model: # ali.models from django.db import models class Search(models.Model): results = models.IntegerField() This is what I get by querying my ali DB with \dt: ali=# … -
Chat system using socket.io with django & nodejs
I am using django on 8000 & node on 4000 for a chat application using socket.now i am confused how to fix io initialization.& i want to apply socket on urls starting with /chat/. Any one can guide me ? -
Unable to migrate Django project, because of the 'auth' app
I updated Django from 1.11 to newest version. Also I updated Mezzanine. Now whenever I try to run the app, or migrate it, or showmigrations, or makemigrations, or fake mitrations, it crash with: Traceback (most recent call last): File "app/manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 275, in build_graph raise exc File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 245, in build_graph self.graph.validate_consistency() File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/graph.py", line 261, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/graph.py", line 261, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/graph.py", line 104, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0010_auto_20180912_1433 dependencies reference nonexistent parent node ('auth', '0009_alter_user_last_name_max_length') I do not really know what is the auth - it is not in my installed apps. This migration named: '0009_alter_user_last_name_max_length' is nowhere on my computer so I am out of ideas how to … -
Django : Radio select for images presented in a horizontal alignment in html form
I need an option in html form where only one image can be selected(something of radio type) and these images are presented in horizontal alignment. My seniors have done this using Django ModelForm and class based views but view made by me is function based and i am using html form instead of django form.Following are the views.py, models.py and forms.py made by seniors. models.py class Persona(models.model): name = models.CharField() image = models.ForeignKey(Image,on_delete=models.CASCADE,limit_to_choices={'choice_model':'profile'},) def __str__(self): return self.name class Image(models.Model): image =models.CharField(max_length=120,null=True) choice_model =models.CharField(max_length=120) def __str__(self): return self.image forms.py class HorizontalRadioSelect(forms.RadioSelect): template_name = 'dashboard/horizontal_select.html' class CustomChoiceField(forms.ModelChoiceField): def label_from_instance(self,obj): return mark_safe("<img src='%(media_url)simages/%(image)s' width=50 height=50/> " % {'media_url':settings.MEDIA_URL,'image':obj.image}) class PersonaForm(forms.ModelForm): persona_name = forms.CharField(label='Persona Name', max_length=100) image = CustomChoiceField(widget=HorizontalRadioSelect(), queryset=Image.objects.filter(choice_model="profile"),initial='1') views.py class PersonaCreateView(LoginRequiredMixin,TemplateView): form_class = PersonaForm template_name = "dashboard/c_persona.html" def get(self, request): form = self.form_class(None) return render(request, self.template_name, {"form": form}) def post(self,request): form = PersonaForm(data=request.POST) if form.is_valid(): persona = form.save() else: print(form.errors) return HttpResponseRedirect('/persona/') Below are the html form and views.py which have been made by me. HTML form <form method="get"> <div> </i><strong>Enter Persona Name</strong>: &nbsp <input type="text" name="persona_name" , required="",> </i><strong>Select Image</strong>: 'I need your help here.I need a horizontal options of images from which i can select only one image' <input type="submit" … -
Django DRF Image store private for user only on S3
I am using DRF for storing user uploaded images to S3 and in S3 i can see that images are public accessible using the URL. My concern over here is there any best way to secure this images and restrict them for owner of that image only to view it. I am using Heroku to deploy my DRF API Framework but i see this as security concern for my user who are uploading image files to S3 bucket. I am trying to isolate user images by their name it self.But still it is public so i can access this images for another user just figure it out there name. Here is S3 URL for media Images https://xxx.s3.amazonaws.com/media/persons/niravjoshi/20181218152410.jpg Here is my settings.py for Django import os import pymysql # noqa: 402 pymysql.install_as_MySQLdb() import dj_database_url from decouple import config import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #SECRET_KEY = 'feufm)u(pvsvb%&_%%*)p_bpa+sv8zt$#_-do5q3(vou-j*d#p' SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #Django Project Apps 'persons', 'rest_framework', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', #'social_django', … -
Django polymorphic proxy models: forbid creation of base model
I have a polymorphic model with proxy inheritance: class Property(PolymorphicModel): table = models.ForeignKey(Table) field1 = models.CharField() field2 = models.IntegerField() field3 = models.BooleanField() @abstractmethod def post(): class Property1(Property): class Meta: proxy = True def post(): # Property1 behavior pass class Property2(Property): class Meta: proxy = True def post(): # Property2 behavior pass I am trying to forbig the instantiation or creation of Property objects. Only the subclasses can be instantiated or created: # all these should be illegal Property(**kwargs) table.property_set.create(**kwargs) Property.objects.create(**kwargs) How would I go about it? I have tried making Property an abstract base class (abstract meta) but that is not quite the idea I am after. -
New Sentry-SDK with Django Rest Framework and debug = False does not report errors
I have set up Sentry and try to perform DjangoIntegration as described in the documentation here, but it seems that when debug is false in production it cannot report any errors. Within settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False if SENTRY_DSN: import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.celery import CeleryIntegration sentry_sdk.init( dsn=SENTRY_DSN, integrations=[ DjangoIntegration(), CeleryIntegration() ], environment="prod", ) When I see a Server Error 500 as a response from the api it seems it cannot forward it to Sentry Sentry 9.0.0, sentry-sdk 0.6.2, djangorestframework 3.9.0, django 2.0.9 -
Hide csrf token in get method in the django
how to hide csrf token from the get method in the django. when we call the get method then only parameters are need to visible in the browser URL rather the csrf token. -
NoReverseMatch at //, Reverse for ' ' not found. ' ' is not a valid view function or pattern name
NoReverseMatch at //, Reverse for ' ' not found. ' ' is not a valid view function or pattern name. As part of Mozilla Development challenge under Django Development,The rest of the site works fine but when trying to visit the page where the borrowed books and logged in as librarian with the required permssion "can mark returned" i get the above error View.py class LoanedBooksAllListView(PermissionRequiredMixin, generic.ListView): """Generic class-based view listing all books on loan. Only visible to users with can_mark_returned permission.""" model = BookInstance permission_required = 'catalog.can_mark_returned' template_name = 'catalog/bookinstance_list_borrowed_all.html' paginate_by = 10 def get_queryset(self): return BookInstance.objects.filter(status__exact='o').order_by('due_back') template {% if user.is_staff %} {% if perms.catalog.can_mark_returned %} <li class="nav-item active"><a class="nav-link" href="{% url 'all-borrowed' %}">All Books</a></li> {% endif %} {% endif %} apps urls.py urlpatterns += [ path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'), path(r'borrowed/', views.LoanedBooksAllListView.as_view(), name='all-borrowed'), ] Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/catalog/borrowed/ Django Version: 2.1.3 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog.apps.CatalogConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Template error: In template E:\MDN\django_projects\localibrary\catalog\templates\base_generic.html, error at line 8 Reverse for 'renew-book-librarian' not found. 'renew-book-librarian' is not a valid view function or pattern name. 1 : <!DOCTYPE html> 2 : <html lang="en"> 3 : … -
How can I resolve this error? TypeError: 'NoneType' object is not callable
I am trying to programmatically creating a bunch of db objects and auto-save them to the db using the code below. But for some reason, I get the error below when I try to save the object (i.e. Tender object). The line the triggers the error is tender_obj.save() in the save_tender_to_db() function. What could be causing this problem? Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\PROJECTS\leadshub\tender_matching_engine\management\commands\scrap_etenders.py", line 8, in handle main() File "C:\PROJECTS\leadshub\Tender_Loader\etenders_scraper.py", line 52, in main save_tender_to_db(entry) File "C:\PROJECTS\leadshub\Tender_Loader\etenders_scraper.py", line 129, in save_tender_to_db description=container_tag[0] File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 413, in create obj.save(force_insert=True, using=self.db) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 718, in save force_update=force_update, update_fields=update_fields) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 748, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 831, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 869, in _do_insert using=using, raw=raw) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 1136, in _insert … -
Django help. Plz tell what should be the urlpatterns
This is Django python code urlpatterns = [ path('admin/', admin.site.urls), ] what is urlpatterns here ? is it list collection? -
Why does email be sent locally and not through server?
I'm working on a Django application. I have set up all my required password reset views and corresponding pages. In the final step I want to use Send Grid in my application to send the emails. I have the following setting s in my base.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'codesniper99' # email id EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = '****' #password EMAIL_USE_TLS = True where **** is my password for the username codesniper99 on sendgrid.com But when I use the password reset function I get locally generated email to my account. Like when i put email for reset as akhilvaid21@gmail.com I get this: when I push my code to my production server and not local host then it doesn't work and no email is sent. What am I doing wrong? -
How to put closing tag like<input/> in django form "input" tag?
// I am coding my program in django with mixing react as well. When I created form in django, it doesn't by default put closing tag "/>" in input tag. so it it producing closing tag error in react console.How to solve it.here is my code //forms.py class SignUpForm(forms.Form): phone_email = forms.CharField() //views.py def sign_up(request): form = SignUpForm() return render(request, 'account/sign_up.html', {"form": form}) //sign_up.html class Sign_up extends React.Component{ render(){ return( <form method="post" action=""> {% csrf_token %} {{ form.as_p }} </form> ) } } //error //syntaxError: embedded: Expected corresponding JSX closing tag for <input> (18:143) 16 | <form method="post" action=""> 17 | <input type="hidden" name="csrfmiddlewaretoken" value="UWBCh291YmYuTNYqk9OKsihm7y1JtrFvgRNNoknJY6Be3fH6ov7uytcgcfPC6Yao"> > 18 | <p><label for="id_phone_email">Phone email:</label> <input type="text" name="phone_email" required id="id_phone_email"></p> -
Checking for a condition in signals.py using a variable passed in a method existing in views.py - django
I'm trying to evaluate a situation here. I have a custom user Model (Using AbstractUser) that contains an extra field called 'role'. I can access the value of this field in views.py using a variable. Now I want to use that variable to check for a condition in signals.py before executing post_save. Here are my code snippets so far. views.py from django.shortcuts import render, redirect from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib import messages from django.contrib.auth.decorators import user_passes_test, login_required # Create your views here. @user_passes_test(lambda u: u.is_superuser) def register(request): if request.method == 'POST': register_form = UserRegisterForm(request.POST) if register_form.is_valid(): register_form.save() username = register_form.cleaned_data.get('username') role = register_form.cleaned_data.get('role') //**This is the variable** messages.success(request, f'Welcome {username}, thank you for signing up.') return redirect('home') else: register_form = UserRegisterForm() context = { 'register_form' : register_form, 'title' : 'Register' } return render(request, 'users/register.html', context) signals.py from django.db.models.signals import post_save from django.conf import settings from django.contrib.auth import get_user_model from django.dispatch import receiver from .models import Teacher @receiver(post_save, sender=User) def create_teacher(sender, instance, created, **kwargs): if created: if hasattr(instance, 'role') and role == 'teacher': //Here is the condition Teacher.objects.create(user=instance) @receiver(post_save, sender=User) def save_teacher(sender, instance, **kwargs): instance.teacher.save() Can someone please help me on how to go about it? Thanks -
Subclassing Django model only for behavior
I have a model Property with certain fields and a relevant method: class Property(models.Model): table = models.ForeignKey(Table) field1 = models.CharField() field2 = models.IntegerField() field3 = models.BooleanField() class Meta: abstract = True def post(): pass But then I have a definite number of types of columns, conceptually speaking. There is no difference in the fields, only in how the behavior of a certain method is implemented: class Property1(Property): def post(): # execute behavior for Property1 pass class Property2(Property): def post(): # execute behavior for Property2 pass and so on. If I turned Property into an abstract base model class and have the rest inherit it, I will end up with different tables for each property. I am not sure I want that. All tables will look the same, which is redundant. But at the same time when running a query to get all properties in a table and calling post() I want the corresponding behavior to be executed: for prop in table.property_set.all(): prop.post() What are my options? -
Django model form choice
Im using Django 2.1.3 and i'm having some trouble with the "comboboxes". i have a model with all my fields and them i pass that model fields to a form but when i see my page all the fields that are choicefield don´t show. what am i doing wrong? models.py class nconfm(models.Model): NAT_CHOICES = ( ('NCI', 'NC Interna'), ('NCF', 'NC Fornecedor'), ('OS', 'Outra Situação'), ('OPM', 'Oportunidade / Melhoria'), ) data = models.DateField() natureza = models.CharField(max_length=50, choices=NAT_CHOICES) forms.py class data(forms.DateInput): format_key = 'DATE_INPUT_FORMATS' input_type = 'date' class formnconf(forms.ModelForm): class Meta: model = nconfm fields = ['data','natureza'] widgets = { 'data': data(), } index.html <form class="site-form" action="" method='POST'> {% csrf_token %} {{form}} </form> -
mod_wsgi on Apache and Windows 7
I installed Apache and mod_wsgi on Win 7 and copied config text output of mod_wsgi into httpd.conf. I also check and see server working before mod_wsgi. Now when I try to connect on local host I get a connection refused. After some research I found out I should add mod_wsgi.server to my app settings. I did it and ran runmodwsgi which failed because it was running a script in Windows which used os.getuid. Not valid in Windows. Is it mandatory to add mod_wsgi to isntalled apps in django project? Not mentioned in here. If so what can I do for os.getuid in Windows? Beside these why I get connection refused and no log if only my handler config is incorrect. -
Django 2 add custom button to admin
using Django 2.1.4, its admin site and ModelAdmin. I would like to add a custom button in the model list, near each item, as in the picture. Clicking on a button should open a custom view. To achieve that, I am adding an url in ModelAdmin. The issue is that, when clicking on the "Generate preview" button, the view is not invoked but rather I get an error message, i.e. "Questionario istituzione scolastica with ID "419/gen_pdf_preview" doesn't exist. Perhaps it was deleted?". http log from Django reports code 302, for the request: [19/Dec/2018 09:16:54] "GET /en/admin/vision/questionarioistituzionescolastica/419/gen_pdf_preview/ HTTP/1.1" 302 0 [19/Dec/2018 09:16:55] "GET /en/admin/vision/questionarioistituzionescolastica/419/gen_pdf_preview/change/ HTTP/1.1" 302 0 I have tried two approaches, but both do not work yet: 1 - a view inside the extended ModelAdmin 2 - an external view Here is the custom ModelAdmin, from admin.py: from .models import * from .views import serve_pdf_preview from django.utils.html import format_html @admin.register(QuestionarioIstituzioneScolastica) class QuestionarioIstituzioneScolasticaAdmin(admin.ModelAdmin): list_display = ('denominazione_istituzione_scolastica', 'generate_pdf_preview_html') def generate_pdf_preview_html(self, obj): return format_html('<a class="button" href="%s/gen_pdf_preview/">Generate preview</a>' % obj.id) generate_pdf_preview_html.short_description = 'Generate pdf preview' generate_pdf_preview_html.allow_tags = True def get_urls(self): from django.urls import path urls = super().get_urls() urls += [ # path('<path:object_id>/gen_pdf_preview/', self.admin_site.admin_view(self.generatepdf_view), name='vision_questionarioistituzionescolastica_generatepdf') path('<path:object_id>/gen_pdf_preview/', self.admin_site.admin_view(serve_pdf_preview), name='vision_questionarioistituzionescolastica_generatepdf') ] for u in urls: print(u) return … -
Passing method name as function argument
I'm probably missing something obvious here, what I'm trying to do is extract part of this Django view into a function since I'm using same code multiple times: def method_name(pk, method_name, model_name): instance = get_object_or_404(Document, id=pk) wb = instance.method_name() with NamedTemporaryFile() as tmp: wb.save(tmp.name) tmp.seek(0) stream = tmp.read() instance.model_name.save('POPDV.xlsx', ContentFile(stream), save=False) instance.save() I would like to pass model_name as a method name (in bold). What is the correct way to do this? My solution would be calling instance.getattribute ("model_name").save(...) -
Wagtail: Filtering a search on a ManyToMany through model
In a Wagtail-based site, I have an ArticlePage model which is related to an Author snippet model in a many-to-many relationship like this: from django.db import models from modelcluster.fields import ParentalKey from wagtail.core.models import Orderable, Page from wagtail.search import index from wagtail.snippets.models import register_snippet class ArticlePage(Page): search_fields = Page.search_fields + [ index.FilterField('author_id'), ] @register_snippet class Author(models.Model): name = models.CharField(max_length=255, blank=False) class ArticleAuthorRelationship(Orderable, models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='articles') page = ParentalKey('ArticlePage', on_delete=models.CASCADE, related_name='authors') I want to be able to search ArticlePages and filter them by a particular Author, which I can do like this: author = Author.objects.get(id=1) articles = ArticlePage.objects.live() \ .filter(authors__author=author) \ .search('football') But in the dev server logs I get this warning: articles.ArticlePage: ArticlePage.search_fields contains non-existent field ‘author_id’ My question is: Am I doing this right? It works, but the warning makes me think there might be a more correct way to achieve the same result. I have also tried using FilterField('authors'), which stops the warning, but I can't work out how to filter on that. -
supervisor web interface can't access to
i use supervisor to supervise my django project. my supervisor_conf [inet_http_server] port=0.0.0.0:9001 the start command supervisord -c supervisor_conf my site http://112.74.47.105/home can be access perfectly except http://112.74.47.105:9001, it say 'this website cannot be accessed' -
Django override only SplitDateTimeField's timefield into select field
i am trying to limit DateTimeField's TimeField into select field with following options 06:00, 11:00, 16:00. So far i tried formfield_overrides and end up with this. formfield_overrides = { models.DateTimeField: {'widget': SplitDateTimeWidget( time_attrs={"choices":settings.FEATURE_HOURS} )} } I was wondering if i override SplitDateTimeWidget's MultiWidget wrapper. Or can i extend SplitDateTimeWidget and override all the default behavior and achieve what i want? if yes, how can i ? -
Python / Celery : how can I kill subtasks when killing a parent task?
Context I've created a Django application that is calling a celery task which in turns spawn other tasks and wait for them to be finished. Here's the workflow : 1) The main python/django code start a celery task in the background 2) The celery task process some code and then start a celery group of differents tasks and wait for them to be ready 3) every task of the group then spawn another group of subtasks in the same way and wait for them to finish It works well (although I'm a begginer and probably implemented it poorly) but now I would like to be able to terminate every child processes if I kill the main celery tasks started in the beggining. What I have so far I've recreated the situation using a simple parent tasks spawning multiple child tasks and i've modified the "on_failure" method of the celery Task class to kill it's child when it fails. Tasks.py from celery import Celery, group,Task, result from celery.signals import task_revoked import time from pprint import pprint application = Celery('tasks',backend='amqp://',broker='amqp://guest@localhost//') class MyTask(Task): def on_failure(self, exc, task_id, args, kwargs, einfo): print(self.AsyncResult(task_id).children[0].revoke(terminate=True,signal='SIGTERM')) print('{0!r} failed: {1!r}'.format(task_id, exc)) @application.task(base=MyTask) def childTask(): while True: time.sleep(10) print("Message de … -
Allow is_staff=False to access specific page Django
I have a change password function which only allowed is_staff=False to access, not allowed is_staff=True to view this page. Is there any way to do this? I only found staff_member_requird, but this is for staff. def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) messages.info(request, 'Your password has been changed successfully!') else: form = PasswordChangeForm(request.user) return render(request, 'registration/change_password.html', {'form': form,})