При обновлении/редактировании данные дублируются, а не обновляются в django

Данные дублируются вместо того, чтобы обновляться в django, пожалуйста, помогите мне преодолеть это. Я также пробовал метод update, но столкнулся с проблемой, что изображение не отображается, поэтому я использовал метод save, который сохраняет и делает копию объекта anthor, что мне не нужно. он должен обновлять тот же самый объект.

views.py

def EuAdmin(request, pk):
        pi = EmailDb.objects.get(id=pk)
        if request.method == 'POST':
            institution = request.POST.get('institution', '')
            fullname = request.POST.get('fullname', '')
            email = request.POST.get('email', '')
            contact = request.POST.get('contact', '')
            position = request.POST.get('position', '')
            uploadd = request.FILES.get('upload', '')
            sdata = EmailDb(institution=institution, fullname=fullname, contact=contact, email=email, position=position, uploaddata=uploadd)
            sdata.save()
            return HttpResponseRedirect("/eadmin")
        return render(request, 'NEC/eupdate.html', {'pi': pi})

models.py

class EmailDb(models.Model):
    institution = models.CharField(max_length=300, blank=True, null=True)
    fullname = models.CharField(max_length=50, blank=True, null=True)
    contact = models.IntegerField()
    email = models.CharField(max_length=300, blank=True, null=True)
    position = models.CharField(max_length=100, blank=True, null=True)
    uploaddata = models.FileField(upload_to='appointment_letter')

    def __str__(self):
        return self.fullname

Это потому, что вы создаете новый EmailDb объект. Вы можете редактировать его с помощью:

from django.shortcuts import get_object_or_404


def EuAdmin(request, pk):
    pi = get_object_or_404(EmailDb, pk=pk)
    if request.method == 'POST':
        institution = request.POST.get('institution', '')
        fullname = request.POST.get('fullname', '')
        email = request.POST.get('email', '')
        contact = request.POST.get('contact', '')
        position = request.POST.get('position', '')
        uploaded = request.FILES.get('upload', '')
        pi.institution = institution
        pi.fullname = fullname
        pi.contact = contact
        pi.email = email
        pi.position = position
        pi.uploaddata = uploaded
        pi.save()
        return HttpResponseRedirect('/eadmin')
    return render(request, 'NEC/eupdate.html', {'pi': pi})

Note: It is better to use a Form [Django-doc] than to perform manual validation and cleaning of the data. A Form will not only simplify rendering a form in HTML, but it also makes it more convenient to validate the input, and clean the data to a more convenient type.


Примечание: Модели обычно не имеют суффикса Db. Модель - это не таблица, она хранится в реляционной базе данных как таблица, но даже тогда она имеет дополнительную логику, такую как валидаторы, менеджеры и т.д.

.

Note: Please use an EmailField [Django-doc] instead of a CharField [Django-doc] to store an email address, this can do validation to check if the entered data is indeed an email address.


Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.

sdata = EmailDb(institution=institution, fullname=fullname, contact=contact, email=email, position=position, uploaddata=uploadd)
sdata.save()

Выполняется оператор INSERT SQL.

Поскольку у вас уже есть объект, просто установите значение и вызовите save() как

def EuAdmin(request, pk):
    pi = EmailDb.objects.get(id=pk)
    if request.method == 'POST':
        institution = request.POST.get('institution', '')
        fullname = request.POST.get('fullname', '')
        email = request.POST.get('email', '')
        contact = request.POST.get('contact', '')
        position = request.POST.get('position', '')
        uploaded = request.FILES.get('upload', '')
        pi.institution = institution
        pi.fullname = fullname
        pi.contact = contact
        pi.email = email
        pi.position = position
        pi.uploaddata = uploaded
        pi.save()
        return HttpResponseRedirect("/eadmin")
    return render(request, 'NEC/eupdate.html', {'pi': pi})
Вернуться на верх