0

我整个星期都在为此苦苦挣扎,我需要让它一劳永逸地休息。这可能看起来像很多代码,但核心是一个简单的概念问题。

我有一个模型 UserProfile,它具有以下字段:

user = models.OneToOneField(User)
weekOne = models.OneToOneField(WeekOne)
weekTwo = models.OneToOneField(WeekTwo)

WeekOne 和 WeekTwo 都是具有自己独特字段 (models.Model) 的模型,它们继承自名为 Week 的自定义类。Week 只是有一些自定义函数来保存每周重新键入的一些方法以及以下代码以使其成为抽象类:

class Meta:
    abstract = True

基本上,我希望每个用户都有一个独特的 weekOne 和 weekTwo(及以后)字段,其中包含具有用户唯一值的自定义字段。

当我第一次创建用户时(即,当他们注册时),我使用以下代码views.py

def signup(request):
    user_form = UserCreateForm(data=request.POST)
    if request.method == 'POST':
        if user_form.is_valid():
            username = user_form.clean_username()
            password = user_form.clean_password2()
            user_form.save()
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('/')
        else:
            return index(request, user_form=user_form)
    return redirect('/')

基本的表单注册内容,这里一切正常。

现在,这就是事情变得危险的地方。我有一个 weekOne 的视图,它确保已创建用户的个人资料,如果没有,则创建一个,其代码如下:

@login_required
def workout1(request):
    template = "workout1.html"
    weekOne = WeekOne()
    weekOne.save()
    user, created = UserProfile.objects.get_or_create(user=request.user,
            defaults = {'weekOne': weekOne})
    name = weekOne.__unicode__()

    if created:
        context = {'user': user}
        return render(request, template, context)

    # Grab already existing User Profile
    weekOne.delete() # Was never used
    context = {'user': user, 'name': name}
    return render(request, template, context)

好的。所以这很酷。但是当我尝试转到第一周的页面时,我收到以下错误:

workout_game_app_userprofile.weekTwo_id may not be NULL

这就是我迷路的地方。我应该为每个星期视图初始化每个星期变量吗?即,对于第一周的视图,我是否应该执行如下代码:

weekOne = WeekOne()
weekTwo = WeekTwo()
weekThree = WeekThree()

ETC。?如果我计划实施的所有 12 周都必须这样做,这似乎是荒谬的重复。

顺便说一句,在我实施第二周之前,我的模型运行良好。

另外,OneToOne 是正确使用的密钥吗?我想做一些事情,比如访问 user.weekOne.item1、user.weekOne.item2 等,并仅为该用户更改和保存它们的值。

UPDATE:对于 Sidharth Shah,这是我的观点和模型中的其余代码:

视图.py:

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.models import User
from workout_game_app.forms import AuthenticateForm, UserCreateForm
from workout_game_app.models import WeekOne, WeekTwo, UserProfile
from django.http import Http404, HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
import simplejson


def index(request, auth_form=None, user_form=None):
    if request.user.is_authenticated():
        user = request.user
        name = "Missions Overview"
        context = {'user': user, 'name': name}
        template = 'workouts.html'
        return render(request, template, context)
    else:
        auth_form = auth_form or AuthenticateForm()
        user_form = user_form or UserCreateForm()
        template = 'index.html'
        context = {'auth_form': auth_form, 'user_form': user_form}
        return render(request, template, context)

def login_view(request):
    if request.method == 'POST':
        form = AuthenticateForm(data=request.POST)
        if form.is_valid():
            login(request, form.get_user())
            return redirect('/')
        else:
            return index(request, auth_form=form)
    return redirect('/')


def signup(request):
    user_form = UserCreateForm(data=request.POST)
    if request.method == 'POST':
        if user_form.is_valid():
            username = user_form.clean_username()
            password = user_form.clean_password2()
            user_form.save()
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('/')
        else:
            return index(request, user_form=user_form)
    return redirect('/')

@login_required
def submitWorkout1(request):
    if request.method == 'POST':
        exercise = request.POST['exercise']
        try:
            amount = request.POST['amount']
        except KeyError: # No amount field on form
            amount = ""
        user = UserProfile.objects.get(user=request.user)
        week = user.weekOne
        exercise, amount, exerciseComplete, allComplete = user.updateExercise(week, exercise, amount)
        data = simplejson.dumps({
            'result': 'success',
            'exercise': exercise,
            'amount': amount,
            'exerciseComplete': exerciseComplete,
            'allComplete': allComplete
            }, indent=4)
        return HttpResponse(data)


@login_required
def workout2(request):
    template = "workout2.html"
    weekTwo = WeekTwo()
    weekTwo.save()
    user, created = UserProfile.objects.get_or_create(user=request.user,
            defaults = {'weekTwo': weekTwo})
    name = weekTwo.__unicode__()

    if created:
        context = {'user': user}
        return render(request, template, context)

    # Grab already existing User Profile
    weekTwo.delete() # Was never used
    context = {'user': user, 'name': name}
    return render(request, template, context)

@login_required
def submitWorkout2(request):
    if request.method == 'POST':
        exercise = request.POST['exercise']
        try:
            amount = request.POST['amount']
        except KeyError: # No amount field on form
            amount = ""
        user = UserProfile.objects.get(user=request.user)
        week = user.weekTwo
        exercise, amount, exerciseComplete, allComplete = user.updateExercise(week, exercise, amount)
        data = simplejson.dumps({
            'result': 'success',
            'exercise': exercise,
            'amount': amount,
            'exerciseComplete': exerciseComplete,
            'allComplete': allComplete
            }, indent=4)
        return HttpResponse(data)

和models.py:

from django.db import models
from django.contrib.auth.models import User

class Week(models.Model):
    # List of exercises by name for the week
    exercises = []
    # Week name in unicode
    name = u''

    # Running count of benchmarks met.
    completeCount = models.PositiveSmallIntegerField(default=0)
    # Set to true if benchmarks reached. 
    weekComplete = models.BooleanField(default=False)
        # A bunch of methods

class WeekOne(Week):
    name = u'Mission One'
    exercises = ['squats', 'lunges', 'stairDaysCount', 'skipStairs']
    # Required benchmarks for given exercises
    squatBenchmark = 1000
    lungeBenchmark = 250
    stairDaysCountBenchmark = 3

    totalGoals = 4

    squats = models.PositiveIntegerField(default=0)
    lunges = models.PositiveIntegerField(default=0)
    skipStairs = models.BooleanField(default=False)
    stairDaysCount = models.PositiveSmallIntegerField(default=0)
    # A bunch of methods

class WeekTwo(Week):
    name = u'Mission Two'
    exercises = ['up3Levels', 'noHands', 'treadmill', 'vagMachine', 'extendedStairs']
    totalGoals = 5

    up3Levels = models.BooleanField(default=False)
    noHands = models.BooleanField(default=False)
    treadmill = models.BooleanField(default=False)
    vagMachine = models.BooleanField(default=False)
    extendedStairs = models.BooleanField(default=False)
    # A bunch of methods

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    weekOne = models.OneToOneField(WeekOne, null=True, default=None)
    weekTwo = models.OneToOneField(WeekTwo, null=True, default=None)
    # Some methods

而且,虽然它工作正常,但我的 forms.py 可以很好地衡量:

from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django import forms
from django.utils.html import strip_tags

class UserCreateForm(UserCreationForm):
    username = forms.CharField(required=True,
            widget = forms.widgets.TextInput(attrs={'placeholder': 'Username'}))
    password1 = forms.CharField(required=True,
            widget = forms.widgets.PasswordInput(attrs={'placeholder': 'Password'}))
    password2 = forms.CharField(required=True,
            widget = forms.widgets.PasswordInput(attrs={'placeholder': 'Password'}))

    def is_valid(self):
        form = super(UserCreateForm, self).is_valid()
        for f, error in self.errors.iteritems():
            if f != '__all_':
                self.fields[f].widget.attrs.update({'class':'error', 'value':strip_tags(error)})
        return form

    class Meta:
        fields = ['username', 'password1', 'password2']
        model = User

class AuthenticateForm(AuthenticationForm):
    username = forms.CharField(
            widget = forms.widgets.TextInput(attrs={'placeholder':'Username'}))
    password2 = forms.CharField(
            widget = forms.widgets.PasswordInput(attrs={'placeholder': 'Password'}))
4

1 回答 1

1

您可能想要以下模型

user = models.OneToOneField(User)
weekOne = models.OneToOneField(WeekOne, null=True, default=None)
weekTwo = models.OneToOneField(WeekTwo, null=True, default=None)

试试看,它应该工作。查看上面的代码,您正在定义字段 weekOne、weekTwo 等。我不确定您是否在创建它时分配了所有必要的字段 weekOne 对象。

于 2013-03-27T02:06:52.673 回答