英文:
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> </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't now if it's correct)
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():
# form.instance.user = request.user
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):
# customer = Customer.objects.get(id=pk) (not sure#)
username = None
items = Finance.objects.all()
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})
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__'
Template (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 }}
<!-- {{ 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> <!--add in css -->
<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 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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论