author = models.ForeignKey('auth.User',null = True,blank = False)麻烦

时间:2021-07-17 18:05:26

I have a table where I save data(description, x, y, result and creation date) and until now everything works. I thought then to add a column with the author for each saved line eg:

我有一个表,我保存数据(描述,x,y,结果和创建日期),直到现在一切正常。我当时想为每个保存的行添加一个作者列,例如:

DES| X | Y | RESULT |CREATION DATE| AUTHOR |

DES | X | Y |结果|创建日期|作者|

hi | 3| 1 |   4    |  24/02/2015     | username |

then I added in models.py auth:

然后我在models.py auth中添加了:

from django.db import models
from django.utils import timezone
from simpleapp.oper import add_divide
from django.conf import settings


class ElementiTab(models.Model):
    author = models.ForeignKey('auth.User', null=True, blank=False)
    des = models.CharField(max_length=30)
    x = models.FloatField()
    y = models.FloatField()
    res = models.FloatField(default=0)
    created_date = models.DateTimeField(default=timezone.now)

    def save(self, *args, **kwargs):
        self.res = add_divide(self.x, self.y)
        super(ElementiTab, self).save(*args, **kwargs)


    def __str__(self):
        return self.des

UPDATE:

更新:

forms.py

forms.py

from django import forms
from .models import ElementiTab

class  ElementiTabForm(forms.ModelForm):

    class Meta:
        model =  ElementiTab
        fields = ('des', 'x', 'y') 

views.py

views.py

@login_required
def tabval(request):
    # if this is a POST request we need to process the form data
    valori = ElementiTab.objects.filter().order_by('-created_date')
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = ElementiTabForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            form.save()

    # if a GET (or any other method) we'll create a blank form
    else:
        form = ElementiTabForm()

    return render(request, 'simpleapp/simpleapp.html', {'form': form, 'valori': valori})

@user_passes_test(lambda u: u.is_superuser)
def delete(request, id):
    valori_to_delete = get_object_or_404(ElementiTab, pk=id).delete()
    return redirect(tabval)

simpleapp.html

simpleapp.html

{% extends 'registration/base_reg.html' %}
    {% block title %}SimpleApp-tabval{% endblock %}
    {%block content%}       



             <h4>TABELLA CON DATI</h4>






<form action="/simpleapp/" method="post">
    {% csrf_token %}
    {{ form.as_table }}
    <input type="submit" value="LIST" />
  </form>
<form action="/simpleapp/" method="DELETE">
        {% csrf_token %}
        <input type="submit" name="canc" value="RESET" />
 </form>

  <br />
  <br />        

                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <tr class="info">
                            <td width="15%" align="center"> NOME</td>
                            <td width="15%" align="center"> X </td>
                            <td width="15%" align="center"> Y </td>
                            <td width="15%" align="center"> RISULTATO </td>
                            <td width="15%" align="center"> DATA CREAZIONE </td>
                            <td width="15%" align="center"> AUTORE </td>
                            {% for elementi in valori %}
                                <div class="elementi">
                                    <tr>

                                    <td>{{elementi.des}}</td> 
                                    <td>{{elementi.x}}</td>
                                    <td>{{elementi.y}}</td>
                                    <td>{{elementi.res}}</td>
                                    <td>{{elementi.created_date}}</td>
                                    <td>{{elementi.author}}</td>
                                    <td width="1%">
                                    {% if user.is_superuser %}
                                        <a href="/delete/{{elementi.id}}" class="btn btn-danger" role="button">Delete</a>
                                    {% else %}
                                    <a href="" class="btn btn-danger disabled" role="button"><span style='font-size: small'>Only Admin</span></a>
                                    {% endif %}
                                    </td>
                                </div>

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



{% endblock content %}

The fact is that the admin page displays a drop-down menu from which I (as administrator) can choose one of the registered user and so I add them both in the table of my app and in the db.

事实是,管理页面显示一个下拉菜单,我(作为管理员)可以从中选择一个注册用户,因此我将它们添加到我的应用程序表和数据库中。

How can I make this process automatic? I.e. after the login, you put data in the table and once saved the data, also the username is saved and should not be the administrator to set it.

如何自动完成此过程?即登录后,将数据放入表中,保存数据后,用户名也会保存,不应由管理员进行设置。

I searched a similar question here but I have not found one to help me to solve my problem.

我在这里搜索了一个类似的问题,但我没有找到一个帮助我解决我的问题。

1 个解决方案

#1


1  

I updated my answere, i misenderstood your question.

我更新了我的回答,我误解了你的问题。

Change this in your view

在您的视图中更改此设置

    if form.is_valid():
        # Creating the object without commiting to database
        obj = form.save(commit=False)
        # Setting the user from request
        obj.author = request.user
        # Commiting to the database
        obj.save()

#1


1  

I updated my answere, i misenderstood your question.

我更新了我的回答,我误解了你的问题。

Change this in your view

在您的视图中更改此设置

    if form.is_valid():
        # Creating the object without commiting to database
        obj = form.save(commit=False)
        # Setting the user from request
        obj.author = request.user
        # Commiting to the database
        obj.save()