我正在尝试保存我的 TagStatus 对象。现在它正在保存,但它没有保存用户名,也没有保存标签外键。
它现在的节省是这样的:
user : __________ (empty)
status : Status 2
tag : _________ (empty)
我究竟做错了什么?为什么不保存用户名或标签?提前谢谢你的帮助。
该模型:
class TagStatus(models.Model):
user = models.ForeignKey(User, null=True, unique=True)
status = models.CharField(max_length=2, choices=tag_statuses)
tag = models.ForeignKey(Tag, null=True, blank=True)
def __unicode__(self):
return self.status
def save(self, *args, **kwargs):
super(TagStatus, self).save(*args, **kwargs)
我的观点:
@login_required
def tags(request):
all_tags = Tag.objects.all()
context = base_context(request)
if request.method == 'POST':
if 'status_check' in request.POST:
status = int(request.POST['select'])
tag = request.POST['tag']
user = request.user
try:
tag_status = TagStatus.objects.get_or_create(status=status, tag__slug=tag, user__username=user.username)
except TagStatus.DoesNotExist:
tag_status = None
response = simplejson.dumps({"status": "Successfully changed status"})
else:
response = simplejson.dumps({"status": "Error"})
return HttpResponse (response, mimetype='application/json')
status_form = TagStatusForm()
context['all_tags'] = all_tags
return render_to_response('tags/tags.html', context, context_instance=RequestContext(request))
模板:
<form class="nice" id="status-form" method="POST" action="">
{% csrf_token %}
<input type="hidden" name="status_check" />
<input type='hidden' name="tag" value="{{ tag.slug }}" />
<select name="select" id="positionSelect" class="input-text category" onchange="this.form.submit()">
<option name="all" value="0">Your Status</option>
<option name="investing" value="1">Status 1</option>
<option name="selling" value="2">Status 2</option>
<option name="interested" value="3">Status 3</option>
</select>
</form>