Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overwriting save method not working in Django Rest Framework
I have a model (Points) which saves the points based on the purchase made by a user. I have made in such a way that when order is made (orderapi is called), a signal is passed with order instance and points are calculated based on the amount and it is saved using the save method. Alothugh Order object is created, I dont see the points being saved in the database. I am not sure what is the issue. My models: class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) @property def total_price(self): # abc = sum([_.price for _ in self.order_items.all()]) # print(abc) return sum([_.price for _ in self.order_items.all()]) def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) @property def price(self): total_item_price = self.quantity * self.order_variants.price # print(total_item_price) return total_item_price class Points(models.Model): order = models.OneToOneField(Order,on_delete=models.CASCADE,blank=True,null=True) points_gained = models.IntegerField(default=0) def collect_points(sender,instance,created,**kwargs): total_price = instance.total_price if created: if total_price <= 10000: abc = 0.01 * total_price else: … -
form are not display
models.py from django.db import models Create your models here. class dhiraj(models.Model): title=models.CharField(max_length=200, default="" ) completed=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now=True) def __str__(self): return self.title form.py from django import forms from django.forms import ModelForm from . models import dhiraj class dhirajForm(forms.ModelForm): class meta: model=dhiraj fiels='__all__' index.html <h1>this is</h1> <form> {{form}} </form> {% for taskk in dhiraj %} <div> <p>{{taskk}}</p> </div> {% endfor %} error says ValueError at / ModelForm has no model class specified. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.2 Exception Type: ValueError Exception Value: ModelForm has no model class specified. Exception Location: C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\forms\models.py, line 295, in init Python Executable: C:\Users\Dhiraj Subedi\dhiraj\virenv\Scripts\python.exe Python Version: 3.9.4 Python Path: ['C:\Users\Dhiraj Subedi\dhiraj\first', 'C:\Users\Dhiraj ' 'Subedi\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39', 'C:\Users\Dhiraj Subedi\dhiraj\virenv', 'C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages'] Server time: Sat, 08 May 2021 06:29:28 +0000 -
Django Question 'ModelChoiceField' object has no attribute 'use_required_attribute'
Dears, I met a problem in Django. There is an error about 'ModelChoiceField' object has no attribute 'use_required_attribute' and I don't know where I made mistake. My goal is to make my submit customizing form but I couldn't understand how CBV in Django can reach this goal, so I went back to use forms.py and FBV in Django. But my fields in form model have foreign keys to refer other models. I used forms.ModelChoiceField and expected to solve foreign key problem but it doesn't work and show this error. Thank you for reading and hope someone can help me to solve it. Here are my code: forms.py from django import forms from .models import Case from school_app.models import School from student_app.models import Student class CaseModelForm(forms.ModelForm): class Meta: model = Case fields='__all__' widgets = { 'name' : forms.ModelChoiceField(queryset=Student.objects.all()), 'phone' : forms.TextInput(), 'school' :forms.ModelChoiceField(queryset=School.objects.all()) } models.py from django.db import models from django.urls import reverse import datetime,time from school_app.models import School from student_app.models import Student # Create your models here. class Case(models.Model): name=models.ForeignKey(Student,related_name='case_student_name',on_delete=models.CASCADE,verbose_name="姓名") phone=models.CharField(verbose_name="電話",blank=False,max_length=256) school=school=models.ForeignKey(School,related_name='case_school',on_delete=models.CASCADE,verbose_name="學校") views.py def CaseFormView(request): print("CaseForm") form_cus = CaseModelForm() if request.method == "POST": form = CaseModelForm(request.POST) if form.is_valid(): form.save() return redirect("/") context={ 'form_cus': form_cus } return render(request, 'case_app/case_form.html',context) urls.py from … -
Database storing weeks and days of week (Efficient method)
I couldn't decide which is the most effective way of storing the week and the days of the week. if x person is available on day d First Option; class Week(models.Model): user availability = models.BooleanField() # if **x** is available at least one day in week **w** start = models.DateField() end = models.DateField() days = models.ManyToManyField('self', through='DaysOfWeek', symmetrical=False) class DaysOfWeek(models.Model): week = models.ForeignKey(Week, on_delete=models.CASCADE) date = models.DateField() availability = models.BooleanField(default=True) Second Option; class Week(models.Model): user availability = models.BooleanField() # if **x** is available at least one day in week **w** start = models.DateField() end = models.DateField() day1 = models.BooleanField(default=True) day2 = models.BooleanField(default=True) day3 = models.BooleanField(default=True) day4 = models.BooleanField(default=True) day5 = models.BooleanField(default=True) day6 = models.BooleanField(default=True) day7 = models.BooleanField(default=True) -
Python - Django persisting storage through gunicorn processes
I am having very specific use case of persisting storage inside Django production app, I cannot pickle instance of a class and save it to db, simple setup is needed of where instances of class can be saved to an array and accessed and removed. I want to look into pymemcache or would it be possible to persist memory inside file outside Django app? I know this is more technical than programming, but any help is great. Thank you. -
RelatedObjectDoesNotExist at /login/ User has no profile
Profile creation for every new user was working properly. But when I resize the image quality of the user profile from my 'models.py' file, then whenever I create a new user it doesn't create profile for that new user. How do I solve this problem? My codes are given below: Views.py: from django.shortcuts import render, redirect from .forms import UserSignupForm, UserUpdateForm, ProfileUpdateForm from django.contrib import messages from django.contrib.auth.decorators import login_required def signup(request): if request.method == 'POST': form = UserSignupForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save() messages.success(request, f'Signup for {username} is successful') return redirect('login') else: form = UserSignupForm() return render(request, 'users/signup.html', {'title': 'signup', 'form': form}) @login_required def profile(request): context = { 'title' : 'Profile' } return render(request, 'users/profile.html', context) @login_required def update_profile(request): if request.method == 'POST': user_update = UserUpdateForm(request.POST, instance=request.user) profile_update = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if user_update.is_valid() and profile_update.is_valid(): user_update.save() profile_update.save() messages.success(request, 'Profile has been updated!') return redirect('profile') else: user_update = UserUpdateForm(instance=request.user) profile_update = ProfileUpdateForm(instance=request.user.profile) context = { 'title' : 'Update Information', 'u_form' : user_update, 'p_form' : profile_update } return render(request, 'users/profile_update.html', context) signals.py: from django.db.models.signals import post_save from django.contrib.auth.models import User from .models import Profile from django.dispatch import receiver @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, … -
Django best practice to display data to template
I have a Django template that I would like to display a users transactions and I would like to know the best practice for displaying data from my database to the template. Should I implement a form that sends a users 'Order by' value and make an SQL query and then return those results back to the user or should I just handle all the processing via JavaScript? What is the best practice? Note: I don't want the page refreshing so I think I'll be implementing AJAX Banking user transactions example: Date: 5/6/21, type: deposit, description: Venmo inc, amount: 200.00 Date: 5/7/21, type: card, description: Starbucks, amount: 6.75 Date: 5/7/21, type: withdrawal, description: Deja Vu club, amount: 250.00 Below is HTML Template: {% extends "home/base.html"%} {% load static %} {% block title %} <title>Account Transactions</title> {% endblock %} {% block body %} <div id="account-transactions-header">Account Activity</div> <div id="account-transactions-main"> <div id="account-transactions-container"> #User should be able to filter by date, type etc. <div id="account-transactions-order-by">Order by: </div> <div id="account-transactions"> #User transactions would appear here loading about 10 results and upon end of scroll request another 10 from database </div> </div> </div> {% endblock %} -
Creating Virtual Environment
I have completed a project in Django on my Windows PC without creating a virtual env. Now, I feel I should have a virtual env. How do I create it and put my project in the virtual env? Please, do explain to me in steps... Thank you in advance. -
python 2.7: ERROR:root:code for hash md5 was not found
I have installed python via homebrew on my macbook (macOS Big Sur 11.2.3). Yes, I know, it's outdated, but I need it for some old projects. I use virtualenv to seperate stuff. When I try to run ./manage.py runserver I got this error: ERROR:root:code for hash md5 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback (most recent call last): . . . File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 8, in <module> from django.contrib.auth.hashers import ( File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/contrib/auth/hashers.py", line 241, in <module> class PBKDF2PasswordHasher(BasePasswordHasher): File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/contrib/auth/hashers.py", line 251, in PBKDF2PasswordHasher digest = hashlib.sha256 AttributeError: 'module' object has no attribute 'sha256' Maybe it is a problem with hashlib or openssl? Thanks. -
data are not send from view to templeate
fapp/views.py from django.shortcuts import render from django.http import HttpResponse from . models import dhiraj def index(request): t=dhiraj.objects.all() context={'dhiraj':t} return render(request,'fapp/index.html',context) def __str__(self): return self.title indext.html <h1>this is</h1> {% for taskk in dhiraj %} <div> <p>{{taskk}}</p> </div> {% endfor %} models.py from django.db import models class dhiraj(models.Model): title=models.CharField(max_length=200, default="" ) completed=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now=True) output is this is other outputs are not shown -
In Django I cant retrieve the values for choice fields , file fields with this value ={{i.cv} in file field and similarly the choice fields
This is my edit.html code and during retrieving the values from database it shows only the text fields like value={{ i.full_name}} but when I am writing value={{ i.cv}}, value={{ i.status}}, value={{ i.gender}} it does not shows the value which needs to bed edited I have two choice fields and one file field. this is my edit.html <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email"> </div> </div> <div class="row form-group"> <div class="col-md-12 … -
Error on migration creating a new user - model 'auth.User', which has been swapped out
I am trying to add my custom user models however, whenever I try to migration my changes I get an error: account.EmailAddress.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. socialaccount.SocialAccount.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. In my settings I have already added: AUTH_USER_MODEL = 'user.User' My custom user model is: class User(AbstractUser): def __str__(self): return self.username How can I fix this issue? -
marked js incorrect response with mathjax in Django
I am trying to integrate MathJax, marked.js into Django. However, the result seems to be not rendered. I meant, for example, if you put a <h1> tag in website you should see a header, but I saw a <h1> tag in string right there. Here is my base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Speedo</title> <link rel="stylesheet" type="text/css" href="{% static 'docs/lib/css/roboto.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'docs/lib/css/fontawesome-4.2.0.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'docs/lib/css/fontawesome-5.14.0.all.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'docs/lib/js/highlight.js-10.4.1/src/styles/stackoverflow-light.css' %}"> <script type="text/javascript" src="{% static 'docs/lib/js/highlight.js-10.4.1/src/highlight.min.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'docs/base.css' %}"> {% block css %}{% endblock %} <script type="text/javascript" src="{% static 'docs/lib/js/polyfill-0.1.41/polyfill.min.js' %}"></script> <script type="text/javascript" src="{% static 'docs/lib/js/marked-1.2.5/marked.min.js' %}"></script> <script> MathJax = { tex: { inlineMath: [ ['$', '$'], ['\\(', '\\)'] ], displayMath: [ ['$$', '$$'], ['\\[', '\\]'] ] } }; </script> <script type="text/javascript" async src="{% static 'docs/lib/js/MathJax-3.1.2/es5/tex-chtml.js' %}"></script> </head> <body> <header> <div id="icon-wrapper"> <svg id="django" xmlns="http://www.w3.org/2000/svg" width="2500" height="873" viewBox="0 0 436.506 152.503"><g fill="#092e20"><path d="M51.465 0h23.871v110.496c-12.245 2.325-21.236 3.256-31.002 3.256C15.191 113.75 0 100.576 0 75.308c0-24.337 16.122-40.147 41.078-40.147 3.875 0 6.82.309 10.387 1.239V0zm0 55.62c-2.79-.929-5.115-1.239-8.061-1.239-12.091 0-19.067 7.441-19.067 20.461 0 12.712 6.666 19.687 18.912 19.687 2.635 0 4.806-.154 8.216-.619V55.62z"/><path d="M113.312 … -
How to install python on the hosgator cpanel
Hi guys someone knows how I can install python in hosgator, i have the Turbo plan but I do not see the option in cpanel to install it, because my project is on Django. Thanks -
AttributeError at / 'int' object has no attribute 'get', trying to get object id via for loop
I'm working on a project that'll display uptime based on an IP. The code is supposed to pull the IP from a model attribute, ping the IP address, and return either a 0 or a 1, which'll be passed to the HTML and checked for there. I've ran the steps through in the python shell and got the data needed, but when running my test server, I get this error: AttributeError at / 'int' object has no attribute 'get' Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.2.2 Exception Type: AttributeError Exception Value: 'int' object has no attribute 'get' Here's my code, if someone can help it's greatly appreciated!!!! views.py: from django.shortcuts import render from django.http import HttpResponse from .models import NewServer import os # Create your views here. def index(request): servers = NewServer.objects.order_by('id') #this should ping the server!!!! #loop through all NewServer objects, storing each #count in ids for ids in servers: #for every loop, set get_server to the #current NewServer objects via the id get_server = NewServer.objects.get(id=ids.id) #create the ping command with the ip #gotten through the 'ip' attribute #in the model ping = "ping -c 1 " + get_server.ip + " > /dev/null" #store the whole command … -
How can a user add an element to their profile in django?
I'm writing a django view that should allow a user to add an anime to their profile but I'm not sure how to actually do this. The idea is that the user clicks a button that says something like 'add anime' and that adds it to a list in their profile. I have this function called 'favorite' but so far it doesn't do anything. The idea is that it would add it to the user's profile once they make the post request. def homepage(request): if request.method == 'POST': animes_url = 'https://api.jikan.moe/v3/search/anime?q={}&limit=6&page=1' search_params = { 'animes' : 'title', 'q' : request.POST['search'] } r = requests.get(animes_url, params=search_params) results = r.json() results = results['results'] animes = [] if len(results): for result in results: animes_data = { 'Id' : result["mal_id"], 'Title' : result["title"], 'Episodes' : result["episodes"], 'Image' : result["image_url"] } animes.append(animes_data) else: message = print("No results found") for item in animes: print(item) context = { 'animes' : animes } return render(request,'home.html', context) def favorite(request, pk): if request.method == 'POST': favorite = Anime.objects.get(pk=pk) user = request.user user.profile.add(favorite) messages.add_message(request, messages.INFO, 'Anime Favorited.') return redirect('home') These are the models: class Anime(models.Model): title = models.CharField('Title', max_length=150) episodes = models.IntegerField() image = models.ImageField() def __str__(self): return self.title class Profile(models.Model): … -
How to upload image from android app to django backend
I need to build android app upload image to my webserver(django backend) My Chart How can I do? Please help me!! -
About scaling the database in docker swarm
So I created a Docker Swarm with Django, Apache, and PostgreSQL all running in an overlay network called internal_network. When I scale Apache and Django services, it works perfectly fine, except for Django, I have to wait a little longer for it to do the migration. But when I scale the PostgreSQL service, Django just break, like first time go to my Django admin page okay then I reload the page Django printed out relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... If I reload again, Django admin back to normal again and this cycle keep looping when I reload the page. I think Django seem to be conflicted about having 2 PostgreSQL task running on my swarm that it just won't work properly -
Entorno en la toma de requerimientos funcionales
Cordial saludo comunidad Actualmente vengo desarrollando mi correspondiente proyecto de grado, el cual estoy realizando la toma de información primaria y me anime a realizar este proceso por medio de esta gran comunidad de colegas el cual me seria de gran ayuda su apoyo y estaría muy agradecido a quienes me colaboren. El proyecto trata sobre los procesos de documentación de software el cual permita la optimización de tiempos en el levantamiento de requerimientos, y para poder investigar, analizar y hacer todo este proceso me gustaría compartirles un formulario con 10 preguntas que no toman 5 min y el cual me ayudaría un mantón. Muchas gracias a todos por su colaboración. ----------------------------------> https://forms.office.com/r/nafCac28n6 <----------------------------- -
DRF simplejwt refresh access_token stored in HTTPonly cookies
I'm doing a project using React and django, I have used a DRF SimpleJWT for authentication. I have stored a access and refresh token in HTTPOnly cookies all are working fine but I didn't find the way to refresh the token. I can't make it through by reading a documentation. If somebody has done it before please share the code -
django urlinput placeholder
I noticed that placeholder works for EmailInput, NumberInput, and TextInput but not URLInput, the placeholder that I defined is not appearing. Here is a sample code snippet # forms.py class SampleForm(forms.ModelForm): class Meta: model = Sample fields = "__all__" widget = { "url": forms.URLInput( attrs={"placeholder": "https://www.google.com"}, ), } I can change URLInput to TextInput for placeholder to appear, but was wondering if I can do make it work with URLInput? Is it by design or I made a mistake somewhere? -
Transfer variable around from javascript to function in django view
Alright I'm trying to figure out the best way to pass a variable around from functions in my views.py file to javascript and back again. There might be a better way to do this. For context, I'm working with the Plaid api. Here is my javascript: <button id="link-button">Link Account</button> <button id="get-accounts-btn">Get Accounts</button> <div id="get-accounts-data"></div> #START JS CODE <script type="text/javascript"> (async function($) { var handler = Plaid.create({ // Create a new link_token to initialize Link token: (await $.post('/create_link_token')).link_token, onSuccess: function(public_token, metadata) { $.post('/exchange_public_token', { public_token: public_token, }); }, onExit: function(err, metadata) { // The user exited the Link flow. if (err != null) { var html = '<strong>' + err + '</strong'; } }, }); $('#link-button').on('click', function(e) { handler.open(); }); //THIS IS WHERE I STARTED MY OWN JAVASCRIPT TO TRY AND GET ACCOUNT INFO $('#get-accounts-btn').on('click', function(e) { // Need to get access_token variable from exchange_public_token in views.py file and pass it to /accounts $.get('/accounts', function(data) { $('#get-accounts-data').slideUp(function() { var html = ''; data.accounts.forEach(function(account, idx) { html += '<div class="inner">'; html += '<strong>' + account.name + ' $' + (account.balances.available != null ? account.balances.available : account.balances.current) + '</strong><br>'; html += account.subtype + ' ' + account.mask; html += '</div>'; }); $(this).html(html).slideDown(); }); … -
How can I do the Unit testing of these custom permissions in my Django/Django REST project?
everyone. I hope you're doing well. I'm a Django newbie, trying to learn the basics of RESTful development. I only know Python, so this is my best fit for the moment. Right now I'm trying to implement Unit tests for my API. It's a simple model to implement CRUD on the names and heights of NBA players. In my models I added a class to describe this data and translated it to a view with ModelViewSets. I wanted to make this data editable only for a specific type of user (a read-write user), only readable for another (read-only user) as well as unaccesible to non-authenticated users. To do so, I created a custom User Model and translated it to my views with a custom permission. Now I want to write a few Unit tests to check that: r/w user can create a new player r/w user can get a list of players r/o user cannot create a new player r/o user can get a list of players unauthenticated user cannot create a new player unauthenticated user cannot get a list of players Here is my models.py: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): ROLES = [('read-only', 'read-only'), … -
Django Background Tasks - Why are my tasks scheduled later?
I'm trying to make a simple function as a Django Background Task, I installed it and it shows no error. However, when I trigger the method, instead of doing the process 15 minutes after, as I tell it, in the database, in the table background_task, it shows it's scheduled to do it 5 hours and 15 minutes later. I imagine it's maybe taking the time of my server where it's running, but I don't know how to verify what is actually causing this time difference. In my Django settings, I have this: TIME_ZONE = 'America/Mexico_City' Which is my correct timezone, and when I do, for instance, datetime.datetime.now(), it does show my localized time, so I don't know what else could be the problem. -
python3 bot.py django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I have a telegram bot witch depends on a Django app, I'm trying to deploy it on Heroku but I get this error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when it runs python3 main/bot.py in Heroku here is my Procfile: web: gunicorn telega.wsgi worker: python main/bot.py main/bot.py: import telebot import traceback from decimal import Decimal, ROUND_FLOOR import requests import json from django.conf import settings from preferences import preferences from main.markups import * from main.tools import * config = preferences.Config TOKEN = config.bot_token from main.models import * from telebot.types import LabeledPrice # # # if settings.DEBUG: TOKEN = 'mybottoken' # # # bot = telebot.TeleBot(TOKEN) admins = config.admin_list.split('\n') admin_list = list(map(int, admins)) @bot.message_handler(commands=['start']) def start(message): user = get_user(message) lang = preferences.Language clear_user(user) if user.user_id in admin_list: bot.send_message(user.user_id, text=clear_text(lang.start_greetings_message), reply_markup=main_admin_markup(), parse_mode='html') else: bot.send_message(user.user_id, text=clear_text(lang.start_greetings_message), reply_markup=main_menu_markup(), parse_mode='html') @bot.message_handler(func=lambda message: message.text == preferences.Language.porfolio_button) def porfolio_button(message): .... ... and my settings.py: """ Django settings for telega project. Generated by 'django-admin startproject' using Django 2.2.7. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import django_heroku import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - …