Django:无法使用form=MyForm(instance=MyID)更新现有记录

2024-06-17 11:56:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图更新一个现有的记录,我创建了他的表单,在我调用的视图中 EditRecipeForm(实例)=Recipe.objects.get获取(id=recipe\u id)但在视图中不显示 现有字段。你知道吗

这是目录的结构

rsg
├── src
|   ├── recipes
|   |   ├── forms
|   |   |   ├── __init__.py
|   |   |   └── update.py
|   |   ├── __init__.py
|   |   ├── admin.py
|   |   ├── models.py
|   |   ├── test.py
|   |   ├── urls.py
|   |   └── views.py
|   ├── rsg
|   |   └── ...
|   ├── signups
|   |   ├── ...
|   |   └── ...
|   └── magnate.py
├── static
    ├── media
    ├── static
    ├── static-only
    ├── templates
    |   ├── recipes
    |   |   ├── profileview.html
    |   |   ├── recipedit.html
    |   |   └── recipecreate.html
    |   ├── signups
    |   └── ....
    ├── ...
    └── index.hml

以下是配方模型:来自rsg/src/recpes/型号.py你知道吗

class Recipe(models.Model):

name = models.CharField('Nome',max_length=200)
    description = models.TextField('Presentazione', null=True, blank=True, default="")

directions = models.TextField('Preparazione', null=True, blank=True)
pub_date = models.DateTimeField('Data di Pubblicazione',auto_now_add=True, auto_now = False)
    updated = models.DateTimeField('Data ultima modifica', auto_now_add=False, auto_now = True)
    img = models.ImageField('Immagine', upload_to="/static/Images/", null=True, blank=True)

    difficulty_grade = (
        ('bassa', 'bassa'),
        ('media', 'media'),
        ('alta', 'alta'),
        ('molto alta', 'molto alta'),
    )

    cost_size = (
         ('basso', 'basso'),
          ('medio', 'medio'),
           ('alto', 'alto'),
    )
    difficulty = models.CharField(smart_unicode('Difficoltà'), max_length=20, null=True, blank=True, choices=difficulty_grade)
    time_preparation = models.IntegerField('Preparazione', null=True, blank=True)
    time_preparation_min_h = models.CharField('Ore/minuti', max_length=20, null=True, blank=True,
                                                choices=(('ore', 'h'),('minuti','min'),('giorni','gg'),))
    time_cooking = models.IntegerField('Cottura', null=True, blank=True)
    time_cooking_min_h = models.CharField('Ore/minuti', max_length=20, null=True, blank=True,
                                                choices=(('ore', 'h'),('minuti','min'),('giorni','gg'),))
    dose_for = models.CharField(smart_unicode('Dosi per'), max_length=20, null=True, blank=True)
    cost = models.CharField(smart_unicode('Costo'), max_length=20, null=True, blank=True, choices=cost_size)

    total_calories =models.DecimalField('Calorie totali', max_digits=9, decimal_places= 2, default=0)
    count_like = models.IntegerField('Likes', default=0)
    count_dontlike = models.IntegerField('Don\'t Likes', default=0)

    # Relation with SignUp for the Author of the Recipe
author_recipe_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='AuthorRecipeUser')

    # Relation with SignUp for the Like/NotLike 
voter_user = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Likes')

    # Relation N:M with the Ingredients
ingredients = models.ManyToManyField(Ingredient, through='MadeWith')

def __unicode__(self):
    return self.name

有一些关系,其他表,但这并不重要。。。你知道吗

包含EditRecipeForm rsg/src/recipes/forms的文件/更新.py你知道吗

from django import forms
from recipes.models import Recipe

class EditRecipeForm(forms.ModelForm):

   class Meta:
          model = Recipe
          fields = ('name','description','directions','img','difficulty','time_preparation',
                    'time_preparation_min_h','time_cooking','time_cooking_min_h','dose_for',
                    'cost')

那个视图.py文件:

def recipedit(request, recipe_id):

    recipe = Recipe.objects.get(pk=recipe_id)
    form = EditRecipeForm(instance=recipe)

    if request.POST:

        if form.is_valid():
            form.save()

            return HttpResponseRedirect("recipes/profileview.html")

    else:
        form = EditRecipeForm(instance=recipe)


    return render_to_response("recipes/recipedit.html",
                              locals(),
                              context_instance=RequestContext(request))

我传递参数“instance”,但是表单是空的。。。你知道吗

我需要帮助谢谢大家!!你知道吗


这是模板文件

{% extends 'base.html' %}

{% block content %}
    <br>
    <br>
    <br>
    <br>
    <form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
        <input type="submit" value="Submit" />
    </form>

{% endblock %}

Tags: pyformtruetimemodelshtmlrecipemin
1条回答
网友
1楼 · 发布于 2024-06-17 11:56:29

你也没有传递POST数据。你知道吗

def recipedit(request, recipe_id):
    recipe = Recipe.objects.get(pk=recipe_id)    
    if request.POST:
        form = EditRecipeForm(request.POST, instance=recipe)
        if form.is_valid():
            ...

相关问题 更多 >