Justin
Justin

Reputation: 9

Need help in Django Model save method

Need help for Django model save() method. i need a redirection back to Person list page or to Person form if some conditions false on my model save() method . Currently i used a validation error but i am looking for redirection back to list page or form. And if i use a return statement, always get added successfully without saving. Here i need a redirection instead of "raise ValidationError(u"Enter a valid name").

Thanks in Advance Justin

#Models.py 
from django.db import models
from django.core.exceptions import ValidationError

class Person(models.Model):
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    address = models.TextField(max_length=300, blank=True)

    def save(self, *args, **kwargs):
        if self.first_name == "":   #(Some condition check, not a simple field value )
                raise ValidationError(u"Enter a valid name")
        # Need a redirection back to Django Admin Persons list page or to Add Person Page with error message
        # But always showing added successfully, if i use a return or redirection.
        else:
            super(Person,self).save(*args, **kwargs)

#admin.py

from django.contrib import admin
from testapp.models import Person
from testapp.forms import PersonAdminForm
from django.contrib import messages

# Register your models here.

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name')
    #form = PersonAdminForm

    #def save_model(self, request, obj, form, change):
        #   obj.user = request.user
        #   obj.save()
    #   messages.add_message(request, messages.INFO, 'Text of message')


admin.site.register(Person, PersonAdmin)

#forms.py

from testapp.models import Person
from django import forms

class PersonAdminForm(forms.ModelForm):
    class Meta:
        model = Person

Thanks friends for the reply, I adding my actual model class here. actually i am not using any custom form or custom validation. i used only django admin interface. But i added a custom save() method in model class. And in that save() method i did some conditions on edit and add cases. Addind data and editing data working with save() method correctly. But condition false case we have no option redirect back to admin model class listing or admin form with error message? Here in my example can i use any other code instead of raise ValidationError("error test message")?. raise ValidationError gives django error page. if i use redirect or return give "... added successfully" message on no data saving also.

Any chance?

my code ...

class Asset(models.Model):
    -----code--------

    class Meta:
        verbose_name_plural= "Employees Assets"         

    def save(self, *args, **kwargs):
        ----- code------

    if self.pk is not None:
        ++++++++++ some code +++++++++++

        if self.hardware.hardware_status == 0 and edit_flag == 2:
            ++++++++++ some code +++++++++++
        elif self.hardware.hardware_status == 1 and edit_flag == 1:
            ++++++++++ some code +++++++++++
        elif (self.hardware.hardware_status == 0 or self.hardware.hardware_status == -1) and   edit_flag == 1:
            ++++++++++ some code +++++++++++    
        elif self.hardware.hardware_status == -1 and edit_flag == 2:
            raise ValidationError('Cant modify Hardware, Hardware status is Lost ')
        else:
            raise ValidationError('Cant modify Hardware, Hardware already assigned to other staff') 

        self.hardware.save()
            super(Asset, self).save(*args, **kwargs) 

    else:
        if self.hardware.hardware_status == 0:
            ++++++++++ some code +++++++++++        
        else:
            raise ValidationError(u'Can't assign, Hardware not available(Lost/Alreday Assigned) for assignment')

    self.hardware.save()
    super(Asset, self).save(*args, **kwargs)


    def  __unicode__(self):
        return u'%s Hardware information for %s' % (self.hardware, self.employee)

Upvotes: 0

Views: 1817

Answers (3)

TheEarlyMan
TheEarlyMan

Reputation: 402

The model doesn't do redirection. Which means, overriding your model save method is of little use here. This is a very direct case of form validation, therefore, you must use the below in forms.py

Your view is taking care of the form redirection for you, therefore, just write your code in the form.

Upvotes: 0

slim_chebbi
slim_chebbi

Reputation: 818

try to custom validation in admin:

forms.py:

class PersonAdminForm(forms.Form):
    class Meta:
    model = Person

    def clean_first_name(self):
        if self.first_name == "":value )
            raise ValidationError(u"Enter a valid name")
        else
            return self.clean_first_name["first_name"]

admin.py:

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name')]
    form = PersonAdminForm

check this linkvalidation

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599490

That is completely the wrong place to do it. Models, deliberately, do not know anything about the request. There's no way to redirect from a save method, and you should not try to implement one. Your view is responsible for running validation and redirecting as approrpriate.

Upvotes: 2

Related Questions