我是Django的新手!所以可能是错误的方式:)
我正在构建一个活动应用。 我正试图在'MyGuest'的'EventProfile'模型中添加/删除用户到'主机'列表,我基本上想在每个'EventProfile'中使用不同的主机列表,我正在使用类方法。
我可以在管理员中为每个特定的EventProfile模型添加/删除每个对象,但似乎无法在我的网站上进行此操作?
我一直收到此错误“get()返回多个主机 - 它返回2!”
请见我的代码,请帮助:)
Models.py
class MyGuest(models.Model):
users = models.ManyToManyField(User)
current_user = models.ForeignKey(User, related_name='add_myguest', null=True)
@classmethod
def make_myguest(cls, current_user, new_myguest):
myguest, created = cls.objects.get_or_create(current_user=current_user)
myguest.users.add(new_myguest)
@classmethod
def lose_myguest(cls, current_user, new_myguest):
myguest, created = cls.objects.get_or_create(current_user=current_user)
myguest.users.remove(new_myguest)
class Host(models.Model):
users = models.ManyToManyField(User)
current_user = models.ForeignKey(User, related_name='add_myguest', null=True)
@classmethod
def make_host(cls, current_user, new_host):
host, created = cls.objects.get_or_create(current_user=current_user)
host.users.add(new_host)
@classmethod
def lose_host(cls, current_user, new_host):
host, created = cls.objects.get_or_create(current_user=current_user)
host.users.remove(new_host)
class EventProfile(models.Model):
event = models.CharField(max_length=100)
greeting = models.CharField(max_length=100)
invitee = models.CharField(max_length=100)
description = models.CharField(max_length=100)
date = models.CharField(max_length=100)
start_time = models.CharField(max_length=100)
finish_time = models.CharField(max_length=100)
venue = models.CharField(max_length=100)
myguest = models.ForeignKey(MyGuest, related_name='add_myguest_profile', null=True)
host = models.ForeignKey(Host, related_name='add_host_profile')
def __str__(self):
return self.event
Views.py
def event_change_hosts(request, operation, pk):
new_host = User.objects.get(pk=pk)
if operation == 'add':
Host.make_host(request.user, new_host)
return redirect('events:event_myguests_profile')
elif operation == 'remove':
Host.lose_host(request.user, new_host)
return redirect('events:event_hosts')
urls.py
url(r'^event_hosts/(?P<pk>\d+)$', views.event_hosts, name= 'event_hosts'),
url(r'^connect_hosts/(?P<operation>.+)/(?P<pk>\d+)/$', views.event_change_hosts, name= 'event_change_hosts'),
template.py
{% for host in hosts %}
<div class="alert alert-info" role="alert">
<a href="{% url 'accounts:profile_with_pk' pk=user.pk %}" type="button"
class="btn btn-primary left"
class="btn btn-default btn-lg active">{{ host.username }}
<a href="{% url 'events:event_change_hosts' operation='remove' pk=user.pk %}">
<button type="button" class="btn btn-danger pull-right btn-s">Remove</button>
</a>
</div>
{% endfor %}