ModelForm __init__ problems - python

I've attempted to modify my Django ModelForm __init__ constructor so that it will accept a passed variable ('admin'), look to see if admin == True, and if so, make a couple of fields ('applicant_affirmation' & 'applicant_interest_stmt') display as non-modifiable. The fields are being shown as non-modifiable, as desired, but the .update() function isn't happening because it is not getting past the if form.is_valid check. I've checked for form.non_field_errors and form.errors, but nothing is there. The updates work fine if the __init__ method is commented out.
Any thoughts on what I might be missing? Admittedly I don't have a strong understanding of building a constructor yet. Help would be very much appreciated.
class ApplicationForm(ModelForm):
class Meta:
model = Application
fields = ('program', 'status', 'applicant_affirmation', 'applicant_interest_stmt', 'applicant_school', 'applicant_major', 'applicant_school_2', 'applicant_major_2', 'gpa_univ', 'estimated_grad_semester')
widgets = {
'applicant_interest_stmt': Textarea(attrs={'class': 'form-control', 'rows': 5}),
'estimated_grad_semester': Select(),
}
def __init__(self, admin, *args, **kwargs):
super(ApplicationForm, self).__init__(*args, **kwargs)
if admin:
self.fields['applicant_interest_stmt'].widget.attrs['disabled'] = 'disabled'
self.fields['applicant_affirmation'].widget.attrs['disabled'] = 'disabled'
def clean(self):
from django.core.exceptions import ValidationError
cleaned_data = super(ApplicationForm, self).clean()
applicant_interest_stmt = cleaned_data.get('applicant_interest_stmt')
applicant_affirmation = cleaned_data.get('applicant_affirmation')
if not applicant_interest_stmt:
msg = u'Please provide an interest statement.'
self._errors["applicant_interest_stmt"] = self.error_class([msg])
if not applicant_affirmation:
msg = u'Please check the affirmation checkbox.'
self._errors["applicant_affirmation"] = self.error_class([msg])
return cleaned_data
Application Model:
class Application(models.Model):
id = models.AutoField(primary_key=True)
program = models.ForeignKey(Program, verbose_name="certificate program")
status = models.ForeignKey(Status, verbose_name="application status")
applicant = models.ForeignKey(Person)
applicant_affirmation = models.BooleanField()
applicant_interest_stmt = models.TextField(verbose_name="In a few sentences, briefly explain why you are interested in this program and what you expect to get out of it")
applicant_school = models.CharField(max_length=100, verbose_name="school (primary)")
applicant_major = models.CharField(max_length=100, verbose_name="major (primary)")
applicant_school_2 = models.CharField(blank=True, max_length=100, verbose_name="school (secondary)")
applicant_major_2 = models.CharField(blank=True, max_length=100, verbose_name="major (secondary)")
gpa_univ = models.DecimalField(max_digits=3, decimal_places=2, verbose_name="GPA (university)")
estimated_grad_semester = models.CharField(max_length=5, verbose_name="estimated graduation semester")
_created = models.DateTimeField(editable=False, blank=False)
_created_by = models.CharField(max_length=150)
_updated = models.DateTimeField(editable=False, blank=False)
_updated_by = models.CharField(max_length=150)
def clean(self):
from django.core.exceptions import ValidationError
cleaned_data = super(Application, self).clean()
if not self.applicant_affirmation:
raise ValidationError('Please check the affirmation checkbox.')
if self.applicant_school_2 == '/':
self.applicant_school_2 = ''
if self.applicant_major_2 == '/':
self.applicant_major_2 = ''
def save(self, *args, **kwargs):
""" On save, update both timestamps """
self._created = datetime.datetime.now()
self._updated = datetime.datetime.now()
return super(Application, self).save(*args, **kwargs)
#end save
def update(self, *args, **kwargs):
""" On update, update only _updated timestamps """
self._updated = datetime.datetime.now()
return super(Application, self).save(*args, **kwargs)
#end update
def __unicode__(self):
return unicode(self.id)
#end unicode
class Meta:
db_table = u'certs_application'
#end meta
Snippet from views.py:
if request.POST:
app_form = ApplicationForm(request.POST)
app_form.fields['estimated_grad_semester'].widget.choices = build_semester_list('', 12)
if app_form.is_valid():
print 'form is valid...'
app_instance = get_object_or_404(Application, id=app_id)
fields = {'program': app_form.cleaned_data['program'],
'status': app_form.cleaned_data['status'],
'applicant_id': application.applicant_id,
'applicant_affirmation': app_form.cleaned_data['applicant_affirmation'],
'applicant_interest_stmt': app_form.cleaned_data['applicant_interest_stmt'],
'applicant_school': app_form.cleaned_data['applicant_school'],
'applicant_major': app_form.cleaned_data['applicant_major'],
'applicant_school_2': app_form.cleaned_data['applicant_school_2'],
'applicant_major_2': app_form.cleaned_data['applicant_major_2'],
'gpa_univ': app_form.cleaned_data['gpa_univ'],
'estimated_grad_semester': app_form.cleaned_data['estimated_grad_semester'],
'_created_by': app_instance._created_by,
'_created': app_instance._created,
'_updated_by': user.eid,
}
try:
application = Application(pk=app_id, **fields)
application.update()
except Exception, exception:
return HttpResponse('Error: ' + str(exception))
return redirect('application_view', app_id=app_id)
else:
print 'app_form is NOT valid'
else:
# -------------------------------------------
# render the application using GET
# -------------------------------------------
app_form = ApplicationForm(admin=admin_user, instance=application)
app_form.fields['estimated_grad_semester'].widget.choices = build_semester_list('', 12)
Final modifications made that resulted in the needed fix:
views.py
if request.POST:
app_form = ApplicationForm(admin=admin_user, data=request.POST)
forms.py
def __init__(self, admin, *args, **kwargs):
super(ApplicationForm, self).__init__(*args, **kwargs)
self.admin = admin
if self.admin:
self.fields['applicant_interest_stmt'].widget.attrs['readonly'] = True
self.fields['applicant_affirmation'].widget.attrs['readonly'] = True
def clean(self):
from django.core.exceptions import ValidationError
cleaned_data = super(ApplicationForm, self).clean()
if not self.admin:
applicant_interest_stmt = cleaned_data.get('applicant_interest_stmt')
applicant_affirmation = cleaned_data.get('applicant_affirmation')
if not applicant_interest_stmt:
msg = u'Please provide an interest statement.'
self._errors["applicant_interest_stmt"] = self.error_class([msg])
if not applicant_affirmation:
msg = u'Please check the affirmation checkbox.'
self._errors["applicant_affirmation"] = self.error_class([msg])
return cleaned_data
NOTE: there is still a lingering problem with getting a non-modifiable setting on the applicant_affirmation Boolean field, but I'll fix that separately from this issue.

you might want to make the admin a golobal to the class
class ApplicationForm(ModelForm):
class Meta:
model = Application
fields = ('program', 'status', 'applicant_affirmation', 'applicant_interest_stmt', 'applicant_school', 'applicant_major', 'applicant_school_2', 'applicant_major_2', 'gpa_univ', 'estimated_grad_semester')
widgets = {
'applicant_interest_stmt': Textarea(attrs={'class': 'form-control', 'rows': 5}),
'estimated_grad_semester': Select(),
}
def __init__(self, admin, *args, **kwargs):
super(ApplicationForm, self).__init__(*args, **kwargs)
self.admin = admin
if self.admin:
self.fields['applicant_interest_stmt'].widget.attrs['disabled'] = 'disabled'
self.fields['applicant_affirmation'].widget.attrs['disabled'] = 'disabled'
def clean(self):
from django.core.exceptions import ValidationError
cleaned_data = super(ApplicationForm, self).clean()
if not self.admin:
applicant_interest_stmt = cleaned_data.get('applicant_interest_stmt')
applicant_affirmation = cleaned_data.get('applicant_affirmation')
if not applicant_interest_stmt:
msg = u'Please provide an interest statement.'
self._errors["applicant_interest_stmt"] = self.error_class([msg])
if not applicant_affirmation:
msg = u'Please check the affirmation checkbox.'
self._errors["applicant_affirmation"] = self.error_class([msg])
return cleaned_data

Related

Status: Select a valid choice. 1 is not one of the available choices Django 3

Here i am using Django 3.0 and Python 3.7.
When i am trying to update the user phone number or email id i am getting this issue.
Here is my views.py:
class ClientUserInfoUpdate(CustomAdminMixin, UpdateView):
model = ClientUser
template_name = "core/user_info_mutiple_edit_form.django.html"
form_class = ClientUserInfoUpdateForm
user = None
methods = None
def get_success_url(self):
return reverse("admin_user_update", args=[self.user.pk])
def get_form_kwargs(self):
kwargs = super(ClientUserInfoUpdate, self).get_form_kwargs()
self.user = kwargs['instance']
self.methods = self.user.get_userinfodata()
kwargs['user'] = self.user
kwargs['methods'] = self.methods
return kwargs
def get_context_data(self, **kwargs):
context = super(ClientUserInfoUpdate, self).get_context_data(**kwargs)
context['user'] = self.user
context['methods'] = self.methods
context['countries'] = countries_sorted
for method in ContactInfoMethod.objects.all():
context['types_' + method.name.lower()] = ContactInfoMethodType.objects.types_by(method.name)
return context
Here is my forms.py:
class ClientUserInfoUpdateForm(forms.ModelForm):
user = None
methods = None
# sort of a copy of fieldsets, but utilising the dynamic capabiliities of the form
#formsections = []
new_info = []
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
self.methods = kwargs.pop('methods')
super(ClientUserInfoUpdateForm, self).__init__(*args, **kwargs)
#self.formsections = []
# auto generate the form based upon self.methods (!!!)
for dm in self.methods:
methodtypes = ContactInfoMethodType.objects.types_by(dm['method'].name)
methodtypes_choices = methodtypes.values_list('pk', 'type__name')
if(dm['method'].use_dialling_code):
dialling_code_choices = countries_sorted_with_dial_choices
i = 1
methodname = ""
for info in dm['items']:
fn = info.dynamic_form_field_name()
self.fields[fn] = forms.CharField()
if(dm['method'].name.lower() == "email"):
self.fields[fn] = forms.EmailField()
self.fields[fn].name = fn
self.fields[fn].verbose_name = dm['method'].name
self.fields[fn].label = dm['method'].name + " " + str(i)
self.fields[fn].required = True
self.fields[fn].initial = info.info
self.fields[fn].widget.attrs['class'] = 'span2'
fns = info.dynamic_form_methodtype_select_field_name()
self.fields[fns] = forms.ChoiceField()
self.fields[fns].choices = methodtypes_choices
self.fields[fns].widget.attrs['class'] = 'input-small'
self.fields[fns].initial = info.methodtype.pk
self.fields[fns].required = True
fndc = info.dynamic_form_dialling_code_select_field_name()
if(dm['method'].use_dialling_code):
self.fields[fndc] = forms.ChoiceField()
self.fields[fndc].choices = dialling_code_choices
self.fields[fndc].widget.attrs['class'] = 'span2'
self.fields[fndc].initial = info.dialling_code
self.fields[fndc].required = True
i += 1
#new_fields.append(self.fields[fn])
#self.formsections.append({'legend': dm['method'].name, 'fields': new_fields, 'methodname':dm['method'].name})
def clean(self):
cleaned_data = self.cleaned_data
'''
# e.g.
{
'contactinfo_212695_type_id': u'4',
'contactinfo_249222_type_id': u'1',
'contactinfo_212695': u'paul#padajo.com',
'contactinfo_212694': u'07984 820767',
'contactinfo_249222': u'paul.vidainnovation#gmail.com',
'contactinfo_212693': u'01908 925111',
'contactinfo_212694_type_id': u'8',
'contactinfo_212693_type_id': u'5'
}
'''
# auto generate the form based upon self.methods (!!!)
for dm in self.methods:
for info in dm['items']:
fn = info.dynamic_form_field_name()
fns = info.dynamic_form_methodtype_select_field_name()
if(fn not in self.cleaned_data or fns not in self.cleaned_data):
raise forms.ValidationError("There is some field data missing")
info.info = self.cleaned_data[fn]
info.methodtype_id = self.cleaned_data[fns]
fndc = info.dynamic_form_dialling_code_select_field_name()
if(dm['method'].use_dialling_code):
info.dialling_code = self.cleaned_data[fndc]
# do the save later (!!)
self.new_info.append(info)
del cleaned_data[fn]
del cleaned_data[fns]
if(dm['method'].use_dialling_code):
del cleaned_data[fndc]
return cleaned_data
def save(self, commit=True):
# technically we're not actually working on this object, so just don't commit any changes to it and return
obj = super(ClientUserInfoUpdateForm, self).save(commit=False)
for info in self.new_info:
print("saving info")
print(info)
info.save()
return obj
class Meta:
model = ClientUser
exclude = ['password', 'client', 'email', 'invitation', 'name', 'role',
'last_login', 'minimum_holiday', 'budget_expenses', 'vat']
Here is my reference image of how my edit page looks like
reference image
How can i edit the details of the user like when i am editing the phone number i am getting this issue.

Django - NOT NULL constraint failed

I'm currently working on a Django app that will parse the contents of an uploaded log file to the associated database in my Django project. I've managed to get it all running as expected except it won't associate my uploaded data with the model's ForeignKey. I can assign null=True which resolves the integrity error but then of course, it doesn't assign any of the uploaded data to that ForeignKey. Here's the code:
models.py
class Case(models.Model):
case_ref = models.CharField(max_length=8)
oic = models.CharField(max_length=50)
subject = models.CharField(max_length=100)
submitted_date = models.DateTimeField(default=datetime.now, blank=True)
def get_absolute_url(self):
return reverse('case_list', kwargs={'pk': self.pk})
def __str__(self):
return self.case_ref + " " + self.subject
class TeamviewerLogs(models.Model):
case = models.ForeignKey(Case, on_delete=models.DO_NOTHING)
teamviewer_id = models.IntegerField()
teamviewer_name = models.TextField()
connection_start = models.TextField()
connection_end = models.TextField()
local_user = models.TextField()
connection_type = models.TextField()
unique_id = models.TextField()
def get_absolute_url(self):
return reverse('case_list', kwargs={'pk': self.pk})
def __str__(self):
return str(self.teamviewer_id) + " - " + str(self.teamviewer_id)
forms.py
class UploadLog(forms.ModelForm):
file = forms.FileField()
class Meta:
model = TeamviewerLogs
fields = [
'file'
]
views.py
def add_logs(request, pk):
case = get_object_or_404(Case, pk=pk)
if request.method == 'POST':
form = UploadLog(request.POST, request.FILES)
if form.is_valid():
teamviewer = form.save(commit=False)
teamviewer.case = case
log_file = request.FILES['file']
log_file = filter(None, (line.rstrip() for line in log_file))
for lines in log_file:
split = lines.decode('utf-8').split('\t')
teamviewer_id = split[0]
teamviewer_name = split[1]
connection_start = split[2]
connection_end = split[3]
local_user = split[4]
connection_type = split[5]
unique_id = split[6]
teamviewer = TeamviewerLogs(teamviewer_id=teamviewer_id, teamviewer_name=teamviewer_name,
connection_start=connection_start, connection_end=connection_end,
local_user=local_user, connection_type=connection_type, unique_id=unique_id)
teamviewer.save()
return redirect('tv_log_details', pk=case.pk)
form.save()
else:
form = UploadLog()
return render(request, 'teamviewer/add_logs.html', {'form': form})
But when I click to upload the file I'm hit with:
When it tries to execute teamviewer.save().
I've been trying to resolve this issue for hours and have tried so many different variations of answers from Stackoverflow or previous code I've used that has worked for different models but I've hit a brick wall...hard!
Any help anyone can offer would be greatly appreciated.
Ok, so here's an example of the concept I've suggested in the comments.
I've got a view which passes some data to the a form;
class ListingDetailView(DetailView):
""" Listing detail page """
model = Listing
template_name = 'listing.html'
def get_form_kwargs(self):
"""Return the kwargs for the form"""
kwargs = {}
initial = {
'listing': self.object,
}
kwargs['initial'] = initial
return kwargs
def get_form(self):
form = ApplicationSignupForm(
**self.get_form_kwargs()
)
return form
def get_context_data(self, **kwargs):
""" Add our form to the context """
context = super().get_context_data(**kwargs)
context['form'] = self.get_form()
return context
The form then makes use of that initial data and sets the field it relates to as hidden. I don't validate this data, but I'll try to show how you might do that;
class ApplicationSignupForm(forms.ModelForm):
class Meta:
""" Setup the form """
fields = (
'listing',
...
)
model = Application
widgets = {
'listing': forms.HiddenInput()
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
initial_data = kwargs['initial']
self.listing = initial_data.get('listing')
def clean(self):
"""
Custom form cleaning
"""
cleaned_data = super().clean()
listing = cleaned_data.get('listing')
if listing != self.listing:
self.add_error('listing', "You can't modify this value")
return cleaned_data

reloading django admin inline form updating data from the back end

I have a ModelForm for a parent model and and an InlineForm for a foreign key related model. The Inline form data is read only and can only be updated via a file upload. I have this working on the intial creation and save, but if you replace the students by uploading a new file, while the data updates properly after the upload and save, the inline form doesn't reload properly right after this save and displays an error. However, if you navigate away and return everything looks good.
Models.py
class Room(models.Model):
room_id = models.AutoField(primary_key=True)
name = models.TextField(blank=False, verbose_name = "Room Name ")
code = models.TextField(blank=False)
file = models.TextField(blank=False)
class Meta(object):
managed = False
db_table = 'public\".\"room'
class Student(models.Model):
room = models.ForeignKey(Room, related_name="students, to_field="room_id", db_column="room_id")
student_id = models.TextField(blank=False, primary_key=False)
#property
def grade(self):
return util.get_grade(self.student_id)
class Meta(object):
managed = False
db_table = 'public\".\"student’
admin.py
class StudentsInline(admin.TabularInline):
model = Student
form = StudentInlineForm
formset = StudentFormSet
readonly_fields = ('student_id', 'grade')
extra = 0
def get_actions(self, request):
'''
Removes the delete action
'''
actions = super(StudentsInline, self).get_actions(request)
del actions['delete_selected']
return actions
def has_delete_permission(self, request, obj=None):
return False
def has_add_permission(self, request, obj=None):
return False
class RoomAdmin(admin.ModelAdmin):
def student_count(self, obj):
return obj.students.count()
student_count.short_description = " Total Enrolled "
form = RoomForm
list_display = [name', ‘code']
readonly_fields = ['student_count']
list_per_page = 25
inlines = [StudentsInline]
def get_actions(self, request):
actions = super(RoomAdmin, self).get_actions(request)
del actions['delete_selected']
return actions
def has_delete_permission(self, request, obj=None):
return False
def save_formset(self, request, form, formset, change):
form.instance.file = 'processed file'
form.instance.save
formset.save()
forms_admin.py
class RoomsForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RoomsForm, self).__init__(*args, **kwargs)
self.fields[‘name'].required = True
self.fields[‘code'].required = True
self.fields['file'] = forms.FileField(
label='Upload your enrollees:'
def load_file(self, upload_file):
student_list = []
data = upload_file.read() #simplified for this example
for s in reader:
s_id = s[0]
new_student = Student(student_id=s_id)
student_list.append(new_student)
return student_list
def save(self, *args, **kwargs):
room_form = super(RoomsForm, self).save(commit=False)
enrollee_list = self.load_file(self.instance.file.file)
if instance.room_id is None:
instance.file = 'uploaded'
instance = super(RoomsForm, self).save(commit=True)
Student.objects.filter(room_id=self.instance.room_id).all().delete()
instance.students.add(*enrollee_list)
return instance
class Meta:
model = Room
fields = '__all__'
class StudentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(StudentForm, self).__init__(*args, **kwargs)

UserCreationForm show error when fields are empty

I'm using Django built in UserCreationForm. I want to show message under the field when that field is empty and user tring to submit form. Unfortunatly I see only built-in behavior of browsers like "fill out this field", by the way in different browsers that behavior is different. Some browsers just encircle the field box with a red line. How to turn off this behavior and show message under the field. Why .error_messages didnt work?! Also I use {{ form.field_name.errors }} in my template.
forms.py
class RegistrationForm(UserCreationForm):
required_css_class = 'required'
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name')
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['username'].widget = TextInput(attrs={'placeholder': _('Username')})
self.fields['username'].required = True
self.fields['username'].error_messages = {'required': 'Please enter your username'}
self.fields['email'].widget = EmailInput(attrs={'placeholder': _('Email address')})
self.fields['email'].required = True
self.fields['email'].error_messages = {'required': 'Please enter your email'}
self.fields['first_name'].widget = TextInput(attrs={'placeholder': _('First name')})
self.fields['first_name'].required = True
self.fields['first_name'].error_messages = {'required': 'Please enter your first_name'}
self.fields['last_name'].widget = TextInput(attrs={'placeholder': _('Last name')})
self.fields['last_name'].required = True
self.fields['last_name'].error_messages = {'required': 'Please enter your last_name'}
self.fields['password1'].widget = PasswordInput(attrs={'placeholder': _('Password')})
self.fields['password1'].required = True
self.fields['password1'].error_messages = {'required': 'Please enter your Password'}
self.fields['password2'].widget = PasswordInput(attrs={'placeholder': _('Confirm password')})
self.fields['password2'].required = True
self.fields['password2'].error_messages = {'required': 'Please enter your Confirm Password'}
view.py
class RegistrationView(FormView):
disallowed_url = 'registration_closed'
form_class = RegistrationForm
http_method_names = ['get', 'post', 'head', 'options', 'trace']
success_url = 'registration_complete'
template_name = 'account/registration_form.html'
SEND_ACTIVATION_EMAIL = getattr(settings, 'SEND_ACTIVATION_EMAIL', True)
registration_profile = RegistrationProfile
#method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
if not self.registration_allowed():
return redirect(self.disallowed_url)
return super(RegistrationView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
new_user = self.register(form)
success_url = self.get_success_url(new_user)
try:
to, args, kwargs = success_url
except ValueError:
return redirect(success_url)
else:
return redirect(to, *args, **kwargs)
def registration_allowed(self):
return getattr(settings, 'REGISTRATION_OPEN', True)
def register(self, form):
site = get_current_site(self.request)
if hasattr(form, 'save'):
new_user_instance = form.save()
else:
new_user_instance = (UserModel().objects.create_user(**form.cleaned_data))
new_user = self.registration_profile.objects.create_inactive_user(
new_user=new_user_instance,
site=site,
send_email=self.SEND_ACTIVATION_EMAIL,
request=self.request,
)
signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request)
return new_user
def get_success_url(self, user=None):
return super(RegistrationView, self).get_success_url()
You need to turn off the behaviour in the HTML itself, by using novalidate in the form element.
<form action="whatever" method="POST" novalidate>
...
</form>

Model form is crashing on a foreign key in django

So I'm trying to create a new feed within the Admin page and its
crashing with the error IntegrityError: lifestream_feed.lifestream_id
may not be NULL, form['lifestream'] is set but
form.instance.lifestream is not.
form.fields even shows that lifestream is a django.forms.models.ModelChoiceField
Here is the code:
class FeedCreationForm(forms.ModelForm):
class Meta:
model = Feed
exclude = ['name', 'domain', 'fetchable']
def parse_feed(self, feed_url):
feed = feedparser.parse(feed_url)
# Does the feed have errors
if feed['bozo']:
if feed['feed'].has_key("links"):
for link in feed['feed']['links']:
if link["type"] == "application/rss+xml":
feed = self.parse_feed(link['href'])
if not feed['bozo']:
return feed
else:
return feed
return None
def clean(self):
"""
Checks to make sure a feed url is valid and gets the feed
title
and domain.
"""
feed_url = self.cleaned_data.get('url')
if not feed_url:
# Feed url was not validated by the field validator
return
feed = self.parse_feed(feed_url)
if feed:
feed_url = feed['url']
self.cleaned_data['url'] = feed_url
else:
# the feed was not parsed correctly.
import logging
self._errors['url'] = ErrorList(["This is not a valid
feed: %s" % feed['bozo_exception']])
logging.error(feed['bozo_exception'])
# This field is no longer valid. Remove from cleaned_data
del self.cleaned_data['url']
return
# Check if the feed has a title field
feed_info = feed.get('feed')
if not feed_info.get('title'):
self._errors['url'] = ErrorList(["This is not a valid
feed: The feed is empty"])
# This field is no longer valid. Remove from cleaned_data
del self.cleaned_data['url']
return
self.cleaned_data['name'] = feed_info['title']
self.instance.name = self.cleaned_data['name']
self.cleaned_data['domain'] = get_url_domain(feed_url)
self.instance.domain = self.cleaned_data['domain']
return self.cleaned_data
class FeedAdmin(admin.ModelAdmin):
list_display = ('name', 'lifestream', 'domain', 'fetchable')
list_filter = ('domain', 'lifestream')
actions = ['make_fetchable', 'make_unfetchable']
add_form = FeedCreationForm
model = Feed
def make_unfetchable(self, request, queryset):
queryset.update(fetchable=False)
make_unfetchable.short_description = _(u"Mark as unfetchable")
def make_fetchable(self, request, queryset):
queryset.update(fetchable=True)
make_fetchable.short_description = _(u"Mark as fetchable")
def add_view(self, request):
if not self.has_change_permission(request):
raise PermissionDenied
if request.method == 'POST':
form = self.add_form(request.POST)
if form.is_valid():
new_feed = form.save()
msg = _('The %(name)s "%(obj)s" was added
successfully.') % {'name': 'user', 'obj': new_feed}
self.log_addition(request, new_feed)
if "_addanother" in request.POST:
request.user.message_set.create(message=msg)
return HttpResponseRedirect(request.path)
elif '_popup' in request.REQUEST:
return self.response_add(request, new_feed)
else:
request.user.message_set.create(message=msg + ' '
+ ugettext("You may edit it again below."))
# TODO: use reversed url
return HttpResponseRedirect('../%s/' %
new_feed.id)
else:
form = self.add_form()
return render_to_response('admin/lifestream/feed/
add_form.html', {
'title': _('Add feed'),
'form': form,
'is_popup': '_popup' in request.REQUEST,
'add': True,
'change': False,
'has_add_permission': True,
'has_delete_permission': False,
'has_change_permission': True,
'has_file_field': False,
'has_absolute_url': False,
'auto_populated_fields': (),
'opts': self.model._meta,
'save_as': False,
#'username_help_text': self.model._meta.get_field
('username').help_text,
'root_path': self.admin_site.root_path,
'app_label': self.model._meta.app_label,
}, context_instance=template.RequestContext(request))
def queryset(self, request):
return self.model.objects.feeds()
admin.site.register(Feed, FeedAdmin)
class Lifestream(models.Model):
"""
A lifestream. Lifestreams can be created per user.
"""
site = models.ForeignKey(Site, verbose_name=_(u"site"))
user = models.ForeignKey(User, verbose_name=_(u"user"))
slug = models.SlugField(_("slug"), help_text=_('Slug for use in
urls (Autopopulated from the title).'), blank=True)
title = models.CharField(_("title"), max_length=255)
def __unicode__(self):
return self.title
class FeedManager(models.Manager):
''' Query only normal feeds. '''
def feeds(self):
return super(FeedManager, self).get_query_set()
def fetchable(self):
return self.feeds().filter(fetchable=True)
class Feed(models.Model):
'''A feed for gathering data.'''
lifestream = models.ForeignKey(Lifestream, verbose_name=_
('lifestream'))
name = models.CharField(_("feed name"), max_length=255)
url = models.URLField(_("feed url"), help_text=_("Must be a valid
url."), verify_exists=True, max_length=1000)
domain = models.CharField(_("feed domain"), max_length=255)
fetchable = models.BooleanField(_("fetchable"), default=True)
# The feed plugin name used to process the incoming feed data.
plugin_class_name = models.CharField(_("plugin name"),
max_length=255, null=True, blank=True, choices=getattr(settings,
"PLUGINS", PLUGINS))
objects = FeedManager()
def __unicode__(self):
return self.name
Its not returning the empty returns, its reaching the return self.cleaned_data:
-> return self.cleaned_data
(Pdb) list
85 self.cleaned_data['name'] = feed_info['title']
86 self.instance.name = self.cleaned_data['name']
87 self.cleaned_data['domain'] = get_url_domain(feed_url)
88 self.instance.domain = self.cleaned_data['domain']
89
90 -> return self.cleaned_data
91
92 class FeedAdmin(admin.ModelAdmin):
93 list_display = ('name', 'lifestream', 'domain', 'fetchable')
94 list_filter = ('domain', 'lifestream')
95 actions = ['make_fetchable', 'make_unfetchable']
(Pdb) self.cleaned_data
{'url': u'http://twitter.com/statuses/user_timeline/6166742.rss', 'domain': u'twitter.com', 'lifestream': <Lifestream: Social>, 'name': u'Twitter / sontek', 'plugin_class_name': u'lifestream.plugins.twitter.TwitterPlugin'}
I believe the problem is in your clean() method.
The general clean() method (as opposed to field specific clean methods like clean_domain()) must return the cleaned_data dictionary (minus any fields which do not validate), and you have at least 3 returns in your clean method that do not return anything.
See here
Turns out this is a bug in HEAD of django

Categories