简体   繁体   English

Django检查User.name是否已在数据库中-通过user.name而不是user.id进行匹配

[英]Django check to see if User.name is in database already — match via user.name rather than user.id

I have a simple personal Django project which allows someone to create a message by providing the username and message on the index page. 我有一个简单的个人Django项目,该项目允许某人通过在索引页面上提供用户名和消息来创建消息。 They can then see all the messages by a given user through that link in the database. 然后,他们可以通过数据库中的链接查看给定用户的所有消息。 Ideally, a guest would type their username and message and if the username is not in the database, it gets created and the message gets saved. 理想情况下,访客将键入其用户名和消息,如果用户名不在数据库中,则会创建该用户名并保存消息。 However, if it is in the database, that message is linked with that existing username and when I view all messages by the user, the old ones and the current one should show up. 但是,如果它在数据库中,则该消息将与该现有用户名链接,当我查看该用户的所有消息时,应该显示旧消息和当前消息。

The issue I'm facing right now is that I am unable to find and link the current message to an exisiting username. 我现在面临的问题是我无法找到当前消息并将其链接到现有的用户名。 For example 例如

User: Josh
Message: Hello World

User: Josh
Message: Second time.

Both user's have separate ID's in the database thus when I view messages from 'Josh', it only gives me one or the other. 两个用户在数据库中都有单独的ID,因此当我查看来自“ Josh”的消息时,它只会给我一个或另一个。 I want them to link up the second time Josh is typed in so that when I view Josh, all messages show up. 我希望他们在第二次输入Josh时进行链接,以便在查看Josh时显示所有消息。 Essentially, how do I match them via User.name rather than User.id?

Models 楷模

class User (models.Model):
    name = models.CharField(max_length=20)

    def __unicode__(self):              
        return self.name

class Message (models.Model):
    content = models.TextField(max_length=140)
    user = models.ForeignKey(User)
    time = models.DateTimeField()

    def __unicode__(self):              
        return self.content

views.py views.py

def index (request):
    if request.method == 'POST':
        u = User(name=request.POST.get('user'))
        u.save()
        m = Message(content=request.POST.get('message'), user = u)
        m.save()
        return render_to_response('index.html', {
                'user': u,
                'message': m,
                }, RequestContext(request))
    else:
        u = User()
        m = Message()
        return render_to_response('index.html', {
                'user': u,
                'message': m,
                }, RequestContext(request))

def view_messages(request, user_name=None):
    if user_name:
        user = get_object_or_404(User,pk=user_name)
        return render_to_response('messages.html', {
            'user': user,
            'messages': Message.objects.filter(user=user)
            })
    else:
        return render_to_response('messages.html', {
            'messages': Message.objects.all(),
            })

index.html index.html

<form action="{% url 'index' %}" id="user_form" method = "POST">
{% csrf_token %}
<input type="text" name="user" id="user" maxlength="20" placeholder="Username" onblur="return validUser(this)">
<br>
<br>
<textarea rows="4" cols="35" name="message"  id="message" maxlength="140" placeholder="Message goes here" onblur="return validMessage(this)"></textarea><br>
<input type="submit" value="Submit" onclick="return finalCheck()">
</form>

Thank you! 谢谢!

You have to set the primary_key=True parameter while defining the class member. 定义类成员时,必须设置primary_key=True参数。 Otherwise, Django adds an automatic ID field as explained here . 否则,Django的增加所解释的自动ID字段这里

Try this for your Model class: 为您的Model类尝试以下操作:

class User (models.Model):
    name = models.CharField(max_length=20, primary_key=True)

    def __unicode__(self):
        return self.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM