saving inlineformset_factory data - django

#render_to('edit_operation.html')
def edit_operation(request, pk):
from forms import OpBaseForm, OperationForm
from django.forms.models import inlineformset_factory
op = Operation.objects.get(pk=pk)
OpBaseFormSet = inlineformset_factory(Operation, OpBase, form=OpBaseForm, extra=5, )
if request.method == "POST":
form = OperationForm(request.POST, instance=op)
formset = OpBaseFormSet(request.POST, instance=op)
if formset.is_valid() and form.is_valid():
form.save()
formset.save() #error here
return HttpResponseRedirect( op.get_absolute_url() )
else:
form = OperationForm(instance=op)
formset = OpBaseFormSet(instance=op)
return {'operation': op, 'opform': form, 'formset': formset}
This seems pretty straightforward, but whenever I try to submit data (even unchanged data), I get this error:
Environment:
Request Method: POST
Request URL: http://localhost:8000/edit/operation/1/
Django Version: 1.0.2 final
Python Version: 2.6.2
Installed Applications:
['main',
'django_extensions',
'django.contrib.comments',
'django.contrib.admindocs',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.gis',
'django.contrib.humanize',
'registration']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "/usr/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/dist-packages/annoying/decorators.py" in wrapper
55. output = function(request, *args, **kwargs)
File "/home/chris/Websites/jobmap/main/views.py" in edit_operation
68. formset.save()
File "/usr/lib/python2.6/dist-packages/django/forms/models.py" in save
389. return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "/usr/lib/python2.6/dist-packages/django/forms/models.py" in save_existing_objects
403. obj = existing_objects[form.cleaned_data[self._pk_field.name]]
Exception Type: KeyError at /edit/operation/1/
Exception Value: None
Anyone have any idea what is causing this error? If theres an error in the formset, then what is formset.is_valid() doing being 'True'? Anyone at least have any ideas on how to debug this in order to find whats going wrong? Both forms work perfectly fine when used individually, and I have {{formset.management_form}} in my template.

Just a quick guess... is your OpBaseForm excluding the model pk? Or, are you missing the pk field in your template? In other words, if you are laying out the fields yourself you still need to include the pk field even though it's hidden.

Related

django - TypeError at /admin/login/ has_module_perms() takes 2 positional arguments but 3 were given

I get an error when I login http://127.0.0.1:8000/admin.
I don't know where the error occurred.
This is the error message:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/
Django Version: 2.0.5
Python Version: 3.6.2
Installed Applications:
['users',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in login
382. self.each_context(request),
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in each_context
302. 'available_apps': self.get_app_list(request),
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in get_app_list
470. app_dict = self._build_app_dict(request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in _build_app_dict
418. has_module_perms = model_admin.has_module_permission(request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/options.py" in has_module_permission
506. return request.user.has_module_perms(self.opts.app_label)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/auth/models.py" in has_module_perms
422. return _user_has_module_perms(self, module)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/auth/models.py" in _user_has_module_perms
196. if backend.has_module_perms(user, app_label):
Exception Type: TypeError at /admin/login/
Exception Value: has_module_perms() takes 2 positional arguments but 3 were given
users/views.py:
from django.shortcuts import render, redirect
from .forms import RegisterForm
# Create your views here.
def index(request):
return render(request, 'index.html')
def register(request):
redirect_to = request.POST.get('next', request.GET.get('next', ''))
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
if redirect_to:
return redirect(redirect_to)
else:
return redirect('/')
else:
form = RegisterForm()
return render(request, 'users/register.html', context={'form': form, 'next': redirect_to})
this is a user login registration authentication code, and only have user app.
in the traceback seem the error didn't occured in my code, so i don't know where it is wrong.
user/models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
email = models.EmailField(verbose_name='email',
unique=True, error_messages={'unique': 'Email is already occupied'})
class Meta(AbstractUser.Meta):
pass
If use an AbstractBaseUser add arguments, or try overwriting the function, can use this:
def has_module_perms(self, *args): # or add
# ....
return True

regex email validation django

Working on a project for school I know how to do this in flask but learning django. I am trying to make sure that a valid email is entered before it post. If I do not do the if else statement the form goes though but wont validate it. I have the following and the only part not working is the one part with comments but I included the whole views.py incase you see something at top that could be wrong.
views.py
from django.shortcuts import render, redirect
from .models import User
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
# Create your views here.
def index(request):
return render(request, "emailvalidation/index.html" )
def create(request):
if request.method == 'POST': #here down
if len(request.form['email']) < 1:
add_message("Invalid Email Address!") #if i take out the if else the form does work
elif not EMAIL_REGEX.match(request.form['email']): #the validation.
add_message("Invalid Email Address!")
else:
User.objects.create(email = request.POST['email'] ) #to here
context ={
"email": User.objects.all(),
}
return render(request, 'emailvalidation/success.html' ,context)
the traceback error
Environment:
Request Method: POST
Request URL: http://localhost:8000/user
Django Version: 1.10.6
Python Version: 2.7.10
Installed Applications:
['apps.emailvalidation',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\exception.py" in inner
42. response = get_response(request)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\django2\emailval\emailval\apps\emailvalidation\views.py" in create
15. if len(request.form['email']) < 1:
Exception Type: AttributeError at /user
Exception Value: 'WSGIRequest' object has no attribute 'form'
request does not have a form attribute. Since you already have if request.method == "POST" - you can safely do the following:
change
request.form['email']
with
request.POST['email']
Ideally, you should be using django forms for handing the validations etc. Django forms have better validation logic, regex validators, etc..

'str' object is not callable - SuccessMessageMixin

I get this error in a project whith SuccessMessageMixin and and not know why. This is my code in view.py.
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import CreateView
class CampanaNueva(SuccessMessageMixin, CreateView):
model = Campana
template_name = "licencias_campana_nueva.html"
fields = ['temporada', 'descripcion']
success_message = "a"
And Raise this error on save:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/licencias/editar/1
Django Version: 1.9.4
Python Version: 3.4.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'home',
'widget_tweaks',
'socios',
'equipaciones',
'licencias']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'cc_corbelo.middleware.LoginRequiredMiddleware']
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\edit.py" in post
279. return super(BaseUpdateView, self).post(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\edit.py" in post
222. return self.form_valid(form)
File "C:\Python34\lib\site-packages\django\contrib\messages\views.py" in form_valid
14. messages.success(self.request, success_message)
Exception Type: TypeError at /licencias/editar/1
Exception Value: 'str' object is not callable
I have this function working in another project without problems...
I got exactly this same message when I accidentally used the messages framework incorrectly in the form_valid method of a completely different view in my project.
The correct code should have been:
messages.success(request, "Deactivated product")
But what I had written instead was
messages.success = "Deactivated product"
This code doesn't work, but it doesn't cause an error on the page, either! However, as soon as I submitted a different form that used the SuccessMessageMixin, I would see the 'str' object is not callable error.
(Having a problem on one page cause an error on a completely different page was fun to debug.)

'str' object has no attribute 'get' (Django)

Ahoy Mateys!
got a simple model with a simpel form here:
class Hardware(models.Model):
type_name = models.CharField(max_length=60)
def __unicode__(self):
return self.type_name
class HardwareForm(ModelForm):
class Meta:
model = Hardware
fields = ['type_name']
and this is used by my simple views function:
def createHardware(request):
if request.method == 'POST':
form = HardwareForm('request.POST')
if form.is_valid():
new_hardware = form.save()
return render_to_response('administration/overview.html')
else:
form = HardwareForm()
return render_to_response('administration/create_hardware.html', {
'form': form, }, context_instance = RequestContext(request))
this is the Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/ticket/createHardware/
Django Version: 1.6.6
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ticket')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\bachi_000\workspace\Help\src\ticket\views.py" in createHardware
155. if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
129. return self.is_bound and not bool(self.errors)
File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
121. self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
273. self._clean_fields()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
282. value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Python27\lib\site-packages\django\forms\widgets.py" in value_from_datadict
207. return data.get(name, None)
Exception Type: AttributeError at /ticket/createHardware/
Exception Value: 'str' object has no attribute 'get'
so i got several forms with much more data in it, and there is no problem to pass an empty form to the html page, fill it out and POST them back to the function to get the data in the form. run is_valid() and pass the data to a new instance of the model (to add some more data to it)
why do i get here this error?
You need to be passing in a dictionary to your HardwareForm, not a string.
Change in your views.py
form = HardwareForm('request.POST')
to:
form = HardwareForm(request.POST)

Django: dynamic success_url results in "'NoneType' object has no attribute 'find'"

I would like to redirect the success_url to the same form after the form was submitted and valid. Online I found a description of a solution, however this solution and my other code option generate the same error message.
Exception Value: 'NoneType' object has no attribute 'find'
urls.py
url(r'^pictures/(?P<id>\d+)/$', PictureUpload.as_view(), name='picture_upload'),
...
1st views.py option
copies the existing link path
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = lambda self: self.request.path
2nd views.py option
recreates the link path based on the reverse url plus the id
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = reverse('picture_upload',
kwargs={'id': self.kwargs.get('id', None)})
Both options end up in the same traceback.
Request Method: POST
Request URL: http://127.0.0.1:8000/pictures/2/
Django Version: 1.5.1
Python Version: 2.7.1
Installed Applications:
('django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'picture',
'debug_toolbar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in post
165. return self.form_valid(form)
File "/Users/Development/project/apps/picture/picture_views.py" in form_valid
180. return super(PictureUpload, self).form_valid(form)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in form_valid
65. return HttpResponseRedirect(self.get_success_url())
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/http/response.py" in __init__
388. parsed = urlparse(redirect_to)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlparse
134. tuple = urlsplit(url, scheme, allow_fragments)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlsplit
173. i = url.find(':')
Exception Type: AttributeError at /pictures/2/
Exception Value: 'NoneType' object has no attribute 'find'
It looks like neither of your get_success_url implementations actually return the URL, so assuming that's not just a cut-and-paste error you're passing None to the HttpResponseRedirect.