0

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!

user1530318
  • 25,507
  • 15
  • 37
  • 48

1 Answers1

-1

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
shaktimaan
  • 11,962
  • 2
  • 29
  • 33
  • When I do this and attempt to view a user's messages, it shows me all user messages now. How should I attempt to grab the user content? Before this it was done as /messages/ – user1530318 Feb 04 '14 at 03:24
  • It would depend on how your `view_tweets` method is defined. I am assuming the lookup earlier would be using the id. Now, it has to be with the user name. – shaktimaan Feb 04 '14 at 03:31
  • Right, so I tried it with replacing user_id to user_name but now am receiving a NoReverseMatch Error "Reverrse for 'messages' with arguments '(u'josh',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['messages/(?P\\d+)?/'] " – user1530318 Feb 04 '14 at 03:35
  • Added view_messages to the original post – user1530318 Feb 04 '14 at 03:36
  • The new error has something to do with the url rule in your urls.py, not the view definition. – shaktimaan Feb 04 '14 at 03:39
  • Right, for some reason it won't go to /messages/josh and display his tweets whereas /messages/1 would have worked, if that makes sense. – user1530318 Feb 04 '14 at 03:41
  • url(r'^messages/(?P\d+)?/', views.view_messages, name='messages'), – user1530318 Feb 04 '14 at 03:42
  • in the html file, the values are being passed in like this {{ user.name }} – user1530318 Feb 04 '14 at 03:43
  • I think this post - http://stackoverflow.com/questions/1842389/reverse-for-with-arguments-and-keyword-arguments-not-found discusses about reasons for NoReverseMatch error – shaktimaan Feb 04 '14 at 03:46
  • Nothing =/. Literally all I did was set the primary key and change the user_id fields to user_name and it's giving me this error. – user1530318 Feb 04 '14 at 03:55
  • I'm guessing its the syntax...It's trying to pass in '(u'josh',)' but is expecting just the name? – user1530318 Feb 04 '14 at 04:02
  • Can the downvoter please explain the reason for the downvote? – shaktimaan Feb 04 '14 at 17:07