run two celery task - django

i use celery in django ,
i add a task to my project and get error, but before add this task my project is work good.
# app_account.celery_task.py
my first task is :
#shared_task
def send_birthday_email():
users = User.objects.filter(is_active=True, date_of_birth__isnull=False, email__isnull=False)
time = datetime.today()
for user in users:
if user.date_of_birth.day == time.day and user.date_of_birth.month == time.month:
send_mail(
f'happy birthday',
f'Happy birthday, dear {user.name}, have a good year',
'local#host.com',
[user.email],
)
my new task :
#shared_task
def send_password_reset_mail(mail_info):
send_mail(
subject=mail_info['subject'],
message=mail_info['message'],
from_email=mail_info['from_email'],
recipient_list=mail_info['recipient_list'],
)
second task use in this signal:
# this signal for send email reset password
#receiver(reset_password_token_created)
def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs):
email_plaintext_message = f"your token is = {reset_password_token.key}"
mail_info = {
'subject': 'Password Reset',
'message': email_plaintext_message,
'from_email': 'noreply#host.com',
'recipient_list': [reset_password_token.user.email],
}
send_password_reset_mail.delay(mail_info)
now , when i run by python manage.py runserver get this error
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/rahmanipy/Desktop/DrfBlog/venv/lib/python3.8/site-packages/django_rest_passwordreset/models.py", line 121, in <module>
UserModel = get_user_model()
File "/home/rahmanipy/Desktop/DrfBlog/venv/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 160, in get_user_model
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
File "/home/rahmanipy/Desktop/DrfBlog/venv/lib/python3.8/site-packages/django/apps/registry.py", line 209, in get_model
app_config.import_models()
File "/home/rahmanipy/Desktop/DrfBlog/venv/lib/python3.8/site-packages/django/apps/config.py", line 301, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/rahmanipy/Desktop/DrfBlog/app_account/models.py", line 4, in <module>
from app_account.celery_tasks import send_password_reset_mail
File "/home/rahmanipy/Desktop/DrfBlog/app_account/celery_tasks.py", line 4, in <module>
from app_account.models import User
ImportError: cannot import name 'User' from partially initialized module 'app_account.models' (most likely due to a circular import) (/home/rahmanipy/Desktop/DrfBlog/app_account/models.py)
can anyone help me ???

You can inline import User inside your first task to avoid the circular import.
#shared_task
def send_birthday_email():
from app_account.models import User
users = User.objects.filter(is_active=True, date_of_birth__isnull=False, email__isnull=False)
time = datetime.today()
for user in users:
if user.date_of_birth.day == time.day and user.date_of_birth.month == time.month:
send_mail(
f'happy birthday',
f'Happy birthday, dear {user.name}, have a good year',
'local#host.com',
[user.email],
)

Related

No module named 'rest_framework' on pythonanywhere.com

I'm trying to host my Django app on https://pythonanywhere.com
I'm am getting the following error :
ModuleNotFoundError: No module named 'rest_framework'
I tried
pip install djangorestframework
pip3 install djangorestframework
but its is still showing error.
I also tried pip freeze and found djangorestframework==3.13.1 in the list.
>>> import rest_framework
also works fine.
I ran my project locally and also it in a new virtual env, it worked fine. Installed same requirements.txt on pythonanywhere but still the same error.
This is bugging me for a long time! please help
here is my error log file:
2021-12-22 10:59:23,012: Internal Server Error: /
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 167, in _get_response
callback, callback_args, callback_kwargs = self.resolve_request(request)
File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 290, in resolve_request
resolver_match = resolver.resolve(request.path_info)
File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 556, in resolve
for pattern in self.url_patterns:
File "/usr/local/lib/python3.8/dist-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.8/dist-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/shantanu2k21/ytPlaylist/ytPlaylist/urls.py", line 20, in <module>
path('',include('play.urls')),
File "/usr/local/lib/python3.8/dist-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/shantanu2k21/ytPlaylist/play/urls.py", line 3, in <module>
from . import views
File "/home/shantanu2k21/ytPlaylist/play/views.py", line 13, in <module>
from rest_framework.decorators import api_view
ModuleNotFoundError: No module named 'rest_framework'
I was not using a virtual environment but using one and configuring it worked.

How to store the default value for a Django form in the database?

I have a page with bookmarks and I want to implement several types of sorting for them. The user chooses the type of sorting and it's stored in the database. He/she sees the chosen type of sorting as the default value for the select-menu.
I wrote this:
class BookmarksSortingForm(forms.Form):
SORTING_CHOICES = [(1, "новым"),
(2, "имени"),
(3, "звёздам -"),
(4, "звёздам +")]
bm_sorting = forms.ChoiceField(SORTING_CHOICES)
# https://stackoverflow.com/questions/6325681/passing-a-user-request-to-forms
# In your view: form = MyForm(..., request=request)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
super().__init__(*args, **kwargs)
self.fields['bm_sorting'].initial = BookmarksSortingForm.SORTING_CHOICES[self.get_current_sorting() - 1][1]
def get_current_sorting(self):
user = User.objects.get(username=self.request.user)
return user.profile.bookmarks_sorting # small integer, default = 1
But I get "TypeError: init() takes 1 positional argument but 2 were given" at the line with bm_sorting. How could I fix this? Django version is 3.2.4.
Upd: Traceback
Traceback (most recent call last):
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__
response = self.process_request(request)
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/middleware/common.py", line 53, in process_request
if self.should_redirect_with_slash(request):
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/middleware/common.py", line 70, in should_redirect_with_slash
if not is_valid_path(request.path_info, urlconf):
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/base.py", line 153, in is_valid_path
return resolve(path, urlconf)
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/base.py", line 24, in resolve
return get_resolver(urlconf).resolve(path)
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/resolvers.py", line 556, in resolve
for pattern in self.url_patterns:
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
<source code not available>
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
<source code not available>
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
<source code not available>
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
<source code not available>
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
<source code not available>
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
<source code not available>
File "/home/gamecoach/Seearo/Seearo/urls.py", line 23, in <module>
re_path('account/?', include('account.urls')),
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
<source code not available>
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
<source code not available>
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
<source code not available>
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
<source code not available>
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
<source code not available>
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
<source code not available>
File "/home/gamecoach/Seearo/account/urls.py", line 2, in <module>
from account.views import AccountView, AchievementsView, AddToBookmarksView, \
File "/home/gamecoach/Seearo/account/views.py", line 8, in <module>
from account.forms import SettingsForm, UploadPhotoForm
File "/home/gamecoach/Seearo/account/forms.py", line 6, in <module>
class BookmarksSortingForm(forms.Form):
File "/home/gamecoach/Seearo/account/forms.py", line 13, in BookmarksSortingForm
bm_sorting = forms.ChoiceField(SORTING_CHOICES)
Exception Type: TypeError at /account/bookmarks.html
Exception Value: __init__() takes 1 positional argument but 2 were given
Upd2:
The answer below helped:
bm_sorting = forms.ChoiceField(choices=SORTING_CHOICES)
and I also had to change a bit this line:
self.fields['bm_sorting'].initial = BookmarksSortingForm.SORTING_CHOICES[self.get_current_sorting() - 1]
and it started to show my form.
You must pass a keyword argument instead of positional to the forms.ChoiceField.
bm_sorting = forms.ChoiceField(choices=SORTING_CHOICES)
Here is how the ChoiceField is defined in Django. Notice the * after self - this denotes that only keyword arguments will be accepted.
class ChoiceField(Field):
def __init__(self, *, choices=(), **kwargs):
super().__init__(**kwargs)
self.choices = choices

Return just the last object in Django REST Framework

I'm new to asking on StackOverflow and to Django so I'm sorry if I made any mistakes.
So far, I have a basic API with Django and REST Framework. I want to return just the last object that was added to the database, which could be done with the highest ID.
This is the models.py:
from django.db import models
class Humidity(models.Model):
value = models.FloatField()
class Temperature(models.Model):
value = models.FloatField()
isFarenheit = models.BooleanField()
I don't have any time fields, but I can add them if necessary.
This is the serializers.py:
class HumiditySerializer(serializers.ModelSerializer):
class Meta:
model = Humidity
fields = ('id', 'value')
class TemperatureSerializer(serializers.ModelSerializer):
class Meta:
model = Temperature
fields = ('id', 'value', 'isFarenheit')
And this is the views.py:
from django.shortcuts import render
from rest_framework import viewsets, permissions
from .models import Humidity, Temperature
from .serializers import HumiditySerializer, TemperatureSerializer
class HumidityView(viewsets.ModelViewSet):
queryset = Humidity.objects.order_by('-id')[0]
serializer_class = HumiditySerializer
class TemperatureView(viewsets.ModelViewSet):
queryset = Temperature.objects.order_by('-id')[0]
serializer_class = TemperatureSerializer
This is the traceback of the error:
Traceback (most recent call last):
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 398, in check
for pattern in self.url_patterns:
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\iotSensors\urls.py", line 21, in <module>
path('', include('api.urls')),
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\api\urls.py", line 6, in <module>
router.register('humidity', views.HumidityView)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 75, in register
basename = self.get_default_basename(viewset)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 162, in get_default_basename
return queryset.model._meta.object_name.lower()
AttributeError: 'Humidity' object has no attribute 'model'
This error is only thrown when I change in the views.py from Humidity.objects.all() to Humidity.objects.order_by('-id')[0] and the same with temperature.
How do I return the last object saved?
Since you don't have time or date fields in your model, you may retrieve the latest object only through id.
Humidity.objects.all().order_by('-id')[:1]
-id retrieves the objects in the reverse order.
Since QueryDict object of django is lazily loaded, this will only retrieve the latest value.
You can use the last function to retrieve the latest object
Humidity.objects.all().latest()
or just retrieve the object with the latest id by
Humidity.objects.latest('id')
# To get last object or record
Humidity.objects.last()

Django can not see any of the installed apps

After a minor migration I keep receiving the following error from Django's runserver command:
RuntimeError: Model class captcha.models.CaptchaStore doesn't declare an explicit app_label and isn't in an application in INSTALLED
_APPS.
This is caused by django-simple-captcha
which has been working for quite a while (a month). I haven't changed something in this exact app.
I have uninstalled it and now Django can't find ADMIN app, so that it has something to do with integrity.
My settings are like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# custom
"boats.apps.BoatsConfig",
"articles.apps.ArticlesConfig",
#3rd party
"captcha",
"bootstrap4",
"django_cleanup",
"easy_thumbnails",
"social_django",
"crispy_forms",
"extra_views",
"debug_toolbar",
"reversion",
"dynamic_validator",
"django.forms", # new for a custom widgets
How I can fix this problem? It seems weird… Or alternativelly how to roll back the last migration?
full trace-back is below:
(myproject) C:\Users\hardcase1\PycharmProjects\myproject>python manage.py runserver
Watching for file changes with StatReloader
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\python\Lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\python\Lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\core\management\commands\runserver.py", line 109
, in inner_run
autoreload.raise_last_exception()
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exc
eption
raise _exception[0](_exception[1]).with_traceback(_exception[2])
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\apps\config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\hardcase1\PycharmProjects\myproject\boats\models.py", line 9, in <module>
from articles.models import SubHeading
File "C:\Users\hardcase1\PycharmProjects\myproject\articles\models.py", line 4, in <module>
from boats.models import ExtraUser
ImportError: cannot import name 'ExtraUser' from 'boats.models' (C:\Users\hardcase1\PycharmProjects\myproject\boats\models.py)
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\core\management\__init__.py", line 381, in execu
te_from_command_line
utility.execute()
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\core\management\__init__.py", line 375, in execu
te
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\core\management\base.py", line 323, in run_from_
argv
self.execute(*args, **cmd_options)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\core\management\commands\runserver.py", line 60,
in execute
super().execute(*args, **options)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\core\management\commands\runserver.py", line 95,
in handle
self.run(**options)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\core\management\commands\runserver.py", line 102
, in run
autoreload.run_with_reloader(self.inner_run, **options)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\autoreload.py", line 579, in run_with_relo
ader
start_django(reloader, main_func, *args, **kwargs)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\autoreload.py", line 564, in start_django
reloader.run(django_main_thread)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\autoreload.py", line 272, in run
get_resolver().urlconf_module
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\urls\resolvers.py", line 564, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\hardcase1\PycharmProjects\myproject\myproject\urls.py", line 14, in <module>
path("captcha/", include("captcha.urls")),
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\captcha\urls.py", line 2, in <module>
from captcha import views
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\captcha\views.py", line 3, in <module>
from captcha.models import CaptchaStore
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\captcha\models.py", line 25, in <module>
class CaptchaStore(models.Model):
File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\db\models\base.py", line 111, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class captcha.models.CaptchaStore doesn't declare an explicit app_label and isn't in an application in INSTALLED
_APPS.
Final migration
class Migration(migrations.Migration):
dependencies = [
('boats', '0014_auto_20190419_1429'),
]
operations = [
migrations.AlterField(
model_name='boatimage',
name='boat_photo',
field=models.ImageField(blank=True, upload_to=boats.utilities.get_timestamp_path, verbose_name='Boat photo'),
), # i removed help_text here
migrations.AlterField(
model_name='boatmodel',
name='boat_mast_type',
field=models.CharField(choices=[(None, 'Please choose rigging type'), ('SL', 'Sloop'), ('KE', 'Ketch'), ('YA', 'Yawl'), ('CK', 'Cat Ketch')], help_text='Please input boat rigging type', max_length=10, verbose_name='Boat rigging type'), # i added (None, 'Please choose rigging type') here
),
]
I presume you just uninstalled django-simple-captcha? Remove "captcha" from INSTALLED_APPS as well, or Django will still look for the app.
And of course delete all CaptchaFields from your models.
It was a circular import. Solution has been found, thanks to Alasdair.
I hid 2 imports inside the method...
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
from articles.models import SubHeading, UpperHeading
SubHeading.objects.update_or_create(name=self.boat_name, order=0,
foreignkey_id=93)
models.Model.save(self, force_insert=False, force_update=False, using=None,
update_fields=None)

Getting an error when trying to set input_formats for Django TimeField

I am using the following model to represent a Class:
class Class(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
day = models.CharField(max_length=10, choices=WEEK_DAYS)
timing = models.TimeField(input_formats = ['%I:%M %p', ])
room = models.CharField(max_length=10)
I want to set my TimeField's format to 12 hours with am and pm. Django's documentation mentions using an input_formats argument to accomplish this here. However, when I run makemigrations, I get the following error:
Traceback (most recent call last):
File ".\manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "D:\Applications\Python\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
utility.execute()
File "D:\Applications\Python\lib\site-packages\django\core\management\__init__.py", line 347, in execute
django.setup()
File "D:\Applications\Python\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\Applications\Python\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "D:\Applications\Python\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "D:\Applications\Python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\plannerly\timetable\models.py", line 15, in <module>
class Class(models.Model):
File "D:\plannerly\timetable\models.py", line 18, in Class
timing = models.TimeField(input_formats = ['%I:%M %p', ])
File "D:\Applications\Python\lib\site-packages\django\db\models\fields\__init__.py", line 2146, in __init__
super().__init__(verbose_name, name, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'input_formats'
I'm not really sure whats causing this. Any ideas?
input_formats is for forms.DateField()[1]. It is not a model.DateField()[2] option.
You have to set input_fomats=[] in your form, not in your models.
[1] https://docs.djangoproject.com/en/2.2/ref/forms/fields/#timefield
[2] https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.DateField