Django Error on edit in Django admin - python-3.x

When I try to change one of my models in the django admin I am getting the below error.
Here is my model.
class Scan(models.Model):
image = models.FileField(upload_to = 'images/', default = 'images/')
R = models.IntegerField(255)
G = models.IntegerField(255)
B = models.IntegerField(255)
description = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
project = models.ForeignKey(Project,
on_delete=models.CASCADE,null=True)
clean = models.NullBooleanField(null=True, default= False)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper
574. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/options.py" in add_view
1553. return self.changeform_view(request, None, form_url, extra_context)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
62. return bound_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
58. return func.get(self, type(self))(*args2, **kwargs2)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/options.py" in changeform_view
1450. return self._changeform_view(request, object_id, form_url, extra_context)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/options.py" in _changeform_view
1482. if form.is_valid():
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/forms.py" in is_valid
179. return self.is_bound and not self.errors
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/forms.py" in errors
174. self.full_clean()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/forms.py" in full_clean
378. self._post_clean()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/models.py" in _post_clean
401. self.instance.full_clean(exclude=exclude, validate_unique=False)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py" in full_clean
1151. self.clean()
Exception Type: TypeError at /admin/api/scan/add/
Exception Value: 'bool' object is not callable

You are overriding clean, which is a func in the model. Rename that variable.

Related

Unable to read a url using fsspec https filesystem implementation directly

I am using fsspec package to implement a function to read an https file.
_hostname = socket.gethostname()
proxy_auth = aiohttp.BasicAuth(_hostname, pwd)
of = fsspec.filesystem("https", client_kwargs={"trust_env":True, "auth":proxy_auth})
http_urls = ["https://stackoverflow.com/"]
print(of.cat(http_urls))
The above code is not fetching the content of the url. The stack trace for the above code is as follows:
File "C:\Anaconda3\envs\mvision\lib\site-packages\fsspec\asyn.py", line 91, in wrapper
return sync(self.loop, func, *args, **kwargs)
File "C:\Anaconda3\envs\mvision\lib\site-packages\fsspec\asyn.py", line 71, in sync
raise return_result
File "C:\Anaconda3\envs\mvision\lib\site-packages\fsspec\asyn.py", line 25, in _runner
result[0] = await coro
File "C:\Anaconda3\envs\mvision\lib\site-packages\fsspec\asyn.py", line 347, in _cat
raise ex
File "C:\Anaconda3\envs\mvision\lib\site-packages\fsspec\implementations\http.py", line 230, in _cat_file
async with session.get(url, **kw) as r:
File "C:\Anaconda3\envs\mvision\lib\site-packages\aiohttp\client.py", line 1117, in __aenter__
self._resp = await self._coro
File "C:\Anaconda3\envs\mvision\lib\site-packages\aiohttp\client.py", line 521, in _request
req, traces=traces, timeout=real_timeout
File "C:\Anaconda3\envs\mvision\lib\site-packages\aiohttp\connector.py", line 535, in connect
proto = await self._create_connection(req, traces, timeout)
File "C:\Anaconda3\envs\mvision\lib\site-packages\aiohttp\connector.py", line 892, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "C:\Anaconda3\envs\mvision\lib\site-packages\aiohttp\connector.py", line 1011, in _create_direct_connection
raise ClientConnectorError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host stackoverflow.com:443 ssl:default [getaddrinfo failed]
But if we wrap it with a cache, I am able to get the content.
_hostname = socket.gethostname()
proxy_auth = aiohttp.BasicAuth(_hostname, pwd)
of = fsspec.filesystem("simplecache", target_protocol="https", \
target_options={"client_kwargs":{"trust_env":True, "auth":proxy_auth}},
cache_storage="/tmp/files")
http_urls = ["https://stackoverflow.com/"]
print(of.cat(http_urls))
Why is the first code section not able to fetch the content? Am I doing anything wrong ?

AttributeError at /logout/ 'tuple' object has no attribute 'backend'

I used Python3 in windows 10 to write a django2 web app.
I tried to configure the LDAP login, but failed.
When I test using postman, it could get the reply successfully.
That is, I send a request to https://example.com/staff, with some authentication code and payload containing username and password, and it reply me with the LDAP reply.
However, when I tried to using ldap3 in Django, after successfully login, error shows:
AttributeError at /logout/
'tuple' object has no attribute 'backend'
code:
settings.py:
AUTHENTICATION_BACKENDS = (
'app.backends.LDAPBackend',
('django.contrib.auth.backends.ModelBackend'),
)
app/backends.py:
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class LDAPBackend:
def authenticate(self, request, username=None, password=None, **kwargs):
try:
headers = {'Authorization': xxxxx}
body = {"username": username, "password": password}
response = requests.post(url="https://example.com/staff", json=body, headers=headers)
result = response.json()
print(result)
if result['code'] != "OK":
logger.info("Wrong Login Information")
return None
print("connected")
except Exception as e:
print(e)
user = UserModel.objects.update_or_create(username=username)
return user
def get_user(self, user_id):
try:
return UserModel._default_manager.get(pk=user_id)
except UserModel.DoesNotExist:
return None
error shows: AttributeError at /logout/ 'tuple' object has no attribute 'backend', below shows result in console:
connected
Internal Server Error: /logout/
Traceback (most recent call last):
File "C:\Users\software\python\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\software\python\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\software\python\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\contrib\auth\views.py", line 61, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\software\python\lib\site-packages\django\views\generic\edit.py", line 141, in post
if form.is_valid():
File "C:\Users\software\python\lib\site-packages\django\forms\forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "C:\Users\software\python\lib\site-packages\django\forms\forms.py", line 180, in errors
self.full_clean()
File "C:\Users\software\python\lib\site-packages\django\forms\forms.py", line 382, in full_clean
self._clean_form()
File "C:\Users\software\python\lib\site-packages\django\forms\forms.py", line 409, in _clean_form
cleaned_data = self.clean()
File "C:\Users\software\python\lib\site-packages\django\contrib\auth\forms.py", line 205, in clean
self.user_cache = authenticate(self.request, username=username, password=password)
File "C:\Users\software\python\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
user.backend = backend_path
AttributeError: 'tuple' object has no attribute 'backend'
[22/Mar/2021 09:49:10] "POST /logout/ HTTP/1.1" 500 149071
You write the following line:
user = UserModel.objects.update_or_create(username=username)
The update_or_create method returns a tuple with the object and a boolean with whether the object was created. So you are storing this tuple in the variable user and returning that. But authenticate is supposed to return only the user causing unintended effects leading to an error. Also you should be using get_or_create [Django docs] instead of update_or_create.
So you should change that above line to:
user, created = UserModel.objects.get_or_create(username=username)

Pickling Python Function fails with ProcessPoolExecutor in a decorator

So I asked this question and tried the ProcessPoolExecutor approach. I used the decorator suggested the following way:
Running Image Manipulation in run_in_executor. Adapting to multiprocessing
import asyncio
import functools
from concurrent import futures
from app.exceptions.errors import ManipulationError
_pool = futures.ProcessPoolExecutor()
def executor(function):
#functools.wraps(function)
def decorator(*args, **kwargs):
try:
partial = functools.partial(function, *args, **kwargs)
loop = asyncio.get_event_loop()
return loop.run_in_executor(_pool, partial)
except Exception as e:
raise ManipulationError(str(e))
return decorator
I then used it on a function like:
#executor
#pil
def blur(image):
frame = image.convert("RGBA")
return frame.filter(ImageFilter.BLUR)
Note the #pil is another decorator I made.
def pil(function):
#functools.wraps(function)
def wrapper(image, *args, **kwargs) -> BytesIO:
img = PILManip.pil_image(image)
if img.format == "GIF":
frames = []
for frame in ImageSequence.Iterator(img):
res_frame = function(frame, *args, **kwargs)
frames.append(res_frame)
return PILManip.pil_gif_save(frames), "gif"
elif img.format in ["PNG", "JPEG"]:
img = function(img, *args, **kwargs)
return PILManip.pil_image_save(img), "png"
else:
raise BadImage("Bad Format")
return wrapper
I called it in a FastApi route like so:
#router.get("/blur/", responses=normal_response)
async def blur_image(url: str):
byt = await Client.image_bytes(url)
img, image_format = await blur(byt)
return Response(img.read(), media_type=f"image/{image_format}")
I get some error about pickling.
500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 391, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
await super().__call__(scope, receive, send)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/middleware/base.py", line 25, in __call__
response = await self.dispatch_func(request, self.call_next)
File "/home/codespace/workspace/dagpi-image/app/middleware/timer.py", line 8, in add_process_time_header
response = await call_next(request)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/middleware/base.py", line 45, in call_next
task.result()
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/middleware/base.py", line 38, in coro
await self.app(scope, receive, send)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/middleware/base.py", line 25, in __call__
response = await self.dispatch_func(request, self.call_next)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette_prometheus/middleware.py", line 56, in dispatch
raise e from None
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette_prometheus/middleware.py", line 52, in dispatch
response = await call_next(request)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/middleware/base.py", line 45, in call_next
task.result()
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/middleware/base.py", line 38, in coro
await self.app(scope, receive, send)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
await route.handle(scope, receive, send)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/fastapi/routing.py", line 201, in app
raw_response = await run_endpoint_function(
File "/home/codespace/workspace/dagpi-image/.venv/lib/python3.8/site-packages/fastapi/routing.py", line 148, in run_endpoint_function
return await dependant.call(**values)
File "/home/codespace/workspace/dagpi-image/app/routes/image_routes.py", line 107, in blur_image
img, image_format = await blur(byt)
File "/opt/python/3.8.6/lib/python3.8/multiprocessing/queues.py", line 239, in _feed
obj = _ForkingPickler.dumps(obj)
File "/opt/python/3.8.6/lib/python3.8/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function blur at 0x7f87524091f0>: it's not the same object as app.image.pil_manipulation.blur
Does someone know why this keeps happening?
I was told the objects have to be serializable, I believe BytesIO is the only in/out of the image. That should be serializable.
Decorators typically produce wrapped functions that aren't easy to pickle (serialize) because they contain hidden state. When dealing with multiprocessing, you should avoid decorators and send ordinary global functions to run_in_executor. For example, you could re-write your executor decorator into a utility function:
_pool = concurrent.futures.ProcessPoolExecutor()
async def exec_async(fn, *args):
loop = asyncio.get_event_loop()
return await loop.run_in_executor(_pool, fn, *args)
Instead of decorating a function with executor, you can just await it using await exec_async(some_function, arg1, arg2, ...). Likewise, you can rewrite the pil decorator into another utility:
def pil(image, transform):
img = PILManip.pil_image(image)
if img.format == "GIF":
frames = []
for frame in ImageSequence.Iterator(img):
res_frame = transform(frame)
frames.append(res_frame)
return PILManip.pil_gif_save(frames), "gif"
elif img.format in ["PNG", "JPEG"]:
img = transform(img)
return PILManip.pil_image_save(img), "png"
else:
raise BadImage("Bad Format")
The implementation of blur now becomes an ordinary function which calls pil, and which can be safely passed to exec_async:
def blur(image):
def transform(frame):
frame = frame.convert("RGBA")
return frame.filter(ImageFilter.BLUR)
return pil(image, transform)
#router.get("/blur/", responses=normal_response)
async def blur_image(url: str):
byt = await Client.image_bytes(url)
img, image_format = await exec_async(blur, byt)
return Response(img.read(), media_type=f"image/{image_format}")
Note: the above code is untested.

Flask-Login: AttributeError: 'int' object has no attribute 'is_authenticated'

I am using python3 with Flask 1.1.1 and Werkzeug 0.16.0.
I am trying to use the Flask login manager to manage the user sessions.
For the DB am running sqlite3.
Below is the class definition
class UserData(UserMixin):
def __init__(self, username, password):
self.username = username
self.password = password
self._authenticated = False
def is_authenticated(self):
return self._authenticated
def is_active(self):
return True
# return true if user is activte and authenticated
def is_annonymous(self):
return False
# return true if annon, actual user return false
def get_id(self):
global connection
user_id = get_user_id(self.username, connection)
unicode_user_id = load_user(user_id)
if unicode_user_id != 0:
self._authenticated = True
print("userid:" , unicode_user_id)
return unicode_user_id
In the function get_id , I fetch the user-id from the DB and set the self._authenticated flag for the authentication.
#login_manager.user_loader
def load_user(user_id):
return int(user_id)
The below is the protected page which should be accessed only but authorized users.
#app.route('/device_detail', methods=['GET', 'POST'])
#login_required
def device_detail_operation():
error = None
return render_template('device_detail.html', error=error)
After the user login when I try to access the protected page directly am running into attribute error.
Below is a stack trace
127.0.0.1 - - [11/Dec/2019 22:52:26] "GET /device_detail HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2328, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2314, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1760, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1832, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1818, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python3.7/site-packages/flask_login/utils.py", line 259, in decorated_view
elif not current_user.is_authenticated:
File "/usr/local/lib/python3.7/site-packages/werkzeug/local.py", line 348, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'int' object has no attribute 'is_authenticated'
In load_user function, you need to return user object. I did not use sqlite but i guess that have something like that: user = models.User.query().filter(models.User.email == user_id).get()
#login_manager.user_loader
def load_user(user_id):
user = models.User.query().filter(models.User.email == user_id).get()
return user

NOT NULL constraint failed: new__common_farmmodel.user_id

I'm trying to make a part of application for the farmer. I did part with registration, loggin and option "add new farm" for the loggin user, but when I tried to add new farm (filled all fields and click on "POST") it was:
django.db.utils.IntegrityError: NOT NULL constraint failed:
new__common_farmmodel.user_id
I found this NOT NULL constraint failed: user_profile.user_id
and tried redo my FarmModel, by now when tried migrate I get:
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle
fake_initial=fake_initial,
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\sqlite3\schema.py", line 137, in alter_field
super().alter_field(model, old_field, new_field, strict=strict)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\base\schema.py", line 535, in alter_field
old_db_params, new_db_params, strict)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\sqlite3\schema.py", line 359, in _alter_field
self._remake_table(model, alter_field=(old_field, new_field))
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\sqlite3\schema.py", line 286, in _remake_table
self.quote_name(model._meta.db_table),
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\base\schema.py", line 137, in execute
cursor.execute(sql, params)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\utils.py", line 99, in execute
return super().execute(sql, params)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\filip\.virtualenvs\ToDoBees\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: new__common_farmmodel.user_id
My actual part of code:
# models.py
FARMER = 'Farmer'
BEEKEEPER = 'Beekeeper'
BUYER = 'Buyer'
USER_TYPE_WITH_NAME_CHOICES = [(FARMER, 'Farmer'), (BEEKEEPER, 'Beekeeper'), (BUYER, 'Buyer')]
class CustomUser(BaseUser):
user = BaseUserManager()
role = models.CharField(choices=USER_TYPE_WITH_NAME_CHOICES, max_length=10, default=BUYER)
telephone = models.CharField(max_length=12)
add_new_farm = models.BooleanField(default=False)
class FarmModel(models.Model):
user = ForeignKey(CustomUser, default=CustomUser, null=None, on_delete=CASCADE)
is_fallen = models.BooleanField(default=False)
it_forest = models.BooleanField(default=False)
farm_location = models.CharField(max_length=250)
since_when_sown = models.DateField()
field_size = models.IntegerField()
additional_description = models.CharField(max_length=1000)
crop_type = models.CharField(max_length=100)
# serializers.py
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length=100, min_length=4, required=True, label='Set your password', write_only=True)
password2 = serializers.CharField(max_length=100, min_length=4, label='Confirm Password', write_only=True)
telephone = serializers.CharField(max_length=12, label='Enter your phone number', required=False)
from .models import USER_TYPE_WITH_NAME_CHOICES
role = serializers.ChoiceField(required=True, choices=USER_TYPE_WITH_NAME_CHOICES)
class Meta:
model = CustomUser
fields = ('email', 'role', 'password', 'password2', 'first_name', 'last_name', 'telephone')
def create(self, validator_data):
user = CustomUser.objects.create()
user.set_password(validator_data['password'])
user.save()
return user
def hash_password(password):
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000)
pwdhash = binascii.hexlify(pwdhash)
return (salt + pwdhash).decode('ascii')
def verify_password(stored_password, provided_password):
salt = stored_password[:64]
stored_password = stored_password[64:]
pwdhash = hashlib.pbkdf2_hmac('sha512', provided_password.encode('utf-8'), salt.encode('ascii'), 100000)
pwdhash = binascii.hexlify(pwdhash).decode('ascii')
return pwdhash == stored_password
def validate(self, attrs):
if attrs.get('password') != attrs.get('password2'):
raise serializers.ValidationError('Those passwords don\'t match.')
return attrs
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = ('add_new_farm',)
class AddFarmSerializer(serializers.ModelSerializer):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
class Meta:
model = FarmModel
fields = ('is_fallen', 'it_forest', 'farm_location', 'since_when_sown', 'field_size', 'additional_description', 'crop_type')
def create(self, validated_data):
user = self.context.get('user')
validated_data['user'] = user
return FarmModel.objects.create(**validated_data)
# views.py
User = get_user_model()
class UserRegistration(CreateAPIView):
queryset = User.objects.all()
serializer_class = RegisterSerializer
authentication_classes = ()
permission_classes = ()
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)
def login_request(request):
return render(request=request, template_name='')
class LoggedUserView(ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
def list(self, request, **kwargs):
queryset = self.get_queryset()
serializer = UserSerializer(queryset)
return Response(serializer.data)
class AddFarm(CreateAPIView):
queryset = FarmModel.objects.all()
serializer_class = AddFarmSerializer
def create(self, request, *args, **kwargs):
data = request.data.copy()
data['user'] = request.user
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
user = request.user
serializer = AddFarmSerializer(AddFarm, context={'user': user})
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) ```
You should use boolean field for null. null = None does not make sense.
You can use
null= True or null=False
Here you have to use null=True
because you want null value(by default) supported field
Documentation link here
I suppose that is not problem in model, I think so... Tell me, it is good code in views:
class AddFarm(CreateAPIView):
queryset = FarmModel.objects.all()
serializer_class = AddFarmSerializer
def create(self, request, *args, **kwargs):
data = request.data.copy()
data['user'] = request.user
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
user = request.user
serializer = AddFarmSerializer(AddFarm, context={'user': user})
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
and in serializers:
class AddFarmSerializer(serializers.ModelSerializer):
# permission_classes = [permissions.IsAuthenticatedOrReadOnly]
class Meta:
model = FarmModel
fields = ('is_fallen', 'it_forest', 'farm_location', 'since_when_sown', 'field_size', 'additional_description',
'crop_type')
def create(self, validated_data):
user = self._context.get('user')
validated_data['user'] = user
return FarmModel.objects.create(**validated_data)
?
I can't find any solution :/

Resources