Django表单保存:对象为“无”,但表单有效

u3r8eeie  于 2023-03-31  发布在  Go
关注(0)|答案(2)|浏览(142)

我希望answer here与我遇到的问题有关,但不幸的是,它不一样,我无法使用它来解决问题。我还尝试遵循method here,这也不能证明成功解决这个特定的问题。

问题是:我尝试使用一个简单的表单来创建一个新的对象。一些信息来自用户,一些信息来自系统。当我处理POST请求时,使用简单的print语句,我可以看到表单是有效的,并且它有正确的数据。但是当我去保存时,它告诉我对象是None,所以它不保存任何东西。

下面是:

  • views.py
  • forms.py
  • models.py
  • template.html

我错过了什么?谢谢!

查看次数.py

def add_set_to_active_workout(request):
    workout = get_active_workout()
    if request.method == "POST":
        form = SetForm(request.POST)
        if form.is_valid():
            print(f"Cleaned data is: {form.cleaned_data}") # This prints what I'd expect, namely, the user submitted data. 
            set = form.save(commit=False)
            set.workout = workout
            print(f"Set is {set}") # This prints: Set is Set object (None)
            set.save()
            print("set saved")
            return HttpResponseRedirect(reverse("log:active_workout"))
        else:
            return render(request, "log/active_workout.html", {
                "set_form": form,
                'workout': workout
            })
    else:
        return render(request, "log/active_workout.html", {
            "set_form": SetForm(), 'workout': workout,
        })

**print语句print(f"Set is {set}") Set is Set object (none),这是要解决的问题。**下面是确切的print语句:

Cleaned data is: {'exercise': <Exercise: Deadlift>, 'actual_weight': 225.0, 'actual_reps': 12, 'actual_difficulty': 'easy'}
Set is Set object (None)
set saved
forms.py

class SetForm(forms.ModelForm):
    class Meta:
        model = Set
        fields = ['exercise', 'actual_weight', 'actual_reps', 'actual_difficulty']

models.py

class Set(models.Model):
    exercise = models.ForeignKey(Exercise, related_name="sets", on_delete=models.SET("Exercise Deleted!"))
    workout = models.ForeignKey(Workout, related_name="sets", on_delete=models.CASCADE)
    actual_reps = models.PositiveSmallIntegerField()
    actual_weight = models.FloatField()

    difficulty_options = (
        ("easy", "easy"),
        ("medium", "medium"),
        ("hard", "hard")
    )
    actual_difficulty = models.CharField(choices=difficulty_options, max_length=6)

    set_complete = models.DateTimeField(auto_now_add=True)

template.html

<h2>Add a Set:</h2>
<form action="{% url 'log:add_set_to_active_workout' %}" method="POST">
    {% csrf_token %}
    {{ set_form.as_p }}
    <input type="submit" value="Save Set" class="btn btn-secondary">
</form>
mu0hgdu0

mu0hgdu01#

您试图在保存新对象之前打印其表示:

print(f"Set is {set}") # This prints: Set is Set object (None)
set.save()
set.save()
print(f"Set is {set}")

我还建议不要使用set作为变量名,因为它是一个内置类型

xfyts7mz

xfyts7mz2#

当你调用print(object_name)时,它会调用对象内部的__str__方法。模型的默认实现如下所示(除非你覆盖它):

def __str__(self):
    return "%s object (%s)" % (self.__class__.__name__, self.pk)

由于您在保存表单时使用了commit=False,它没有将对象存储在数据库中,因此pk为None。这就是为什么当您打印时,您会得到

Set object (None)
^^^^^^^^^^ ^^^^^
class name   pk

但是在使用set.save()保存并打印之后,它应该返回Set object (1)

***仅供参考:您应该使用不同于set的变量名,因为它表示Python中的set数据类型。

相关问题