我整整一周都在苦苦挣扎,我需要一劳永逸地休息。这可能看起来像很多代码,但核心是一个简单的概念问题。
我有一个模型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()
等?如果我必须在我计划实施的所有12周内完成它,这似乎是荒谬的重复。
顺便说一句,在我实施第二周之前,我的模型运作良好。另外,OneToOne是否是正确使用的密钥?我想做一些事情,比如访问user.weekOne.item1,user.weekOne.item2等,并仅为该用户更改和保存它们的值。
UPDATE
:对于Sidharth Shah,这是我的观点和模型中的其余代码:
views.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'}))
答案 0 :(得分:1)
您可能希望拥有以下型号
user = models.OneToOneField(User)
weekOne = models.OneToOneField(WeekOne, null=True, default=None)
weekTwo = models.OneToOneField(WeekTwo, null=True, default=None)
尝试一下,它应该工作。查看上面的代码,您将定义字段weekOne,weekTwo等。我不确定的是,如果您在创建它时分配所有必需字段weekOne对象。