将Django表单数据保存到用户

时间:2019-02-12 00:40:57

标签: python django django-models django-forms django-views

我正在创建一个用于一般教育用途的网站,其中一个功能是日历部分,我希望用户能够存储他们的事件,但是当他们登录时,他们可以查看他们创建的事件。这是用于学术任务。

我似乎无法使该日历链接到用户字段。我希望日历表中的每个记录都有一个user_id,它将与current_user相同。我知道您可以使用django默认用户auth,但是由于不了解它而我还没有这样做,到我意识到它来不及了。

因此,我真正需要做的就是在表单有效时,将current_user id的值分配为日历表中学生的值。但是由于某些原因,我一直遇到问题,并且该表单没有被检测为有效表单,或者该程序只是未分配该值。

我的主要目标是让每个用户查看自己的日历。我不介意将当前的学生字段更改为外键字段

Student.Views

def calendar(request):

student_obj = Student.objects.get(student_name=current_user)
print(student_obj)


if request.method == 'POST':
    form = EventsForm(initial={'student': '3'} or request.POST)
    print(form.errors)

    if form.is_valid():
        form.save()
        all_events = Events.objects.filter(student=student_obj.id)
        messages.success(request, 'Event Has Been Added')
        return render(request, 'Student/calendar.html', {'all_events': all_events})

    else:
        messages.success(request, 'Event Has NOT Been Added')
        all_events = Events.objects.filter(student=student_obj.id)
        return render(request, 'Student/calendar.html', {'all_events': all_events})

学生模型

class Student(models.Model):
     student_name = models.CharField(max_length=59, default=None)
     username = models.CharField(max_length=59)
     password = models.CharField(max_length=59)
     age = models.PositiveIntegerField()
     date_of_birth = models.DateField(max_length=10)
     form = models.CharField(max_length=3)
     email = models.EmailField(max_length=59)
     present = models.PositiveIntegerField(default=0)
     late = models.PositiveIntegerField(default=0)
     absent = models.PositiveIntegerField(default=0) 
     maths_grade = models.PositiveIntegerField(default=0)
     english_grade = models.PositiveIntegerField(default=0)
     science_grade = models.PositiveIntegerField(default=0)
     behaviour_level = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.student_name

class Events(models.Model):
    student = models.CharField(max_length=200)
    date = models.DateField(max_length=10, default=None)
    event = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)

学生表格

class EventsForm(forms.ModelForm):
    class Meta:
        model = Events
        fields = ["event", "completed", "date", "student"]

日历模板

<div class="container" style="color: #fff">
<br/>
{% if messages %}
    {% for message in messages %}

        <div class="alert alert-warning alert-dismissible" roles="alert">
            <button class="close" data-dismiss="alert">
                <small>x</small>
            </button>
            {{ message }}
        </div>

    {% endfor %}
{% endif %}

{% if all_events %}
<div>
<table class="table table-dark table-bordered">

        {% for things in all_events %}


        {% if things.completed %}
            <style>
                .striker {
                    text-decoration: line-through;
                    text-color: black;
                }
            </style>
            <tr class="table-danger striker">
                <td style="color: black">{{ things.date }}</td>
                <td><a href="{% url 'edit' things.id %}", style="color: black">{{ things.event }}</a></td>
                <td><center><a href="{% url 'delete' things.id %}", style="color: black">Delete</a></center></td>
            </tr>

        {% else %}

            <tr>
                <td>{{ things.date }}</td>
                <td ><a href="{% url 'edit' things.id %}", style="color: white">{{ things.event }}</a></td>
                <td><center><a href="{% url 'delete' things.id %}", style="color: white">Delete</a></center></td>
            </tr>

        {% endif %}

        {% endfor %}


</table>
</div>
{% endif %}

2 个答案:

答案 0 :(得分:0)

将form.save()更改为

event = form.save(commit=False)
event.student = request.user
event.save()

那样就可以了。

答案 1 :(得分:0)

不要让它变得复杂,这必须更容易。 如果我了解您要做什么,我将按照以下方式创建模型:

在此处更新

#model.py

from django.db.models.signals import post_save
from django.dispatch import receiver

class Student(models.Model):
    user= models.OneToOneField(User, null=True) #student is user
    #Define student fields...

class Calendar(models.Model):
    #Defile calender fields here along with its default values ...
    user = models.OneToOneField(Student)

'''
this signal populate calender table with  user_id along with its 
calender fields 
'''     
@receiver(post_save, sender=Student)
def create_student_calender(sender, instance, created, **kwargs):
   if created and not kwargs.get('raw', False):
        calendar = Calender(user=instance)
        calendar.save()



class Event(models.Model):
   calender  = models.ForeignKey(Callender, null=True)
   # Define  event fields here ...

使用这样的模型结构,每当学生创建帐户时,日历模型就会被填充并保存日历字段和学生的ID字段。

那么学生如何创建活动?只需创建一个inlineformset_factory表单即可在每个学生的日历上创建事件,如下所示:

#form.py 

from django.forms import inlineformset_factory
from django import forms

class EventForm(forms.ModelForm):
    #Events form fields here...

    class Meta:
        model  = Event
        fields = ["Event's field"]



EventFormSet = inlineformset_factory(Calender, Event, form=EventForm, 
                                      max_num=1, can_delete=False)

将此表单集呈现给学生以创建其事件的视图,该表单集自动将学生的事件与日历相关联。

因此,您可以添加逻辑以执行更多操作。

希望您能了解如何解决此问题