默认设置用户ID为只读

时间:2018-07-24 03:51:25

标签: python foreign-keys django-class-based-views django-users

我已经查看了几篇文章,并尝试了一些变体,但无法将当前登录的用户ID缺省设置为外键,无法自动显示在我的模板中,并且字段已锁定,因此值不能被改变。

现在页面显示正常;但是,用户ID字段为空白,并且在下拉菜单中显示了所有用户,因此可以选择任何用户。我尝试使用templatetag设置readonly属性,但是由于该字段不在表单中,因此我收到一个错误,因为没有'as_widget'属性。

这是模特 ...

from django.contrib.auth import get_user_model
User = get_user_model()

class Tracking_Who(models.Model):
    user_id = models.ForeignKey(User, related_name='tracking_who_user_list', on_delete=models.CASCADE)
    name = models.CharField(max_length=60)
    height = models.CharField(max_length=15, blank=True)
    weight = models.CharField(max_length=15, blank=True)
    picture_upload = models.FileField(upload_to='tracking_who', blank=True)

    class Meta:
        unique_together=('user_id','name')

    # needed for redirect on updates
    def get_absolute_url(self):
        return reverse("tracking_health_app:details_tracking_who",kwargs={'pk':self.pk})

    def __str__(self):
        return 'User_id: ' + str(self.user_id) + '| Who: ' + str(self.name)

这是CBV

class TrackingWhoCreateView(LoginRequiredMixin, CreateView):
    template_name = 'tracking_health/create_tracking_who.html'
    model = Tracking_Who
    fields = '__all__' #['user_id','name','height','weight','picture_upload']
    success_url = reverse_lazy("tracking_health_app:all_tracking_who")

这是模板

{% extends "base.html" %}
{% load staticfiles %}
{% load bootstrap3 %}
{% load tracking_health_templatetags %}

{% block content %}

<h1>Create a new Person or Animal to track!</h1>

<form method="POST" id="TrackingWhoForm">

  {% csrf_token %}
  {% bootstrap_form form %}

  <input type="submit" class="btn btn-primary btn-large" value="Create">
</form>

{% endblock %}

任何帮助将不胜感激!

0 个答案:

没有答案