Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

python - After the added product is updated and edited, another new detail page will be generated, but the original modified page was not updated

Python              3.8.3
Django              2.2
asgiref             3.3.1
djangorestframework 3.11.1
Pillow              7.2.0
pip                 19.2.3
psycopg2            2.8.6
pytz                2020.1
setuptools          41.2.0
sqlparse            0.3.1

May I ask the great god, The newly added product object needs to be edited, but after editing it becomes another addition. For example: Enter the item 3 product, edit the content and click "Confirm Edit". The original item is the item number 3 and instantly becomes the item item No. 4. After each edit or update, it will become a new product page. What is the program part? Is there a mistake?

Add again: Originally wanted to edit this page http://127.0.0.1:8001/store/107/(id=107), After editing and archiving, the page that pops up is a new id=111 page. http://127.0.0.1:8001/store/111/ (id=111)

But I enter admin http://127.0.0.1:8001/admin/store/product/111/change/ After the change, there is no problem, and you can edit it. This error only appears on the screen of my newly created form.

Find a solution: There is a similar "editing" program on the Internet. The writing method is similar to what I wrote, but I cannot edit the product with id=107. How can I solve it?

urls.py

    path('<int:id>/edit/', views.productUpdate, name='edit'),

views.py

def productUpdate(request, id=None):
    # basic use permissions 基本使用權限
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404

    instance = get_object_or_404(Product, id=id)
    form = ProductForms(request.POST or None, instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        # message success
        messages.success(request, "<a href='#'>Item</a> Saved", extra_tags='html_safe')
        return HttpResponseRedirect(instance.get_absolute_url())

    # 購物車購買數量
    data = cartData(request)
    cartItems = data['cartItems']

    context = {
        'instance': instance,
        'form': form,
        'cartItems': cartItems,
    }
    return render(request, 'store/form.html', context)

models.py

class Product(models.Model):
    name = models.CharField(max_length=200)
    content = models.TextField(default='')
    price = models.DecimalField(max_digits=7, decimal_places=2)
    digital = models.BooleanField(default=False, null=True, blank=True)
    image = models.ImageField(
        upload_to=imgs,
        null=True,
        blank=True,
        width_field="width_field",
        height_field="height_field"
    )
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)

    def __unicode__(self):
        return self.name

    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url

    def get_absolute_url(self):
        return reverse('store:detail', kwargs={'id': self.id})

    class Meta:
        ordering = ["-timestamp", "-updated"]

form.html

{% extends "store/main.html" %}

{% block content %}
    <div class="container">
         <div class="row pt-5">
            <div class='col-sm-6 pt-5'>
                <a href="{% url 'store:store' %}" class="pt-5 text-danger bg-dark text-decoration-none">返回首頁</a>
            </div>
        </div>
        <div class="row">
            <div class='col-sm-6'>
                <h1>Form</h1>

                <form method='post' action='{% url 'store:create' %}' enctype='multipart/form-data'>{% csrf_token %}
                    {{ form.as_p }}
                    <button><input type='submit' class='btn btn-default' value='Create Post'/></button>

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

    </div>

{% endblock content %}

detail.html

            <div class='col-sm-6 col-sm-offset-3'>
                <a href="{% url 'store:edit' id=instance.id %}">Edit/update Product</a><br>
                <a href="{% url 'store:delete' id=instance.id %}">Del Product</a><br>
                {#                <a href="{% url 'store:list' %}">Product</a><br>#}
            </div>

Important notice, because this is not an error message, neither the ide nor the webpage provides any error message, so it is not attached.

Novice practice complete project : https://github.com/georgiawang5332/libshopapp

please help me thank you!!!

question from:https://stackoverflow.com/questions/65843925/after-the-added-product-is-updated-and-edited-another-new-detail-page-will-be-g

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that you are creating a new object instead of updating the existing one: Hope this will solve your problem.

def productUpdate(request, id=None):
    # basic use permissions 基本使用權限
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404

    context = {}
    if request.POST:
        form = ProductForms(request.POST)
        if form.is_valid():
            instance = get_object_or_404(Product, id=id)
            form = ProductForms(data=request.POST, instance=instance)
            form.save()
            # updating our context
            context.update({'instance': instance})
            # message success
            messages.success(request, "<a href='#'>Item</a> Saved",
                             extra_tags='html_safe')
            return HttpResponseRedirect(instance.get_absolute_url())

    else:
        form = ProductForms()  # if request isn't POST we initialize an empty form

    data = cartData(request)
    cartItems = data['cartItems']

    context.update({
        'form': form,
        'cartItems': cartItems,
    })
    return render(request, 'store/form.html', context)

Visit django's modelform docs for more detail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...