Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How do i get the customer id automatically while customer post the booking form?
i am newbie in django how do i get the id of customer model while submitting the form .for eg john is submitting the form of booking i want automatically get who submit the booking .means while customer register the form and the link will sended to the customer for booking. and in booking i want to initialize the customer automatically for the booking. means john booked the car and given detail for when he want the car for booking . Model class Booking(models.Model): class Meta(): db_table = "booking" verbose_name = "Booking" verbose_name_plural = "Bookings" ordering = ['-booking_date'] booking_car_car = models.ForeignKey( Car, on_delete=models.CASCADE, related_name='booking_car_car_key' ) booking_customer_customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name='booking_customer_customer' ) booking_start_date = models.DateField( blank=False, null=False ) booking_end_date = models.DateField( blank=False, null=False ) booking_total_price = models.IntegerField( blank=False, null=False ) booking_approved = models.NullBooleanField( blank=True, null=True ) booking_date = models.DateTimeField( auto_now_add=True, blank=False, null=False ) def __str__(self): return self.booking_customer_customer.customer_firstname class Customer(models.Model): first_name = models.CharField(max_length=64,null= False) last_name = models.CharField(max_length=64) customer_age = models.IntegerField(blank=True, null=True) last_name = models.CharField(blank=True, max_length=100) license_year = models.IntegerField(blank=False, null=False) tlc_number = models.IntegerField(blank=False ,null=False) contact_num =models.IntegerField(blank=False, null=False) contact_email = models.EmailField(blank =False) def __str__(self): return self.first_name Views def rentacar_booking(request): if request.POST: template = Template.objects.get(template_default__exact=1) template_page = template.template_alias + str("/rentacar/rentacar_booking_form.html") menu_config_list = MenuItemRentacarList.objects.all()[0] menu_config … -
Need to query a resultset from database in Django using a form
I have a form which is editing a database entry and saving the changes back to the database. after the changes are saved, I want to redirect to a contract.html, where I want to populate the details of that entry. below is the view: *def edit_res(request, pk=None): if request.method == 'POST': resident_form = EditItemForm(request.POST) if resident_form.is_valid(): key = int(request.POST['id']) resident = Resident.objects.get(pk=key) resident_form = EditItemForm(request.POST, instance=resident) resident_form.save() #form = EditItemForm(request.POST, instance=key) #resident = get_object_or_404(Resident, pk=key) #form = EditItemForm(request.POST, instance=key) #if form.is_valid(): #form.save() #return HttpResponse('Saved form') return redirect('Contract') else: item = Resident.objects.get(pk=pk) form = EditItemForm(instance=item) args = {} args.update(csrf(request)) args['form'] = form args['id'] = pk return render_to_response('reg_form/edit.html', args)* currently after the edited entry is saved, I redirected it to the Contract.html page. I am trying to write a function, which can be called above to return the data from the database: def res(request,in_res_id): data=Resident.objects.get(res_id=in_res_id) return TemplateResponse(request,'Contract.html',{'data':data}) My contract.html is like, where I want to populate the column value for res_fname : *This skilled nursing facility Admission Agreement is entered into between Located at and _{{data.res_fname}} (hereinafter “Resident”) * Please advise. Thank you ! -
How to configure docker to use redis with celery
docker-compose.yml version: '3.1' services: redis: image: redis:latest container_name: rd01 ports: - '6379:6379' webapp: image: webapp container_name: wa01 ports: - "8000:8000" links: - redis depends_on: - redis celery: build: . container_name: cl01 command: celery -A server worker -l info depends_on: - redis I also don't feel I understand links and depends_on, I tried different combinations. Celery cannot connect to redis. I get the following error - [2018-08-01 13:59:42,249: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. I believe I have set broker URLs correctly in settings.py in my django application (webapp image) CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_RESULT_BACKEND = 'redis://redis:6379/0' What is the right way to dockerize a django project with celery and redis? TIA. -
How to add custom class to django-filters field
I tried to make a way that worked with forms, but here the class did not apply class TrainerFilter(django_filters.FilterSet): price_lt = django_filters.NumberFilter(field_name="prise", lookup_expr='lt') class Meta: model = Profile fields = ['direction', 'group', 'child', 'price_lt'] widgets = { 'direction': SelectMultiple(attrs={'class': 'custom-select'}), } -
django how to display the details page for a newly added product
I am still a learner for python django. I am trying to create a site where user can Add the a new product and should be able to see the details of the latest added product in another page. I am able to achieve the first part i.e the Add Product page. But i need help as to how to get the detail page correct. Request the guidance. My model.py is as follows: from django.db import models from django.db.models import CASCADE from django.urls import reverse from category.models import Subcategory, Category from category.utils import unique_slugify class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=CASCADE) subcategory = models.ForeignKey(Subcategory, related_name='products', on_delete=CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, blank=True) image = models.ImageField(upload_to='images/', blank=True) description = models.TextField(blank=True) price = models.IntegerField(default=0) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) index_together = (('id', 'slug'),) def __str__(self): return self.name def save(self, **kwargs): slug_str = "%s %s %s" % (self.name, self.category, self.subcategory) unique_slugify(self, slug_str) super(Product, self).save(**kwargs) My views.py looks as follows: from django.shortcuts import render, get_list_or_404 from django.urls import reverse_lazy from django.views.generic import CreateView, UpdateView, ListView from category.models import Subcategory from product.forms import ProductForm from product.models import Product class ProductListView(ListView): model = Product … -
Categorized Status Choices in Django
Let's say I have a model of sandwiches, and I want to say what protein you want to put on the sandwich: class Sandwich(models.Model): protein_choices = ( ('n', 'Please Choose'), ('e1', 'Eggplant'), ('e2', 'Hummus'), ('v1', 'Provolone'), ('v2', 'Egg'), ('p1', 'Fish'), ('c1', 'Beef'), ('c2', 'Chicken'), ('c3', 'Pork'), ) protein = models.CharField( max_length=2, choices=protein_choices, default='n', ) How could I make the choices categorized by vEgan, Vegetarian, Pescatarian, or Carnivore? I want to be able to check its category (is the sandwich Vegan[assuming categorizations don't overlap]?), and I have been using a model.Manager, but I want to ensure that all choices have a category (I think this is the missing link, and don't think testing is the right way) and only one choice is selected (which is already handled by the status structure presented). Should this be handled in a model.Form, a 1->M relationship with some other structure, or through model.Managers and something else? -
Does Django re-run all migrations for it's test db?
I am trying to run python manage.py test and it starts off with the usual Creating test database for alias 'default'... but then a pymysql.err.InternalError occurs with the message "Invalid default value for 'expiration_time'". expiration_time is a timestamp variable with the default value as null. One reason that I can think of why this error is occuring is probably because all migrations are being re-run and that this might not be an acceptable default value but I could not find any information on how the test db is actually created by django. -
How to make login method when I don't use basic User model in Django?
If you want look a problem quikly, down the scroll to 'views.py' forms.py `from django import forms from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['studentNumber', 'name', 'major', 'email', 'password', 'phoneNumber', 'github', 'sns', ] class LoginForm(forms.ModelForm): class Meta: model = Profile fields = ['email', 'password']` models.py `from django.db import models class Profile(models.Model): studentNumber = models.CharField(max_length=30, blank=False) name = models.CharField(max_length=10, blank=False) major = models.CharField(max_length=20, blank=False) email = models.EmailField(max_length=30, blank=False) password = models.CharField(max_length=15, blank=False) phoneNumber = models.CharField(max_length=15, blank=False) github = models.CharField(max_length=150, blank=False) sns = models.CharField(max_length=150, blank=False)` views.py `from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import login, authenticate from .forms import ProfileForm, LoginForm from .models import Profile def signup(request): if request.method == "POST": form = ProfileForm(request.POST) if form.is_valid(): form.save() #object save return HttpResponse('signup success.') else: form = ProfileForm() return render(request, 'registration/profile.html', {'form': form}) def signin(request): if request.method == "POST": form = LoginForm(request.POST) email_input = str(request.POST['email']) password_input = str(request.POST['password']) user_Qset = Profile.objects.filter(email = email_input) if user_Qset is not None: password_saved = str(user_Qset.values('password')[0]['password']) if password_input == password_saved: ***login(request, user_Qset) # Here is a problem!*** return HttpResponse('login success.') else: return HttpResponse('locin failed, wrong password') else: return HttpResponse('login failed, wrong email address') else: form = LoginForm() return render(request, … -
Good way to display ManyToManyFields in HTML table individually
I want to give a view which has a form/formset that allows the update of any row in the model I have. I think Formsets will do this for me, but I can't quite figure out how to display this. Basically, column A in my table has the user, and column B is a ManyToManyField to select other users to attach for the relationship to the column A user. Currently, I can only get my form to display as a dropdown for both the column A user and column B options. I want column A to be displayed as text (each user in a row individually in my HTML table) with the second column in the HTML table to contain the list of options. Here is my code: forms.py class UserSurveyQueueForm(forms.ModelForm): class Meta: model = UserSurveyQueue fields = ('__all__') models.py class UserSurveyQueue(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) queue = models.ManyToManyField( User, related_name='survey_queue' ) class Meta: verbose_name = ('Survey Queue') verbose_name_plural = ('Survey Queues') def current_queue(self): return ", ".join([str(q.username) for q in self.queue.all()]) def __str__(self): return self.user.username views.py def queue_manager(request): """ View for managers to see modify queues for their direct reports """ UserSurveyQueueFormSet = formset_factory(UserSurveyQueueForm) if request.method == "POST": … -
django requests url param header is NoneType when encoded as string
trying to get an API request's headers properly formatted and encoded. example: import requests from os import environ HEADERS = { 'Api-Key': environ.get('API_KEY'), 'Authorization': str('Token%20' + environ.get('AUTH_TOKEN')) } def make_request(message): payload = {'foo': bar} r = requests.post('https://api.x.com/endpoint/', headers=HEADERS, data=payload) if r.status_code == requests.codes.ok: return create_message(RESPONSES['welcome']) return create_message(RESPONSES['something_went_wrong'].format(r.status_code, r.reason)) will err out: 'Authorization': str('Token%20' + environ.get('AUTH_TOKEN')) TypeError: must be str, not NoneType even though I'm encoding that header param as a string (per docs: http://docs.python-requests.org/en/master/user/quickstart/#custom-headers). what's the right way to encode that header? thanks -
How to implement two abstract models with ForeignKey relation of one to other in Django?
I.e. we have SomeSeries with several SomeDecors, where ForeignKey of SomeDecor points to SomeSeries. I want both to be abstract and later instantiate several pairs of it (with it's own tables in db). Is it possible? -
AttributeError: type object 'NoDbTestRunner' has no attribute 'split'
I'm trying to create a DiscoverRunner for Django 2.0 and python3 to skip DB creation, but get this error: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/mlmireles/.virtualenvs/risk-analysis/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/mlmireles/.virtualenvs/risk-analysis/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mlmireles/.virtualenvs/risk-analysis/lib/python3.6/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv super().run_from_argv(argv) File "/home/mlmireles/.virtualenvs/risk-analysis/lib/python3.6/site-packages/django/core/management/base.py", line 280, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "/home/mlmireles/.virtualenvs/risk-analysis/lib/python3.6/site-packages/django/core/management/base.py", line 254, in create_parser self.add_arguments(parser) File "/home/mlmireles/.virtualenvs/risk-analysis/lib/python3.6/site-packages/django/core/management/commands/test.py", line 47, in add_arguments test_runner_class = get_runner(settings, self.test_runner) File "/home/mlmireles/.virtualenvs/risk-analysis/lib/python3.6/site-packages/django/test/utils.py", line 306, in get_runner test_path = test_runner_class.split('.') AttributeError: type object 'NoDbTestRunner' has no attribute 'split' Here's the code for the runner: from django.test.runner import DiscoverRunner class NoDBTestRunner(DiscoverRunner): def setup_databases(self, **kwargs): pass def teardown_databases(self, *args, **kwargs): pass -
How to unregister or add a custom ModelAdmin to django-allauth from the admin
I wish to unregister SocialAccount, SocialApp, SocialToken from my admin or add a custom ModelAdmin so that my staff users will not be able to see my secret keys. Hence i attempted to unregister the models through the code shown in one of my admin.py. admin.py from one of my own app from allauth.socialaccount.models import SocialAccount, SocialApp, SocialToken admin.site.unregister(SocialApp, SocialAppAdmin) admin.site.unregister(SocialToken, SocialTokenAdmin) admin.site.unregister(SocialAccount, SocialAccountAdmin) However i got the error message saying that the models are not registered. But when i did something like: admin.site.unregister(SocialApp, SocialAppAdmin) i got an error message saying raise AlreadyRegistered('The model %s is already registered' % model.__name__) django.contrib.admin.sites.AlreadyRegistered: The model SocialAccount is already registered Error Message raise NotRegistered('The model %s is not registered' % model.__name__) django.contrib.admin.sites.NotRegistered: The model SocialAccount is not registered How do i go about unregistering 3rd party packages like these? -
Why does a Django Postgres Migration Altering field to DurationField causes an error?
When running migrations with the postgres DATABASE_ENGINE I am getting the following error: django.db.utils.ProgrammingError: cannot cast type numeric to interval LINE 1: ...R COLUMN "duration" TYPE interval USING "duration"::interval when the migration alters a field from a DecimalField operations = [ migrations.AlterField( model_name='entry', name='duration', field=models.DurationField(blank=True, null=True), ), ] Is there a way to fix this? -
csv download doesn't occur without error in Django
I am implementing csv donwloand function referring to this page. Even though I don't get any error message, cannot get csv file downloaded. Does anyone know what is the problem for this implementation? Below is the code to download csv file from database. class timeCSVexport(View): def get(self,request,pk,keyword): key=keyword.replace("_"," ") queryset=timeseries.objects.filter(html__pk=pk).filter(keyword=key) bio = BytesIO() data=json.loads(list(queryset)[0].df) df=pd.DataFrame.from_dict(data,orient='index').T df.index=pd.to_datetime(df.index) df1=df.sort_index() sheet=key[:31] if len(key)>31 else key print (sheet) writer=pd.ExcelWriter(bio,engine='xlsxwriter') df1.to_excel(writer,sheet_name=sheet) writer.save() bio.seek(0) workbook=bio.getvalue() response = StreamingHttpResponse(workbook,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % pk return response -
Django - How to automatically reset values of the database column to 0 everyday?
I am trying to reset the values of 'today_count' of this table back to 0 everyday at 12:00AM automatically. Is there any way to do this? class HashTag(models.Model): tag = models.CharField(max_length=50, unique=True) count = models.DecimalField(max_digits=10, decimal_places=0) today_count = models.DecimalField(max_digits=10, decimal_places=0) Thanks. -
Django template : Need 2 values to unpack in for loop; got many
So to update my previous question : Django template : Need 2 values to unpack in for loop; got 8 from django.shortcuts import render, redirect from accounts.forms import Searchform import requests page='' ville ='' region='' prixmin ='' prixmax= '' surfacemin='' surfacemax='' def post(request): global page ,ville ,prixmin ,prixmax, surfacemin, surfacemax, region, annonces if request.method == 'POST': form = Searchform(request.POST) if form.is_valid(): ville = form.cleaned_data['ville'] prixmin = form.cleaned_data['prix_min'] prixmax = form.cleaned_data['prix_max'] surfacemax = form.cleaned_data['surface_max'] surfacemin = form.cleaned_data['surface_min'] else: page='1' form = Searchform() annonces = [] try: url = 'example' img = 'example' ville = 'example' typeImmo = 'example' Nb_piece = 'example' Nb_ch = 'example' surface = 'example' prix = 'example' annonces.append((url,img,ville,typeImmo,Nb_piece,Nb_ch,surface,prix)) except:pass args = {'form': form, 'annonces':annonces, 'rech':len(annonces)} return render(request, 'accounts/page_recherche.html', args) and then I will unpack the data in annonces to use it in my page. Sorry for the style of my code I'm new at programming and at python. Any pro tips for writing better code are much appreciated ;) Thks ! -
In Django, how to trigger signal in many to many relation models with intermediate model?
I would like to trigger signal when item is added in the many to many relation model that has intermediate model. These are models below. class Page(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) url = models.TextField('Website Page URL', null=False, blank=False, unique=True) site = models.ForeignKey(Site, related_name='pages', on_delete=models.CASCADE) class Link(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) url = models.CharField('Page Link', max_length=600, null=False, blank=False, unique=True) pages = models.ManyToManyField(Page, related_name='links', through='PageLinkAssociation') class PageLinkAssociation(models.Model): page = models.ForeignKey(Page, on_delete=models.CASCADE) link = models.ForeignKey(Link, on_delete=models.CASCADE) As you can see on these model classes, the url fields of the Page and Link classes are unique. The bellow code snippet represents the way how I add items to those three tables. links = kwargs.get('links', None) for link in links: try: link_obj = PageLink.objects.create(url=link) PageLinkAssociation.objects.create(page=page, link=link_obj) except IntegrityError: link_obj = PageLink.objects.get(url=link) PageLinkAssociation.objects.create(page=page, link=link_obj) In this way, the items are properly added to the tables as I expected. What I am concerned is that I would like to trigger signal after every link_obj is added to the Link table. I have seen that post_save is not working. Django documentation told me that I should use m2m_changed for m2m relation, but I am not sure that is the correct way. -
How to generate forms for django-eav
I have added the package django-eav to create custom fields on my models. It works fine through the admin. However, I am having trouble generating the forms through a template. I get the following error. Exception Value: ModelForm has no model class specified. views.py def add_account(request): form = AccountForm() return render(request, 'account/add_account.html', {'form': form}) forms.py from eav.forms import BaseDynamicEntityForm class AccountForm(BaseDynamicEntityForm): model = Account documentation on forms and django-eav is pretty limited.http://mvpdev.github.io/django-eav/docstrings.html#forms Hope anyone can guide me in the right direction. cheers! -
Django How to add a model other than a form
I am making an app using Django2.0. But There are things that I do not know even if I investigate. There are models as follows. class Picture(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE) title = models.CharField(max_length=255) image = models.ImageField(upload_to='image/') using the following form class PictureForm(forms.ModelForm): class Meta: model = Picture fields = ['place', 'title', 'image'] And run following code on views.py obj = Picture() pic = PictureForm(request.POST, request.FILES, instance=obj) pic.save() I can add model peacefully. But in this way, I should select place and title on form every time. Beforehand I decide place and title, I will only select image on the form. It reduces my work. Since there are several place and title, I do not want to set them to default values. I succeeded in making a form. class PictureForm(forms.ModelForm): class Meta: model = Picture fields = ['image',] But I don't know how to add title and place on views.py I'm not good at English. Thank you for seeing the bad sentensecs to the end -
Stripping blocks in docx template
Im trying to generate some entries of a dict in the template this way: Title {% for a in primary_biblio_data %} {{ a[1] }}. {{ a[0] }} {% endfor %} Problem is that is being generated this way: Title 1. A 2. B 3. C What I want is an output like: Title 1. A 2. B 3. C According to Jinja2 doc, I've tried all the stripping options like: {% for a in primary_biblio_data %} {{ a[1] }}. {{ a[0] }} {%- endfor %} or {% for a in primary_biblio_data -%} {{ a[1] }}. {{ a[0] }} {% endfor %} But it only works if I define the block this way: {% for a in primary_biblio_data %} {{ a[1] }}. {{ a[0] }} {% endfor %} this makes the template less readable. Stripping doest not work that way or am I doing something wrong? Thank you in advance! -
Can I have an organized way to work with django?
I come from an Mean, Express, Angular and Node (MEAN) stack background. I really liked how angular has separate components and then we can style each components and then nest them in each other. It is just more organized and way more shareable when in companies. It gets easier to actually understand the structure. Can I do this in django since I notice that my css is supposed to be all in one static file. Is it possible? NOTE: Angular not Angular.js -
django filter one object from model instance on serialization
I have django model with m2m field, and I want to customise serializer so I can filter only needed data. Code is shown bellow. models.py: class Example(models.Model): type = models.CharField(max_length=25) users = models.ManyToManyField(User) serializers.py: class UserSerializer(serializers.ModelSerializer): def to_representation(self, instance): return {... processing User's fields...} class ExampleSerializer(serializers.ModelSerialzier): def to_representation(self, instance): user = self.context result = {... some fields ...} if type == "some_value": ### IN THIS CASE THERE ARE ONLY TWO USERS, NEVER MORE### users = UserSerializer(instance.users, many=True).data users.remove({'id': user.id}) result['users] = users[0] else: result['users'] = ... views.py: ExampleSerializer(Example.objects.all(), many=True, context=user).data Not sure you need anything else, but feel free to ask. So the problem is that in case if type is "some_value" I want to get only one user which is not the one who initiated this call, it works fine but looks ugly and I'm not sure that on highload would perform fast enough. Of course I could write another custom serializer especially for this case, but still looking for the best solution. Is there any built-in option in python? And I'm noticed that serializers aren't really fast for such an operations, is there any way I could save up time? Something like indexes and etc? Thanks in advance … -
DRF+Ajax Method "POST" not allowed. viewsets + router
I am getting error 'Method "POST" not allowed' while running the api. I have use ModelViewSet and Routers Also use Ajax on front-end to send "POST"-request. I did GET and PUT? and it's work perfectly, but POST - never. in app.views.py class PostsViewSet(viewsets.ModelViewSet): queryset = Posts.objects.filter(is_published=True).select_related() serializer_class = PostDetailSerializer # permission_classes = (IsAuthor, MyPermission) def perform_create(self, serializer): serializer.save(author=self.request.user) in app.serializers.py class PostDetailSerializer(serializers.HyperlinkedModelSerializer): # author = serializers.ReadOnlyField(source='author.username') author = UserInfoSerializer(read_only=True) class Meta: model = Posts fields = ('url', 'id', 'title', 'text', 'created', 'author', 'last_modified', 'is_published') in permissions.py class IsAuthor(permissions.BasePermission): def has_object_permission(self, request, view, obj): print(request.method) if (request.method in permissions.SAFE_METHODS or request.user and request.user.is_authenticated()): return True return obj.author == request.user class MyPermission(permissions.BasePermission): allowed_methods = ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS'] def has_permission(self, request, view): return request.method in self.allowed_methods in urls.py class PostsRouter(routers.SimpleRouter): routes = [ routers.Route( url=r'^{prefix}{trailing_slash}$', mapping={'get': 'list'}, name='{basename}-list', initkwargs={'suffix': 'List'}, detail=False ), routers.Route( url=r'^{prefix}/{lookup}{trailing_slash}$', mapping={'get': 'retrieve'}, name='{basename}-detail', initkwargs={'suffix': 'Detail'}, detail=True ), routers.Route( url=r'^{prefix}/create/$', mapping={'put': 'create'}, name='{basename}-create', initkwargs={'suffix': 'Detail'}, detail=True ), routers.Route( url=r'^{prefix}/{lookup}/update/$', mapping={'put': 'update'}, name='{basename}-update', initkwargs={'suffix': 'Detail'}, detail=True ), ] router = PostsRouter() router.register(r'users', views.UserViewSet) router.register(r'', views.PostsViewSet) urlpatterns = [ url(r'', include(router.urls)), ] Please help!!! -
Job is not performed by APScheduler's BackgroundScheduler
I have a Django application that I'm running on Docker. I'm trying to launch an APScheduler scheduler when I run the docker container. I created a scheduler and I simply added it a job that I called test1, and that sends an email to my address. This is the Python script that is launched when I run the container. from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.schedulers.background import BackgroundScheduler #scheduler = BlockingScheduler() scheduler = BackgroundScheduler() def test1(): ... (code to send email) scheduler.add_job(test1, 'interval', seconds = 20) scheduler.start() This is the results I obtained with each of the two kind of schedulers: BlockingScheduler: the scheduler works, I receive an email every 20 seconds. However I can't access the app. I presume this is normal due to the very nature of the BlockingScheduler. BackgroundScheduler: no problem to access the application. However, I receive no email. Since the emails were sent in one of the two cases I guess the problem is neither Django nor Docker related, but purely about APScheduler. I did my research but I couldn't find why the BackgroundScheduler didn't work as in the tutorials I read, the developper set up the scheduler the same way I did. Any help would …