mysql 字段'activity_id'需要一个数字,但得到〈QueryDict: Django

ctehm74n  于 2022-10-31  发布在  Mysql
关注(0)|答案(1)|浏览(125)

我正在创建一个小的django CRUD项目,并致力于创建创建功能,然而每次我试图通过网站前端创建一个活动时,我都会得到以下错误

Field 'activity_id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['DnM8yrfIrvYgvN6rShEOtR9DFwjpryNtHHs6ytHK1CSAYg3G9sm7YjkcHlpejJDt'], 'host': ['1'], 'name': ['testing testing'], 'date': ['2022-06-28'], 'start_time': ['19:20:58'], 'end_time': ['19:52:50'], 'location': ['test Location'], 'description': ['ewerwerwerwe']}>.

当我通过/admin面板创建somethign时,它按预期工作。
下面是我的forms.py文件:

from django import forms
from .models import Activity

class ActivityForm(forms.ModelForm):
    class Meta:
        model = Activity
        fields = ('host', 'name', 'date',
                  'start_time', 'end_time', 
                  'location', 'description')

    def __init__(self, *args,**kwargs):
        """
        Add placeholders and classes, remove auto-generated
        labels and set autofocus on first field
        """
        super().__init__(*args,**kwargs)
        placeholders = {
            'name': 'Activity Type',
            'date': 'Date of Activity',
            'start_time': 'Start Time',
            'end_time': 'End Time',
            'location': 'Location',
            'description': 'Description',
            'host': 'Host',
        }

        for field in self.fields:
            if self.fields[field].required:
                placeholder = f'{placeholders[field]} *'
            else:
                placeholder = placeholders[field]
            self.fields[field].widget.attrs['placeholder'] = placeholder
            self.fields[field].label = False

这是models.py文件

class Activity(models.Model):
    class Meta:
        verbose_name_plural = 'Activities'

    activity_id = models.AutoField(primary_key=True)
    host = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    name = models.CharField(max_length=254, null=False, blank=False)
    date = models.DateField()
    start_time =models.TimeField()
    end_time = models.TimeField()
    location = models.CharField(max_length=40, null=False, blank=False)
    description = models.CharField(max_length=140, null=False, blank=False)
    available = models.BooleanField(default=True)

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

和视图:

def create_activity(request):
    if request.method == "POST":
        form_data = request.POST
        form = Activity(form_data)
        print(form_data)
        form.save()
    else:
        form = ActivityForm()
        context = {
        'form': form,
    }
        return render(request, 'activities/new_listing.html', context)
uz75evzq

uz75evzq1#

您使用form_data创建一个ActivityForm,因此:

def create_activity(request):
    if request.method == 'POST':
        form = ActivityForm(request.POST)  # 🖘 ActivityForm
        if form.is_valid():
            form.save()
            return redirect('name-of-some-view')
    else:
        form = ActivityForm()
    context = {
        'form': form,
    }
    return render(request, 'activities/new_listing.html', context)

注意:如果POST请求成功,您应该创建一个**redirect**[Django-doc]来实现Post/Redirect/Get pattern [wiki]。这样可以避免在用户刷新浏览器时,您也会发出相同的POST请求。

相关问题