列'user_id'不能为null django

时间:2015-07-04 18:52:57

标签: mysql django

我试图创建一个帖子,其中注册用户创建并在数据库中插入主键ID,但这不会给我以下错误列'user_id'不能为空

这是我的models.py

class posts(models.Model):
    titulo = models.CharField(max_length=180, unique=True)
    slug = models.SlugField(max_length=180, editable=False)
    contenido = models.TextField()
    categoria = models.ForeignKey(categorias)

    user = models.ForeignKey(User)
    tags = models.CharField(max_length=200)
    creado = models.DateTimeField(auto_now_add=True)
    modificado = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.titulo)
        super(posts, self).save(*args, **kwargs)

    def __str__(self):
        return self.titulo

这是我的view.py

def addPosts(request):
     if request.method == "POST":
            form = addPostForm(request.POST)
            if form.is_valid():
                add = form.save(commit=False)
                #add.user = User.objects.get(id=request.user)
                add.save()
                form.save_m2m()
                return HttpResponseRedirect('/')
        else:
            form = addPostForm ()
        ctx = {'form': form}
        return render_to_response('posts/add.html', ctx, context_instance=RequestContext(request))

这是forms.py

class addPostForm(forms.ModelForm):
      class Meta:
            model = posts
            exclude = {'slug','user', 'creado'}

解决这个问题的一些方法?

2 个答案:

答案 0 :(得分:1)

Request.user返回当前用户对象。无需进行查找。

function roll() {
  var text = "";
  var sides = +document.getElementById("diceSides").value;
  var dice = +document.getElementById("numberOfDice").value;
  var rolls = [];

  //  --------Ensures both Numbers are Intergers-----------

  if (isNaN(sides) || isNaN(dice)) {
    alert("Both arguments must be numbers.");
  }
  //  --------Loop to Print out Rolls-----------
  var counter = 1;
  do {
    roll = Math.floor(Math.random() * sides) + 1;
    text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
    counter++;
    rolls.push(roll);

  }
  while (counter <= dice)
  document.getElementById("output").innerHTML = text;

  //  --------Double Determination-----------
  var cache = {};
  var results = [];
  for (var i = 0, len = rolls.length; i < len; i++) {
    if (cache[rolls[i]] === true) {
      results.push(rolls[i]);
    } else {
      cache[rolls[i]] = true;
    }
    //  --------Print amount of Doubles to Document-----------
  }
  if (results.length === 0) {} else {
    document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
  }
}

//  --------RESET FUNCTION-----------
function reset() {
  document.getElementById("output1").innerHTML = "";
  document.getElementById("output").innerHTML = "";
  document.getElementById("diceSides").value = "";
  document.getElementById("numberOfDice").value = "";
  text = "";
  rolls = [];
}
在您的视图中

答案 1 :(得分:0)

如果与Django内置用户联系,您将希望以与您的模型不同的方式进行操作:

.hints .error { display: none; }
.form-group.ng-invalid.ng-dirty .error-invalid { display: block; }
.form-group.ng-invalid-required.ng-dirty .error-required { display: block; }

考虑在您的设置中定义此内容,然后使用:

user = models.ForeignKey(User)

请参阅此处的文档:https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#referencing-the-user-model

如果您决定在将来扩展Django基本用户模型,这也将为您提供面向未来的保障。