Django创建新记录而不是更新现有记录

hts6caw3  于 2023-01-14  发布在  Go
关注(0)|答案(2)|浏览(135)

我是Python和Django的新手,尝试创建一个可以创建和更新成员(SQL数据库中的自定义表)的应用程序。创建工作正常,但在更新而不是更新现有成员时,每次我提交时都会创建新记录。抱歉,因为stackoverflow不允许我保存
'VIEW.py单视图类使用?id = idofrecord和& ed = T的URL参数处理,以显示编辑表单'

#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()
        }
oxiaedzo

oxiaedzo1#

如果你想更新示例,那么你必须在初始化表单时传递示例对象,如下所示:

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)

有关表单更新的详细信息,请参阅文档。

7fyelxc5

7fyelxc52#

为了更新Member模型的现有示例,您应该使用form.save(commit=False)方法。
尝试这样做:

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'])

相关问题