gpt4 book ai didi

python - Django 帮助 : Resolving NOT NULL constraint failed error with CreateView

转载 作者:太空狗 更新时间:2023-10-30 02:57:19 25 4
gpt4 key购买 nike

我是 stackoverflow、python 和 Django 的新手,有一个关于“(NOT NULL 约束失败:sixerrapp_gig.user_id)”错误的问题,当我点击表单上的提交时。

很确定这是因为到目前为止我还没有根据我在 StackOverflow 上找到的值分配 user_id 值,但我不确定如何使用 django CreateView 来分配它。

项目练习基于 fiverr.com 的克隆。

请看下面的代码:

在 models.py 中:

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.core.urlresolvers import reverse #for model forms

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.CharField(max_length=500)
about = models.CharField(max_length=1000)

def __str__(self):
return self.user.username

class Gig(models.Model):
CATEGORY_CHOICES = (
("GD", "Graphics & Design"),
("DM", "Digital & Marketing"),
("VA", "Video & Animation"),
("MA", "Music & Audio"),
("PT", "Programming & Tech")
)
title = models.CharField(max_length=500)
category = models.CharField(max_length = 2, choices=CATEGORY_CHOICES)
description = models.CharField(max_length=1000)
price = models.IntegerField(default=6)
photo = models.FileField(upload_to='gigs')
status = models.BooleanField(default=True)
user = models.ForeignKey(User)
create_time = models.DateTimeField(default=timezone.now)

def get_absolute_url(self):
return reverse('my_gigs')

def __str__(self):
return self.title

views.py:

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .models import Gig
from .forms import GigForm

class CreateGig(CreateView):
model = Gig
fields = ['title','category','description','price','photo','status']

gig_form.html

{% extends 'base.html' %}
{% load staticfiles %}

{% block page %}

<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'sixerrapp/form-template.html' %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>

{% endblock %}

我认为我需要的是在提交表单时用户字段自动获取一个值。不确定我的代码中缺少什么来做到这一点。

在此先感谢您的帮助!

最佳答案

您需要在 View 的 form_valid() 方法中处理它。

class CreateGig(CreateView):
model = Gig
fields = ['title','category','description','price','photo','status']

def form_valid(self, form):
form.instance.user = self.request.user
return super(CreateGig, self).form_valid(form)

更多引用 https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#models-and-request-user

关于python - Django 帮助 : Resolving NOT NULL constraint failed error with CreateView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37536577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com