Django - 注册网站用户和非站点用户如何使用模型? [英] Django - how to have models for registered site users and non-site users?

查看:172
本文介绍了Django - 注册网站用户和非站点用户如何使用模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旅行模型,可以让许多参与者订阅一个给定的旅行和一个所有者。参与者是在网站上注册的用户,但我也希望能够将离线用户添加到旅行中,在网站上没有帐户的用户,以便跟踪所有用户。
所有者和参与者链接到Userena用户个人资料(旁边的问题:可能直接链接到用户会更好吗?但是如何获得full_name看作为选择然后在内联管理员?)

I have a Trip model which can have many participants subscribed for a given trip and one owner. The participans are users registered on the site, but I also want to be able to add 'offline' users to the trip, users who do not have accounts on the site, so that I could keep track of all the users coming. The owner and participatns are linked to Userena user profile (side question: maybe linking directly to User would be better? But how would I get full_name to see as selection in inline admin then?)

class Trip(models.Model):
    name = models.CharField('trip name', max_length=200)
    type = models.ForeignKey(Category, related_name='categories')
    .
    .
    .
    slug = models.SlugField('trip slug', max_length=100)
    owner = models.ForeignKey(UserProfile, related_name='owner')
    participants = models.ManyToManyField(UserProfile, blank=True, null=True, related_name='participants')
    is_public = models.BooleanField("is visible?",db_index=True)

class ParticipationInline(admin.TabularInline):
    model = Trip.participants.through
    extra = 3

class TripAdmin(admin.ModelAdmin):

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name in ('desc',):
            return db_field.formfield(widget=TinyMCE(
                attrs={'cols': 100, 'rows': 20},
                mce_attrs={'external_link_list_url': reverse('tinymce.views.flatpages_link_list')},
            ))
        return super(TripAdmin, self).formfield_for_dbfield(db_field, **kwargs)
    inlines = [
        ParticipationInline,
        ]
    exclude = ('participants',)
    prepopulated_fields = {"slug": ("name",)}
    list_display = ('name', 'type', 'date', 'dest','owner', 'is_public')
    list_filter = ['date', 'type']
    search_fields = ['name', 'dest', 'desc']
    date_hierarchy = 'date'

    class Media:
        js = ('js/tiny_mce/tiny_mce.js',
              'js/tiny_mce/textareas.js',)


admin.site.register(Trip, TripAdmin)

所以当我通过管理界面添加旅行时,我想先从现有的注册用户中选择一个参与者,如果我没有在那里找到它,希望能够内联添加新的离线参与者。实现这一点的最佳方式是什么?

So when I add a Trip through Admin interface I want to first select a participant from existing registered users, and if I don't find them there, I want to be able to inline add a new 'offline' participant. What would be the best way to achieve this?


  1. 有两个配置文件从我的 UserProfile

  2. 为离线用户单独设置一个模型,并在旅行中使用两个ManyToMany关系


修改后,Hedde的评论。

Edit after Hedde's comment.

根据GenericRelation的建议,我创建了 OfflineUser 到我的旅行

I created OfflineUser as suggested with GenericRelation to my Trip:

class OfflineUser(models.Model):
    first_name = models.CharField(_('first'), max_length=30)
    last_name = models.CharField(_('last'), max_length=30)
    ...
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey("content_type", "object_id")    

class Trip(models.Model):
    ...
    owner = models.ForeignKey(UserProfile, related_name='owner')
    participants = models.ManyToManyField(UserProfile, blank=True, null=True, related_name='participants')
    offline_users = generic.GenericRelation(OfflineUser)

添加 OfflineUserInline 我可以添加注册用户和离线用户到我的旅行
然后我可以列出这两种类型的旅行参与者:

and after adding OfflineUserInline I am able to add registered users and offline users to my Trip! I can then list the Trip participants of both types like this:

{% if request.user.is_staff %}
        <ul>
            {% for participants in object.participants.all %}
                <li> {{ participants.full_name }}
                </li>
            {% empty %}
                No registered users!
            {% endfor %}
            {% for participants in object.offline_users.all %}
                <li> {{ participants.full_name }}
                </li>
            {% empty %}
                No offline users!
            {% endfor %}
        </ul>
{% endif %}

所以它适用于一个点,现在我有一个奇怪感觉我没有完全了解Hedde的答案...

So it works to a point and now I have a strange feeling that I did not completely understood Hedde's answer...

每次我想与参与者做一些事情(计数,列出他们等)我将需要做那两次?

Everytime I want to do something with the participants (count them, list them, etc) I will need to do that twice?

推荐答案

使用 contenttypes框架可以使这更容易。您可以从管理员和清洁表单中过滤/隐藏内容类型,或在需要时覆盖保存。对于离线参与者,我不会创建一个配置文件,而是模仿,例如:

Using the contenttypes framework could make this easier. You can filter/hide contenttypes from the admin and clean forms or override saves where needed. For the 'offline' participants I wouldn't create a profile, but mimic, e.g.:

class OfflineUser(models.Model):
    first_name = models.CharField(_('first name'), max_length=30)
    last_name = models.CharField(_('last name'), max_length=30)
    email = models.EmailField(_('e-mail address'))
    # field extensions
    ... = generic.GenericRelation(...)

    def get_profile(self):
        pass

    def get_full_name(self):
        """
        Add some default User methods so you can call them on
        the related_object without raising attribute errors
        """
        full_name = u'%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

现在您可以执行以下操作:

Now you can do things like:

{{ some_model.content_object.get_profile.get_full_name }}

有很多st ackoverflow和google结果可以帮助您,例如

There are plenty of stackoverflow and google results to help you out, e.g.

通用多对多关系

这篇关于Django - 注册网站用户和非站点用户如何使用模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆