Related
Notification are already working in the view class. But not working in admin.py
I do send the puh notification after the save record in save_model. but not working here is my method
class EventAdmin(admin.ModelAdmin):
list_display = ('event_name', 'event_type', 'event_city', 'event_organizer', 'start_date',
'start_time', 'end_date', 'end_time', 'is_approved', 'is_active', 'created_at')
fields = ('main_image', 'event_name', 'event_organizer', 'event_type', 'event_city', 'event_tag', 'event_address', 'event_description',
'event_notes', 'start_date', 'start_time', 'end_date', 'end_time', 'age_max', 'age_min', 'event_lat', 'event_lng', 'website', 'is_approved', 'is_active', 'created_at')
def save_model(self, request, instance, form, change):
user = request.user
instance = form.save(commit=False)
if not change or not instance.created_by:
instance.created_by = user
# Here is notification class
notifiClass = Notifications()
notifiClass.sendNotifications(instance)
else:
instance.is_updated = True
instance.modified_by = user
instance.save()
form.save_m2m()
return instance
here is my Notification class in admin.py
class Notifications(object):
def sendNotifications(self, data):
users = models.NewEventNotification.objects.all().filter(is_notify=1)
serializer = NewEventNotificationSerializer(users, many=True)
tokens = []
for user in serializer.data:
tokens.append(user['user_token'])
if tokens:
push_service = FCMNotification(api_key=api_key)
message_title = "New Event"
message_body = data
result = push_service.notify_multiple_devices(
registration_ids=tokens, message_title=message_title, message_body=message_body)
print(result)
this shows the result in browser
TypeError at /admin/events/event/add/
Object of type Event is not JSON serializable
Request Method: POST
Request URL: http://192.168.0.104:8000/admin/events/event/add/
Django Version: 2.1.5
Exception Type: TypeError
Exception Value:
Object of type Event is not JSON serializable
Exception Location: C:\Python\Python37-32\lib\json\encoder.py in default, line 179
Python Executable: C:\Python\Python37-32\python.exe
Python Version: 3.7.4
Python Path:
['D:\\python\\emsbackend',
'C:\\Python\\Python37-32\\python37.zip',
'C:\\Python\\Python37-32\\DLLs',
'C:\\Python\\Python37-32\\lib',
'C:\\Python\\Python37-32',
'C:\\Users\\laptop '
'genration\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Python\\Python37-32\\lib\\site-packages',
'C:\\Python\\Python37-32\\lib\\site-packages\\pip-19.2.3-py3.7.egg']
Server time: Fri, 20 Dec 2019 18:32:51 +0500
and in console
Internal Server Error: /admin/events/event/add/
Traceback (most recent call last):
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 604, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1637, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1525, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1564, in _changeform_view
self.save_model(request, new_object, form, not add)
File "D:\python\emsbackend\events\admin.py", line 296, in save_model
notifiClass.sendNotifications(instance)
File "D:\python\emsbackend\events\admin.py", line 382, in sendNotifications
registration_id=tokens[0], message_title=message_title, message_body=message_body)
File "C:\Python\Python37-32\lib\site-packages\pyfcm\fcm.py", line 113, in notify_single_device
**extra_kwargs
File "C:\Python\Python37-32\lib\site-packages\pyfcm\baseapi.py", line 299, in parse_payload
return self.json_dumps(fcm_payload)
File "C:\Python\Python37-32\lib\site-packages\pyfcm\baseapi.py", line 120, in json_dumps
ensure_ascii=False
File "C:\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Python\Python37-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python37-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Event is not JSON serializable
after searching got this solution. on notification class
# Here is notification class
notifiClass = Notifications()
notifiClass.sendNotifications(instance)
change to this
# make serializer class of that event
serializer = eventSerializer(instance)
notifiClass = Notifications()
notifiClass.sendNotifications(serializer)
I have reviewed many questions/answers for hours and applied many techniques but I couldn't pass the user id to the form init() method, it always gives errors like "init() got an unexpected keyword argument 'request'". Anyone knows the reason?
Form, updated as requested in the comment:
class ChildChoreForm(ModelForm):
class Meta:
model = ChildChore
exclude = ('child',)
fields = '__all__'
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(ChildChoreForm, self).__init__(*args, **kwargs)
self.fields['chore'].queryset = Chore.objects.filter(created_by=self.request.user)
ChildChoreFormSet = inlineformset_factory(Child, ChildChore, form=ChildChoreForm, extra=1)
View:
class ChildChoreUpdate(UpdateView):
model = Child
success_url = reverse_lazy('children-list')
form_class = ChildChoreFormSet
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
if hasattr(self, 'object'):
kwargs.update({'request': self.request})
return kwargs
The Errors I'm getting after opening the updaet web page:
Internal Server Error: /chore/children/23
Traceback (most recent call last):
File "C:\Python\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 190, in get
return super().get(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Python\py_projects\children_chores\chore\views.py", line 202, in get_context_data
data = super(ChildChoreUpdate, self).get_context_data(**kwargs )
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
return form_class(**self.get_form_kwargs())
File "C:\Python\lib\site-packages\django\forms\models.py", line 898, in __init__
super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
File "C:\Python\lib\site-packages\django\forms\models.py", line 569, in __init__
super().__init__(**defaults)
TypeError: __init__() got an unexpected keyword argument 'request'
Internal Server Error: /chore/children/23
Traceback (most recent call last):
File "C:\Python\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 190, in get
return super().get(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Python\py_projects\children_chores\chore\views.py", line 202, in get_context_data
data = super(ChildChoreUpdate, self).get_context_data(**kwargs )
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
return form_class(**self.get_form_kwargs())
File "C:\Python\lib\site-packages\django\forms\models.py", line 898, in __init__
super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
File "C:\Python\lib\site-packages\django\forms\models.py", line 569, in __init__
super().__init__(**defaults)
TypeError: __init__() got an unexpected keyword argument 'request'
The problem is that you have set up your form to accept a request argument in __init__, but you are initialising a formset, not a form. You need to modify the formset to accept that same argument and pass it to the forms in the formset:
# First define a base class that overrides __init__ and get_form_kwargs
from django.forms import BaseFormSet
class BaseChildChoreFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
# Handle the request argument that you are passing on init
self.request = kwargs.pop('request', None)
super().__init__(*args, **kwargs)
def get_form_kwargs(self, index):
kwargs = super().get_form_kwargs(index)
# Add request to the kwargs that are passed to the form on init
kwargs['request'] = self.request
return kwargs
# Now set up your formset using this class
ChildChoreFormSet = inlineformset_factory(
Child, ChildChore, form=ChildChoreForm, formset=BaseChildChoreFormSet, extra=1)
I am getting the following error message when I save the user object. I have searched on the internet for the error message, but I can not find any help. It maybe somthing very obvious that I am missing, but I am not able to find any help available.
Can someone take a look and let me know what the error here is?
File admin.py
from django.contrib.auth.admin import UserAdmin
class UserAdmin(UserAdmin):
list_display = ('username', 'email', 'first_name', 'last_name',
'is_active', roles, login)
list_filter = ('groups',)
def save_model(self, request, obj, form, change):
queryset = MyUser.objects.filter(id=obj.id)
if obj.is_active:
logger.info('User is marked active')
elif not obj.is_active:
logger.info('User is marked inactive')
obj.save()
def add_view(self, *args, **kwargs):
self.inlines = []
return super(UserAdmin, self).add_view(*args, **kwargs)
def change_view(self, request, object_id, form_url='', extra_context=None):
self.inlines = (ProfileInline,)
return super(UserAdmin, self).change_view(request, object_id, form_url, extra_context)
File models.py
class MyUser(User, URLGenerator):
objects = models.Manager() # The default manager.
safe = SafeUserManager()
class Meta:
proxy = True
ordering = ['username']
def __unicode__(self):
return self.get_full_name()
The ERROR I'm getting:
Internal Server Error: /admin/public/myuser/1/change/
Traceback (most recent call last):
File "/dp/app/venv/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 551, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 224, in inner
return view(request, *args, **kwargs)
File "/dp/app/dpapp/public/admin.py", line 364, in change_view
return super(UserAdmin, self).change_view(request, object_id, form_url, extra_context)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1511, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1408, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1440, in _changeform_view
if form.is_valid():
File "/dp/app/venv/local/lib/python2.7/site-packages/django/forms/forms.py", line 183, in is_valid
return self.is_bound and not self.errors
File "/dp/app/venv/local/lib/python2.7/site-packages/django/forms/forms.py", line 175, in errors
self.full_clean()
File "/dp/app/venv/local/lib/python2.7/site-packages/django/forms/forms.py", line 386, in full_clean
self._post_clean()
File "/dp/app/venv/local/lib/python2.7/site-packages/django/forms/models.py", line 413, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "/dp/app/venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 1235, in full_clean
self.clean()
File "/dp/app/venv/local/lib/python2.7/site-packages/django/contrib/auth/models.py", line 349, in clean
self.email = self.__class__.objects.normalize_email(self.email)
AttributeError: 'Manager' object has no attribute 'normalize_email'
Your User object doesn't have the manager method normalize_email. Try changing your user's manager to
objects = BaseUserManager()
which you can import in django.contrib.auth.base_user
I am trying to make some changes in the fields using Djangos build in Admin console.It gives me 'str' object has no attribute 'iter' error exception when i try to change some fields in the models.These fields are Foreign Keys
PROJECT MODEL CAUSES ERROR WHEN I CHANGE THE MANAGER FIELD
class Project(models.Model):
"""Project Model.
"""
name = models.CharField(unique=True, max_length=255)
manager = models.ForeignKey('Employee', blank=True, null=True)
project = models.Manager()
class Employee(models.Model):
"""
Employee Model.
"""
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.CharField(
unique=True,
max_length=255,
blank=True,
null=True)
projects = models.ManyToManyField('Project', blank=True)
employee = models.Manager()
TRACEBACK
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
544. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
211. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in change_view
1512. return self.changeform_view(request, object_id, form_url, extra_context)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in inner
185. return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in changeform_view
1451. change_message = self.construct_change_message(request, form, formsets, add)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in inner
185. return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in construct_change_message
942. elif form.changed_data:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in __get__
35. res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in changed_data
447. if field.has_changed(initial_value, data_value):
File "/usr/local/lib/python2.7/dist-packages/django/forms/fields.py" in has_changed
1075. initial = field.to_python(initial)
File "/usr/local/lib/python2.7/dist-packages/django/forms/fields.py" in to_python
424. return super(DateField, self).to_python(value)
File "/usr/local/lib/python2.7/dist-packages/django/forms/fields.py" in to_python
395. for format in self.input_formats:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in __wrapper__
112. return getattr(res, method_name)(*args, **kw)
Exception Type: AttributeError at /admin/login/project/2/change/
Exception Value: 'str' object has no attribute '__iter__'
admin.py file
from django.contrib import admin
from models import *
admin.site.register(Employee)
admin.site.register(Project)
I've had this problem myself. I upgraded from Django 1.10 to 1.10.2 and that seems to have fixed it for me. Good luck.
I want to redefine class attribute in derived class. The email attribute is already exists in parent class User, but it's have no unique=True property as I need. I know that Django does not support this feature directly. So I did that:
class CustomUser(User):
"""The inherited User class. Email field are redefined to add the warning
about uniqueness is required. UserManager as the default manager so that
the standard methods are available."""
def __init__(self, *args, **kwargs):
super(CustomUser, self).__init__(*args, **kwargs)
email = models.EmailField(unique=True)
email.contribute_to_class(u'email', self)
objects = UserManager()
Traceback:
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/admin/options.py" in wrapper
307. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/admin/sites.py" in inner
196. return self.login(request)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/admin/sites.py" in login
331. return login(request, **defaults)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/auth/views.py" in login
35. if form.is_valid():
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/forms/forms.py" in is_valid
121. return self.is_bound and not bool(self.errors)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/forms/forms.py" in _get_errors
112. self.full_clean()
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/forms/forms.py" in full_clean
268. self._clean_form()
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/forms/forms.py" in _clean_form
296. self.cleaned_data = self.clean()
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/admin/forms.py" in clean
26. self.user_cache = authenticate(username=username, password=password)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/auth/__init__.py" in authenticate
55. user = backend.authenticate(**credentials)
File "/home/i159/workspace/students/backends.py" in authenticate
15. print self.user_class()
File "/home/i159/workspace/students/stdapp/models.py" in __init__
13. email.contribute_to_class(u'email', self)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/db/models/fields/__init__.py" in contribute_to_class
235. self.set_attributes_from_name(name)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/db/models/fields/__init__.py" in set_attributes_from_name
232. self.verbose_name = name.replace('_', ' ')
Exception Type: AttributeError at /admin/stdapp/customuser/add/
Exception Value: 'CustomUser' object has no attribute 'replace'
What can I do to fix it or how to set unique to True in email field? What the cause of this exception?
Edit:
Another way to do this.
First variation:
class CustomUser(User):
def __init__(self, *args, **kwargs):
setattr(self._meta.fields[4], 'unique', True)
Second:
class CustomUser(User):
def __init__(self, *args, **kwargs):
self._meta.fields[4].unique=True
Both are have the same error: can't set attribute.