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!

1 Answer 1

-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
12
  • 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/<user_id> Feb 4, 2014 at 3: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 4, 2014 at 3: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<user_name>\\d+)?/'] " Feb 4, 2014 at 3:35
  • Added view_messages to the original post Feb 4, 2014 at 3:36
  • The new error has something to do with the url rule in your urls.py, not the view definition.
    – shaktimaan
    Feb 4, 2014 at 3:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.