Home > Net >  Django creates new record instead of updating existing record
Django creates new record instead of updating existing record

Time:01-13

I am new to Python and Django, trying to create an app that can create and update the Member (custom table in SQL Database). Create works fine but on update instead of updating the existing member it is creating new record every time I submit. Sorry because stackoverflow was not allowing me save

'VIEW.py single view class handled with URL parameter with ?id=idofrecord and &ed=T to show the Edit form'

#LISTS VIEWS
class NewMember(LoginRequiredMixin,TemplateView):

def get(self, request, \*args, \*\*kwargs):
    memberId = request.GET.get('id')
    isEdit = request.GET.get('ed')
    print('NEW MEMBER VIEW TRIGGERED')
    print(memberId)
    print(isEdit)
    if isEdit == 'T':
        memberObject = Member.objects.get(id=memberId)
        form = MemberForm(instance=memberObject)  
        print("EDIT TRIGGERED")
        return render(request, 'components/list/list-new-member.html', {'form':form, 'memberid':memberId})
     elif memberId:
        form = MemberForm()
        context = Member.objects.get(id=memberId)
        print('VEIW MEMBER TRIGERRED')
        return render(request, 'components/list/list-view-member.html', {'context':context,'form':form})
    else:
        #CREATE NEW MEMBER
        form = MemberForm()
        context = {'form':form}
        return render(request, 'components/list/list-new-member.html', context)

def post(self, request, \*args, \*\*kwargs):
    print('REST POST PRINTED')
    form = MemberForm(request.POST, request.FILES)
    if form.is_valid():
        retObj = form.save()
        print('RECORD UPDATED')
        return redirect('/app/list/member?id=' str(retObj.id))

else:
    print(request.POST)
    print(form.errors)
    print('REST PRINTING POST :form.is_valid() '  str(form.is_valid()))
    if form.is_valid():

        retObj = form.save()
        print(retObj.id)
        return redirect('/app/list/member?id=' str(retObj.id))

context = {'form':form}
return render(request, 'components/list/list-new-member.html', context)
It should update the existing record as form object has passed with Instance and Post object

Model.py

#MEMBER MODEL
class Member(models.Model):
    TYPE = (
        (1, 'Associate'),
        (2, 'Supervisor'),
        (3, 'Region Head'),
        (4, 'Country Head')
    )

    GENDER = (
        (1, 'Female'),
        (2, 'Male'),
        (3, 'Other')
    )

    QUALIFICATION = (
        (1, 'Under Graduate'),
        (2, 'Graduate'),
        (3, 'Masters'),
        (4, 'PhD')
    )

    MEMBERSTATUS = (
        (1, 'Lead'),
        (2, 'Pending Approval'),
        (3, 'Active'),
        (4, 'Rejected'),
        (5, 'Terminated')
    )

    firstname = models.CharField(max_length = 120)
    middlename = models.CharField(max_length = 50, null=True)
    lastname = models.CharField(max_length = 100)
    registrationuniquekey = models.CharField(max_length = 30, null=True)
    
    profession = models.CharField(max_length = 100, null=True)    
    birthdate = models.DateField(auto_now=False, auto_now_add=False, null=True)
    gender = models.IntegerField(choices=GENDER, null=True)

    aadhaar = models.CharField(max_length = 12, null=True)
    aadhaarfile = models.ImageField(upload_to='memberfile/' , null=True, blank=True)
    profilephoto = models.ImageField(upload_to='memberfile/' , null=True, blank=True)

    memberid = models.CharField(max_length=30, null=True)
    memberstatus = models.IntegerField(choices=MEMBERSTATUS, null=True)
    registrationlink = models.CharField(max_length = 200, null=True)
    
    email = models.EmailField(max_length = 100)
    phone = models.CharField(max_length = 12, null=True)
    country = models.ForeignKey(Country, null=True, on_delete=models.SET_NULL)

    address = models.TextField(max_length = 999 , null=True)

    qualification = models.IntegerField(choices=QUALIFICATION, null=True)
    hobbies = models.CharField(max_length = 100, null=True)
    extraactivities = models.CharField(max_length = 200, null=True)

    lifegoals = models.TextField(max_length = 400, null=True)
    whywe = models.TextField(max_length = 400, null=True)
    notes = models.TextField(max_length = 400, null=True)

    referredby = models.CharField(max_length = 100,default=1)
    requestedby = models.ForeignKey(User, on_delete=models.CASCADE, default=2)
    type = models.IntegerField(choices=TYPE, null=True)
    
    approvedbystate = models.CharField(max_length = 100, null=True)
    approvedbypresident = models.CharField(max_length = 100, null=True)
    datecreated = models.DateTimeField(auto_now_add=True)
    iagree = models.BooleanField(null=True)

    def save(self, *args, **kwargs):
        if not self.registrationlink:
            self.registrationlink = None
        super(Member, self).save(*args, **kwargs)

    def __str__(self):
        return self.firstname

FORM.py

class MemberForm(forms.ModelForm):
    class Meta:
        model = Member
        fields = (
        'firstname', 
        'middlename', 
        'lastname', 
        'profession', 
        'gender',
        'aadhaar',
        'aadhaarfile',
        'profilephoto',
        'birthdate',
        'email',
        'phone',
        'country',
        'address',
        'qualification',
        'hobbies',
        'extraactivities',
        'lifegoals',
        'whywe',
        'referredby',
        'type',
        'approvedbystate',
        'approvedbypresident',
        'iagree',
        'requestedby')

        widgets = {
        'firstname':    forms.TextInput(attrs={'class':'form-control'}),
        'middlename':   forms.TextInput(attrs={'class':'form-control'}), 
        'lastname':     forms.TextInput(attrs={'class':'form-control'}),
        'profession':   forms.TextInput(attrs={'class':'form-control'}),
        'birthdate':    forms.DateInput(attrs={'class':'form-control', 'type':'date'}),
        'gender':       forms.Select(attrs={'class':'form-control'}),
        'aadhaar':      forms.NumberInput(attrs={'class':'form-control'}), 
        'aadhaarfile':  forms.FileInput(attrs={'class':'form-control'}), 
        'profilephoto': forms.FileInput(attrs={'class':'form-control'}), 
        'email':        forms.EmailInput(attrs={'class':'form-control'}),
        'phone':        forms.NumberInput(attrs={'class':'form-control', 'type':'tel'}),
        'country':      forms.Select(attrs={'class':'form-control'}),
        'address':      forms.Textarea(attrs={'class':'form-control'}),
        'qualification':forms.Select(attrs={'class':'form-control'}),   
        'hobbies':      forms.TextInput(attrs={'class':'form-control'}),
        'extraactivities': forms.TextInput(attrs={'class':'form-control'}),
        'lifegoals':    forms.Textarea(attrs={'class':'form-control'}),
        'whywe':        forms.Textarea(attrs={'class':'form-control'}),
        'referredby':   forms.TextInput(attrs={'class':'form-control'}),
        'type':         forms.Select(attrs={'class':'form-control'}),
        'approvedbystate':forms.TextInput(attrs={'class':'form-control'}),
        'approvedbypresident':forms.TextInput(attrs={'class':'form-control'}),
        'requestedby':  forms.Select(attrs={'class':'form-control'}),
        'iagree':forms.CheckboxInput()
        }

CodePudding user response:

If you want to update the instance, then you have pass the instance object when initiating the form. Like this:

def post(self, request, *args, **kwargs):
    member_id = request.GET.get('id')  # preferable if you use url arguments instead of search query
    is_edit = request.GET.get('ed')
    if is_edit == 'T':
        member_object = Member.objects.get(id=member_id)
        form = MemberForm(request.POST, request.FILES, instance=member_object) 

More information on form update can be found in documentation.

CodePudding user response:

In order to update an existing instance of the Member model, you should use the form.save(commit=False) method.

Try doing this way:

if form.is_valid():
member = Member.objects.get(id=memberId)
member.firstname = form.cleaned_data['firstname']
member.save()


Member.objects.filter(id=memberId).update(firstname = form.cleaned_data['firstname'])
  • Related