我想在django admin中建立用户(管理员)之间的小型电子邮件应用程序我成功地让用户发送和接收消息,在下一步中:用户应该能够回复收到的消息。 只是我添加了一个"回复"用indox格式的按钮将其重定向到发件箱表单,现在的问题是如何在请求中添加to:mail?
我的 model.py
class Mail(models.Model):
from_user = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('From User'),
related_name='sent_mails')
to_user = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('To User'),
related_name='recieved_mails')
subject = models.CharField(_('Subject'), max_length=255)
body = models.TextField(_('Body'))
read = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
last_update = models.DateTimeField(auto_now=True)
admin.py
class Inbox(Mail):
class Meta:
app_label = 'internal_mails'
proxy = True
verbose_name = _("Inbox")
verbose_name_plural = _("Inbox")
class Outbox(Mail):
class Meta:
app_label = 'internal_mails'
proxy = True
verbose_name = _("Outbox")
verbose_name_plural = _("Outbox")
class InboxAdmin(MailAdmin):
list_display = ('id', 'from_user', 'subject',)
exclude = ('read',)
def get_queryset(self, request):
queryset = super(InboxAdmin, self).get_queryset(request)
return queryset.filter(to_user=request.user)
def has_add_permission(self, request, obj=None):
return False
def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
response = super(InboxAdmin, self).changeform_view(
request, object_id=object_id,
form_url=form_url, extra_context=extra_context
)
if isinstance(response, HttpResponseRedirect):
obj = Mail.objects.get(id=object_id)
print(obj.from_user)
response = HttpResponseRedirect('/'.join(response.url.split('/')[:-2] + ['outbox/add/']))
else:
obj = Inbox.objects.get(id=object_id)
obj.read = True
obj.save()
return response
class OutboxAdmin(MailAdmin):
list_display = ('id', 'to_user', 'subject',)
list_filter = ('to_user',)
exclude = ('from_user', 'read',)
def get_queryset(self, request):
queryset = super(OutboxAdmin, self).get_queryset(request)
return queryset.filter(from_user=request.user)
def save_model(self, request, obj, form, change):
obj.from_user = request.user
obj.save()
admin.site.register(Inbox, InboxAdmin)
admin.site.register(Outbox, OutboxAdmin)
答案 0 :(得分:1)
这里是我如何解决我在url Ex中发送用户id的问题: 127.0.0.1:8000/en/outbox/add/?to_user=1
点击回复按钮时,会重定向到具有用户ID
的发件箱 InboxAdmin 类中的
if isinstance(response, HttpResponseRedirect):
obj = Mail.objects.get(id=object_id)
url = reverse("admin:internal_mails_outbox_add")
return HttpResponseRedirect(url + "?to_user=" + str(obj.from_user.id))
另外请注意,如果您需要知道如何在Django-admin中反转URL,则可能需要阅读此内容 https://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls