Home > Software design >  Update into existing database not working
Update into existing database not working

Time:10-05

I have a page where the users can add a new mco number, when the user click on the Add mco button, it will retrieve the id as shown below:

enter image description here

but when the user add the new mco number and click on the submit button, it will create another row and not update into the id database as shown below, why is that so and how do I solve this issue?

enter image description here

views.py

@login_required()
def AddMCO(request, id):
    photo = get_object_or_404(Photo, id=id)
    if request.method == "POST":

        form = AddMCOForm(request.POST)
        if form.is_valid():
            mcoNum = form.cleaned_data['mcoNum']
            form.save()

            return redirect('ViewMCO')

    else:
        form = AddMCOForm()
    context = {
        "form": form,
        "photo": photo

    }
   
    return render(request, 'AddMCO.html', context, )

forms.py

class AddMCOForm(forms.ModelForm):

    mcoNum = forms.CharField(
        label='Enter MCO Number',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Please enter MCO Number here..'
            }
        )
    )
    class Meta:
        model = Photo
        fields = ("mcoNum",)


    def __init__(self, *args, **kwargs):
        super(AddMCOForm, self).__init__(*args, **kwargs)
        self.fields['mcoNum'].widget.attrs.update({'class': 'form-control', 'placeholder': 'MCO Number'})
        self.fields['mcoNum'].label = ''
        self.fields['mcoNum'].help_text = ''

AddMCO.html

<!DOCTYPE html>
<html>

<head>
    <script>
      $(function () {
        $("#datetimepicker1").datetimepicker();
      });
    </script>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>SCS Add MCO</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>

    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-giJF6kkoqNQ00vy HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X 965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH 8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>

    <!-- Font Awesome -->
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

    <!-- Moment.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script>

    <!-- Tempus Dominus Bootstrap 4 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css" integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5 sRxqak2Qs=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js" integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script>


</head>
<body class="m-5">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-4">
                <h3>Add MCO Number</h3>

                <a href="{% url 'ViewMCO' %}" class="btn btn-dark my-3">Go Back</a>
                <div class="card" style="width: 400px">


                     <form  method="post">
                    {% csrf_token %}

                        <div class="form-group m-3">

                            <br>
                            {{ form.as_p}}
                        </div>





                        <button type='submit' class="btn btn-primary m-3">Submit</button>

                    </form>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

models.py

class Photo(models.Model):
    STEP1 = "Reception"
    STEP2 = "Launching"

    STATUS = (
        (STEP1, 'Reception'),
        (STEP2, 'Launching'),

    )

    Datetime = models.DateTimeField(auto_now_add=True)
    mcoNum = models.TextField() #mcoNum stand for MCO number
    serialno = models.TextField()  # serialno stand for serial number
    partno = models.TextField()  # partno stand for part number
    reception = models.TextField()
    Customername = models.TextField() #Custoner Name
    status = models.CharField(max_length=20, choices=STATUS, default=STEP1, editable=False)

    def __str__(self):
        return self.reception

CodePudding user response:

you are not passing the instance to the form assuming the photo model has addMCO Form as model form of course.

@login_required()
def AddMCO(request, id):
    photo = get_object_or_404(Photo, id=id)
    if request.method == "POST":

        form = AddMCOForm(request.POST, instance=photo)
        if form.is_valid():
            mcoNum = form.cleaned_data['mcoNum']
            form.save()

            return redirect('ViewMCO')

    else:
        form = AddMCOForm(instance=photo)
    context = {
        "form": form,
        "photo": photo

    }


return render(request, 'AddMCO.html', context, )

CodePudding user response:

You have not mentioned Django version and which db is used.

Check if this can help you. Django not updating database

  • Related