django模型的外部动态内联默认值 [英] django model inline dynamic default value for foreignKey

查看:107
本文介绍了django模型的外部动态内联默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在models.py中有这3个模型。

I have these 3 models in models.py

class Customer(models.Model):
    name = models.CharField(max_length=50)
    ....

class Agent(django.contrib.auth.models.User):
    regions = models.CharField(max_length=50, choices={...})
    ....

class Payment(models.Model):
    added_by = models.ForeignKey(Agent)
    customer = models.ForeignKey(Customer)
    date = models.DateField(default=datetime.date.today())
    amount = models.IntegerField(default=0)

,在我的admin.py中,我也有以下类:

and also in my admin.py, I have these classes:

class PaymentInline(admin.TabularInline):
     model = Payment
     extra = 0

class CustomerAdmin(admin.ModelAdmin):
    inlines = [PaymentInline,]

问题1:
是否可能有代理商字段预先设置为客户更改页面付款在线中当前登录的代理商。
我们可以为agent字段预设值,就像django对客户字段所做的方式一样,该值已经隐藏在行内。

Question#1: is it possible to have the 'agent' field pre-set to the current logged in Agent in 'PaymentInline' in Customer change page. we can preset the value for the agent field, just like the way that django does for 'Customer' field, which is hidden from the inline already.

问题2:
还是有一种构造链接的方法,其中url中的customer_id和agent_id是硬编码的;并且在添加付款页面中,我们可以为客户字段和代理商字段
提供默认值和不可编辑的值,例如,此URL [1]的
会将我们链接到常规添加页面,但是customer_field和agent_feild设置为Agent.objects.get(id = 1)和Customer.objects.get(id = 1)。 (或者我们可以隐藏这两个字段,因为它们还是不可编辑的)

Question#2: or is there a way to construct a link, with the customer_id and agent_id "hardcoded" in the url; and in the add payment page, we could have the default and non-editable values for customer field and agent field for example, this url[1] will link us to the normal add page, but with the customer_field and agent_feild set to Agent.objects.get(id=1) and Customer.objects.get(id=1). (Or we can hide these 2 fields since they are non-editable anyway)

[1] http:// localhost:8000 / admin / my_app / payment / add / ?customer_id = 1& agent_id = 1

[1]http://localhost:8000/admin/my_app/payment/add/?customer_id=1&agent_id=1

有什么想法吗?

谢谢

Max

推荐答案

Q1:
我的猜测是编辑内联模板,隐藏代理列,并将其默认设置为登录用户。
Q2:
GET参数默认情况下传递给表单。
如果您想使某些字段不可编辑,我认为您需要更改模板以检查这些参数是否存在,然后隐藏(或不隐藏)这些字段。或者,您可以将不同的形式传递给ModelAdmin视图(同样在检查是否存在GET选项之后)。

Q1: My guess would be to edit the inline template, hide the Agent column and set it by default to the logged in user. Q2: GET arguments are passed to the form by default. If you want to make some fields not non-editable I think you need to alter the template to check for presence of those arguments and then hide the fields (or not). Alternatively you could pass different form to the ModelAdmin view (also after checking for the presence of GET options).

Tomus

这篇关于django模型的外部动态内联默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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