我正在使用 Django Channels,我希望能够将其他字段与json
帖子的数据一起保存到数据库中。
我的模型中有一个外键,Postmie
它指向email
我的用户模型中的字段。Postmie
是负责将帖子保存到数据库的模型。外键创建一个名为 的字段email_id
。当我将帖子保存到数据库时,我还想获取发布帖子的用户的电子邮件并将其保存在数据库中。我该怎么做呢?我没有使用 Django 表单。
我的模型与此处Postmie
的 Django Channels 教程中的模型相同Post
,唯一的区别是我的模型有一个额外的外键指向我的用户模型中的电子邮件字段。
email=request.user.email
不起作用。我正在考虑将电子邮件放在隐藏字段中,但这对我来说似乎不安全。
我使用的方法实际上与此处 consumers.py
的 Django Channels 教程中的方法相同。一切正常,但我无法在数据库中输入其他字段以获取帖子。
def save_post(message, slug, request):
"""
Saves vew post to the database.
"""
post = json.loads(message['text'])['post']
email = request.user.email
feed = Feed.objects.get(slug=slug)
Postmie.objects.create(feed=feed, body=post email_id=email)
邮递模型:
@python_2_unicode_compatible
class Postmie(models.Model):
# Link back to the main blog.
feed = models.ForeignKey(Feed, related_name="postmie")
email = models.ForeignKey(Usermie,
to_field="email",
related_name="postmie_email", max_length=50)
subject = models.CharField(max_length=50)
classs = models.CharField(max_length=50, null=True, blank=True)
subclass = models.CharField(max_length=50, null=True, blank=True)
title = models.CharField(max_length=60, null=True, blank=True)
body = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return "#%i: %s" % (self.id, self.body_intro())
def post_email(self):
return self.email
def post_subject(self):
return self.subject
def post_datetime(self):
return self.datetime
def get_absolute_url(self):
"""
Returns the URL to view the liveblog.
"""
return "/feed/%s/" % self.slug
def body_intro(self):
"""
Short first part of the body to show in the admin or other compressed
views to give you some idea of what this is.
"""
return self.body[:50]
def html_body(self):
"""
Returns the rendered HTML body to show to browsers.
You could change this method to instead render using RST/Markdown,
or make it pass through HTML directly (but marked safe).
"""
return linebreaks_filter(self.body)
def send_notification(self):
"""
Sends a notification to everyone in our Liveblog's group with our
content.
"""
# Make the payload of the notification. We'll JSONify this, so it has
# to be simple types, which is why we handle the datetime here.
notification = {
"id": self.id,
"html": self.html_body(),
"date_created": self.date_created.strftime("%a %d %b %Y %H:%M"),
}
# Encode and send that message to the whole channels Group for our
# feed. Note how you can send to a channel or Group from any part
# of Django, not just inside a consumer.
Group(self.feed.group_name).send({
# WebSocket text frame, with JSON content
"text": json.dumps(notification),
})
def save(self, *args, **kwargs):
"""
Hooking send_notification into the save of the object as I'm not
the biggest fan of signals.
"""
result = super(Postmie, self).save(*args, **kwargs)
self.send_notification()
return result