简体   繁体   中英

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. 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. I want them to link up the second time Josh is typed in so that when I view Josh, all messages show up. 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

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

<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. Otherwise, Django adds an automatic ID field as explained here .

Try this for your Model class:

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

    def __unicode__(self):
        return self.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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