我想建立一个网站,用户可以使用Django相互发送单词。当用户删除单词时,该单词将仅为该用户删除。我有一个工作网站;唯一的问题是当一个单词被删除时,它将被删除给所有用户。我该如何解决这个问题,这是一个与ManyToMany关系有关的问题吗?
Django单词模型:
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
class Word(models.Model):
definition = models.CharField(max_length=350)
turkish = models.CharField(max_length=50)
english = models.CharField(max_length=50)
users = models.ManyToManyField(User)
creator = models.CharField(max_length=50)
def __str__(self):
return self.english
def summary(self):
return self.definition[:50] + "..."
共享视图功能:
@login_required
def send(request):
users_list = User.objects.all().exclude(username=request.user.username)
user = request.user
small = user.username.title()
send_to_str = request.POST['user']
sent_word_str = request.POST['word']
send_to = User.objects.get(username=send_to_str)
sent_word = Word.objects.get(id=sent_word_str)
if not users_list:
sendmessage = 'You have no friends'
else:
sendmessage = ''
sent_word.users.add(send_to)
words = Word.objects.filter(users=user).order_by('-english')
return render(request, 'intro.html', {'sendmessage': sendmessage, 'words': words, 'small' : small})
删除视图功能:
@login_required
def delete(request):
if request.method == 'POST':
current_id = request.POST['word_id']
current_word = Word.objects.get(id=current_id)
current_word.delete()
messages.add_message(request, messages.INFO, 'Succesfully deleted.')
return redirect('translater:home')
else:
return render(request, 'intro.html', {'message': 'there is a problem'})
重定向到此html:
{% if words %}
<h3 style="color:gray;font-weight:bold">My Word List</h3>
<br>
{% endif %}
{% for word in words %}
<h4 style="color:red">{{ word.english }} / {{ word.turkish }} </h4>
<h4 style="color:green">{{ word.summary }} / {{ word.creator }}</h4>
<br>
<button type="button" onClick="document.getElementById('deleterForm').submit()" class="btn btn-warning">Delete!</button>
<button type="button" onClick="document.getElementById('sharerForm').submit()" class="btn btn-primary">Share!!</button>
<form id="deleterForm" action="{% url 'translater:delete' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="word_id" value="{{ word.id }}">
</form>
<br>
<form id="sharerForm" action="{% url 'translater:share' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="word_id" value="{{ word.id }}">
</form>
<form id="senderForm{{ word.id }}" action="{% url 'translater:send' %}" method="POST">
{% csrf_token %}
{% for user in users_list %}
<input type="submit" name="user" value="{{ user }}">
<input type="hidden" name="word" value="{{ word.id }}">
{% endfor %}
{{ sendmessage }}
</form>
<br>
{% endfor %}