ValueError: 无法赋值 “value”,”Order.dish_name” 必须是一个 “Dish” 实例

huangapple go评论93阅读模式
英文:

ValueError: Cannot assign "value" "Order.dish_name" must be a "Dish" instance

问题

以下是您要翻译的内容:

"我正在使用Django编写一个餐厅应用程序,我有一个特定的视图来捕获Ajax请求。从这个请求中,我得到了一个菜名,我尝试将其保存在一个新的Order对象中。我一直在尝试解决这个错误“ValueError: 无法赋值'pasta':'Order.dish_name'必须是'Dish'实例。”,但我不知道为什么。我已经尝试修复它两天了,所以我想知道我做错了什么"

以及代码片段:

models.py

from django.db import models

class Table(models.Model):
    number = models.IntegerField(primary_key=True)

    def __str__(self):
        return str(self.number)

class Dish(models.Model):
    name = models.CharField(primary_key=True, max_length=50)
    price = models.FloatField()
    type = models.CharField(max_length=50)
    gluten = models.BooleanField(null=False)
    lactose = models.BooleanField(null=False)

    def __str__(self):
        return self.name

class Meal(models.Model):
    start = models.TimeField()
    end = models.TimeField(blank=True, null=True, default=None)
    table = models.ForeignKey(Table, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.table.number)

class Order(models.Model):
    request_time = models.TimeField()
    kitchen_start_time = models.TimeField(blank=True, null=True, default=None)
    delivery_time = models.TimeField(blank=True, null=True, default=None)
    dish_name = models.ForeignKey(Dish, null=True, blank=True, default=None, on_delete=models.CASCADE)
    table = models.ForeignKey(Table, null=True, default=None, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.table.number)

main.js

$(".special").click(function (e){
    var x = e.target.id;
    $.ajax({
        type: 'POST',
        data: {
            'dishes': x,
        },
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        },
    });
    e.preventDefault();
});

html的一部分

{% for d in dishes %}
    <div class="cell">
        <a href="#" class="special" id='{{d.name}}'>{{d.name}}</a>
    </div>
{% endfor %}

视图

def open(request, number):
    tav = Table.objects.get(number=number)
    p = Meal(table=tav, start=datetime.now())
    p.save()
    dishes = Dish.objects.all().order_by('type')
    if request.method == 'POST':
        clicked_dish = request.POST.get('dishes')
        new_order = Order(request_time=datetime.now(), dish_name=clicked_dish, table=tav)
        new_order.save()
    return render(request, 'nuovo.html', {'dishes': dishes, 'table': tav})

url

urlpatterns = [
    re_path(r'^admin/', admin.site.urls),
    re_path(r'home/', views.home),
    re_path(r'^new/', views.index, name='index'),
    re_path(r'^open/(\d+)/$', views.open, name='open'),
]

希望这有助于您理解并解决您的问题。如果您需要更多帮助,请随时提出。

英文:

I am writing a restaurant app in Django and I have a specific view that catches an Ajax request. From this request I get the name of a dish, which I try to save in a new object Order. I keep getting this error " ValueError: Cannot assign "'pasta'": "Order.dish_name" must be a "Dish" instance." and I have no idea why. I have been trying to fix it for 2 days, so i would like to know what I am doing wrong

type here

models.py`

from django.db import models

class Table( models.Model ) :
    number = models.IntegerField( primary_key= True)

    def __str__( self ) :
        return str(self.number)
    
class Dish(models.Model ) :
    name = models.CharField( primary_key= True, max_length= 50 )
    price = models.FloatField()
    type = models.CharField( max_length= 50 )
    gluten = models.BooleanField( null= False)
    lactose = models.BooleanField( null= False)


    def __str__( self ) :
        return self.name

class Meal(models.Model ) :
    start = models.TimeField()
    end = models.TimeField(blank= True, null= True, default= None)
    table = models.ForeignKey(Table, on_delete=models.CASCADE)

    def __str__( self ) :
        return str(self.table.number)
    
class Order(models.Model):
    request_time = models.TimeField()
    kitchen_start_time = models.TimeField(blank= True, null= True, default= None)
    delivery_time = models.TimeField(blank= True, null= True, default= None)
    dish_name = models.ForeignKey(Dish, null= True, blank= True, default= None, on_delete=models.CASCADE)
    table = models.ForeignKey(Table, null= True, default= None, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.table.number)````

The main.js

$(&quot;.special&quot;).click(function (e){
    var x= e.target.id
    $.ajax({
        type: &#39;POST&#39;,
        data: {
            &#39;dishes&#39; : x,
        },
        success: function(response){
            console.log(response);
            },
        error: function(error){
            console.log(error);
            },
    });   
    e.preventDefault();    
}
)

part of the html

 {% for d in dishes %}
      
        &lt;div class=&quot;cell&quot;&gt;
          &lt;a href=# class=&quot;special&quot; id=&#39;{{d.name}}&#39; &gt; {{d.name}}&lt;/a&gt;&lt;/li&gt;
        &lt;/div&gt;

  {% endfor %}

the view


def open(request, number):

    tav = Table.objects.get(number = number)
    p = Meal(table=tav, start=datetime.now())
    p.save()
    dishes = Dish.objects.all().order_by(&#39;type&#39;)
    if request.method == &#39;POST&#39;:
        clicked_dish =request.POST.get(&#39;dishes&#39;)
        new_order= Order(request_time=datetime.now(), dish_name= clicked_dish, table=tav)
        new_order.save()

    return render(request, &#39;nuovo.html&#39;, {&#39;dishes&#39;: dishes, &#39;table&#39;: tav})

and the url

urlpatterns = [
    
    re_path(r&#39;^admin/&#39;, admin.site.urls),
    re_path(r&#39;home/&#39;, views.home),
    re_path(r&#39;^new/&#39;,views.index, name=&#39;index&#39;),
    re_path(r&#39;^open/(\d+)/$&#39;,views.open, name=&#39;open&#39;),
]

答案1

得分: 1

我会过滤出一个菜品实例

从django.http导入HttpResponseBadRequest

def open(request, number):
    if request.method == "GET":
        return HttpResponseBadRequest()

    tav = Table.objects.get(number=number)
    p = Meal(table=tav, start=datetime.now())
    p.save()
    d = request.POST.get('dishes', None)
    dish = Dish.objects.filter(id=d).first()
     
    new_order = Order(request_time=datetime.now(), dish_name=dish, table=tav)
    new_order.save()

return render(request, 'nuovo.html', {'dish': dish, 'table': tav})

希望它能工作!

英文:

I would filter an instance of dish

from django.http import HttpResponseBadRequest

def open(request, number):
    if request.method == &quot;GET&quot;:
        return HttpResponseBadRequest()

    tav = Table.objects.get(number = number)
    p = Meal(table=tav, start=datetime.now())
    p.save()
    d =request.POST.get(&#39;dishes&#39;, None)
    dish = Dish.objects.filter(id=d).first()
     
    new_order= Order(request_time=datetime.now(), dish_name= dish, table=tav)
    new_order.save()

return render(request, &#39;nuovo.html&#39;, {&#39;dish&#39;: dish, &#39;table&#39;: tav})

Hope it work's!

huangapple
  • 本文由 发表于 2023年3月10日 01:37:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75688181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定