所有用户共享相同创建的数据,如何修复它?

huangapple go评论155阅读模式
英文:

All users share the same data created, how do i fix it?

问题

我创建了一个程序,让用户在创建自己的帐户后,输入他们的开支以进行跟踪。但是,当我进行测试时,所有用户共享相同的表格。

例如:假设用户1将"租金:$2500"添加到表格中,但当我关闭该帐户并打开一个新帐户(用户2)时,我可以在页面上看到其他用户的开支。请帮帮我,我已经花了很多时间尝试解决它,但我无法解决。
提前感谢您的帮助。

Model:

class Customer(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

class Finance(models.Model):
    expenses_category = [
        ("Saving", "Saving"),
        ("Food", "Food"),
        ("Bills", "Bills"),
        ("Rent", "Rent"),
        ("Extra", "Extra"),
    ]

    expenses_month = [
        ("January", "January"),
        ("February", "February"),
        ("March", "March"),
        ("April", "April"),
        ("May", "May"),
        ("June", "June"),
        ("July", "July"),
        ("August", "August"),
        ("September", "September"),
        ("October", "October"),
        ("November", "November"),
        ("December", "December"),
    ]

    customer = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    category = models.CharField(choices=expenses_category, max_length=200)
    price = models.IntegerField()
    month = models.CharField(choices=expenses_month, max_length=200)

Views:

@csrf_exempt
def registerPage(request):
    if request.user.is_authenticated:
        return redirect('home')
    else:
        form = CreateUserForm()
        if request.method == 'POST':
            form = CreateUserForm(request.POST)
            if form.is_valid():
                user = form.save()
                username = form.cleaned_data.get('username')
                group = Group.objects.get(name='customer')
                user.groups.add(group)
                messages.success(request, 'Account was created for ' + username)
                return redirect('login')
        context = {'form': form}
        return render(request, 'app_finance/register.html', context)

def loginPage(request):
    username = None
    if request.user.is_authenticated:
        username = request.user.customer
        return redirect('home')
    else:
        if request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')
            else:
                messages.info(request, 'Username or password incorrect.')
        context = {}
        return render(request, 'app_finance/login.html', context)

def logoutUser(request):
    logout(request)
    return redirect('login')

def userPage(request):
    return render(request, 'app_finance/user.html')

@login_required(login_url='login')
def homeView(request):
    username = None
    items = Finance.objects.all()
    form = FinanceForm(initial={'customer': User})
    if request.method == 'POST':
        username = request.user.customer
        form = FinanceForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = FinanceForm()
    return render(request, 'app_finance/home.html', {'form': form, 'items': items})

Forms:

class CustomerForm(ModelForm):
    class Meta:
        model = Customer
        fields = '__all__'
        exclude = ['user']

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

class FinanceForm(ModelForm):
    class Meta:
        model = Finance
        fields = '__all__'

模板(home.html):

<div>
    <span>Hello, {{ request.user }}</span><br>
    <span><a class="hello-msg" href="{% url 'logout' %}">Logout</a></span>
</div>

<form action="" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

<br>
<div class="row">
    <div class="col-md">
        <div class="card card-body">
            <h1>Expenses</h1>
        </div>
        <div class="card card-body">
            <table class="table">
                <tr>
                    <th>User</th>
                    <th>Category</th>
                    <th>Price</th>
                    <th>Month</th>
                </tr>
                {% for i in items %}
                    <tr>
                        <td>{{ i.customer }}</td>
                        <td>{{ i.category }}</td>
                        <td>{{ i.price }}</td>
                        <td>{{ i.month }}</td>
                        <td>&nbsp;&nbsp;</td>
                        <td><a class="btn btn-sm btn-info" href="">Update</a></td>
                        <td><a class="btn btn-sm btn-danger" href="">Delete</a></td>
                    </tr>
                {% endfor %}
            </table>
        </div>
    </div>
</div>
英文:

I made a program where users put their expenses to keep track of them, after they create their own account. But when i test it, all users share the same table.

Ex: Lets say user 1, add to the table "Rent: $2500", but when i close that account and open a new one (User 2), i can see the expenses of the other Users in the page. Please help me, I've been putting a lot of time trying to solve it but i cant.
Thanks in advance

Model:


class Customer(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True,blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
# def __str__(self):
# 	return self.name       (i don&#39;t now if it&#39;s correct)
class Finance(models.Model):
expenses_category = [
(&quot;Saving&quot;, &quot;Saving&quot;),
(&quot;Food&quot;, &quot;Food&quot;),
(&quot;Bills&quot;, &quot;Bills&quot;),
(&quot;Rent&quot;, &quot;Rent&quot;),
(&quot;Extra&quot;, &quot;Extra&quot;),
]
expenses_month = [
(&quot;January&quot;, &quot;January&quot;),
(&quot;February&quot;, &quot;February&quot;),
(&quot;March&quot;, &quot;March&quot;),
(&quot;April&quot;, &quot;April&quot;),
(&quot;May&quot;, &quot;May&quot;),
(&quot;June&quot;, &quot;June&quot;),
(&quot;July&quot;, &quot;July&quot;),
(&quot;August&quot;, &quot;August&quot;),
(&quot;September&quot;, &quot;September&quot;),
(&quot;October&quot;, &quot;October&quot;),
(&quot;November&quot;, &quot;November&quot;),
(&quot;December&quot;, &quot;December&quot;),
]
customer = models.ForeignKey(User, on_delete=models.CASCADE, null=True,blank=True)
category = models.CharField(choices=expenses_category, max_length=200)
price = models.IntegerField()
month = models.CharField(choices=expenses_month, max_length=200)

Views:

@csrf_exempt
def registerPage(request):
if request.user.is_authenticated:
return redirect(&#39;home&#39;)
else:
form = CreateUserForm()	
if request.method == &#39;POST&#39;:
form = CreateUserForm(request.POST)
if form.is_valid():
# form.instance.user = request.user
user = form.save()
username = form.cleaned_data.get(&#39;username&#39;)
group = Group.objects.get(name=&#39;customer&#39;)
user.groups.add(group)
messages.success(request, &#39;Account was created for &#39;+ username)
return redirect(&#39;login&#39;)
context = {&#39;form&#39;:form}
return render(request, &#39;app_finance/register.html&#39;, context)
def loginPage(request):
username = None
if request.user.is_authenticated:
username = request.user.customer
return redirect(&#39;home&#39;)
else:
if request.method == &#39;POST&#39;:
username = request.POST.get(&#39;username&#39;)
password = request.POST.get(&#39;password&#39;)
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect(&#39;home&#39;)
else:
messages.info(request, &#39;Username or password incorrect.&#39;)
context = {}
return render(request, &#39;app_finance/login.html&#39;, context)
def logoutUser(request):
logout(request)
return redirect(&#39;login&#39;)
def userPage(request):
return render(request, &#39;app_finance/user.html&#39;)
@login_required(login_url=&#39;login&#39;)
def homeView(request):
# customer = Customer.objects.get(id=pk) (not sure#)
username = None
items = Finance.objects.all()
form = FinanceForm(initial={&#39;customer&#39;:User})
if request.method == &#39;POST&#39;:
username = request.user.customer
form = FinanceForm(request.POST) # initial={&#39;customer&#39;:user}
if form.is_valid():
form.save()
return HttpResponseRedirect(&#39;/&#39;)
else:
form = FinanceForm()
return render(request, &#39;app_finance/home.html&#39;, {&#39;form&#39;: form,&#39;items&#39;:items}) 

Forms:

    class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = &#39;__all__&#39;
exclude = \[&#39;user&#39;\]
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = [&#39;username&#39;, &#39;email&#39;, &#39;password1&#39;, &#39;password2&#39;]
class FinanceForm(ModelForm):
class Meta:
model = Finance
fields = &#39;__all__&#39;

Template (home.html)


&lt;div&gt;
&lt;span&gt;Hello, {{request.user}}&lt;/span&gt; &lt;br&gt;
&lt;span&gt;&lt;a class=&quot;hello-msg&quot; href=&quot;{% url &#39;logout&#39; %}&quot;&gt;Logout&lt;/a&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;form action=&quot;&quot; method=&quot;post&quot;&gt;
{% csrf_token %}
{{ form }}
&lt;!-- {{ form }} --&gt;
&lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
&lt;/form&gt;
&lt;br&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-md&quot;&gt;
&lt;div class=&quot;card card-body&quot;&gt;
&lt;h1&gt;Expenses&lt;/h1&gt;                   
&lt;/div&gt;  
&lt;div class=&quot;card card-body&quot;&gt;
&lt;table class=&quot;table&quot;&gt;
&lt;tr&gt;
&lt;th&gt;User&lt;/th&gt;
&lt;th&gt;Category&lt;/th&gt;
&lt;th&gt;Price&lt;/th&gt;
&lt;th&gt;Month&lt;/th&gt;
&lt;/tr&gt;
{% for i in items %}
&lt;tr&gt;
&lt;td&gt;{{i.customer}}&lt;/td&gt;
&lt;td&gt;{{i.category}}&lt;/td&gt;
&lt;td&gt;{{i.price}}&lt;/td&gt;
&lt;td&gt;{{i.month}}&lt;/td&gt;
&lt;td&gt;&amp;nbsp&amp;nbsp&lt;/td&gt;         &lt;!--add in css --&gt;
&lt;td&gt;&lt;a class=&quot;btn btn-sm btn-info&quot; href=&quot;&quot;&gt;Update&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;a class=&quot;btn btn-sm btn-danger&quot; href=&quot;&quot;&gt;Delete&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
{% endfor %}
&lt;/table&gt;                                    
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

I tried changing the views' queries but i failed, also modifying the model.

答案1

得分: 0

你正在获取```Finance```模型的所有对象并将它们发送到你的模板中你需要根据当前用户进行筛选尝试在```homeView```的代码中修复这个问题

```python
@login_required(login_url='login')
def homeView(request):
    # customer = Customer.objects.get(id=pk)(不确定#)
    username = None
    items = Finance.objects.filter(customer_id=request.user.id) # ----> 根据当前用户更改这里
    form = FinanceForm(initial={'customer':User})
    if request.method == 'POST':
        username = request.user.customer
        form = FinanceForm(request.POST) # initial={'customer':user}
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = FinanceForm()
        return render(request, 'app_finance/home.html', {'form': form, 'items':items}) 

<details>
<summary>英文:</summary>
You are taking all the objects of ```Finance``` model and sending them to your template. You need to filter it as per the current user. Try fixing this in your code of ```homeView```.

@login_required(login_url='login')
def homeView(request):
# customer = Customer.objects.get(id=pk) (not sure#)
username = None
items = Finance.objects.filter(customer_id=request.user.id) # ----> change this as per current user
form = FinanceForm(initial={'customer':User})
if request.method == 'POST':
username = request.user.customer
form = FinanceForm(request.POST) # initial={'customer':user}
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = FinanceForm()
return render(request, 'app_finance/home.html', {'form': form,'items':items})


</details>

huangapple
  • 本文由 发表于 2023年6月1日 06:24:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377655.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定