Reputation: 27757
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.
The issue I'm facing right now is a
NoReverseMatch Error "Reverrse for 'messages' with arguments '(u'josh',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['messages/(?P<user_name>\\d+)?/']
where '(u'josh',)' is the user.name returned by:
<li><a href="{% url 'messages' user.name %}">{{ user.name }}</a></li>
How do I strip the excess of off that so that only 'josh' is returned (which is what I'm assuming this URL wants). I want to do this in the HTML file itself.
url(r'^messages/(?P<user_name>\d+)?/', views.view_messages, name='messages'),
Models
class User (models.Model):
name = models.CharField(max_length=20, primary_key=True)
def __unicode__(self):
return self.name
class Message (models.Model):
content = models.TextField(max_length=140, null=True, blank=True)
user = models.ForeignKey(User)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.content
Thank you!
Upvotes: 0
Views: 617
Reputation: 149
django uses a separate model field for directly displaying in the URL: SlugField "Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs."
so either you update your model with a name_slug or just use "encoding", e.g. base64
Upvotes: 0
Reputation: 3244
I think that the trouble is because of user_name
is named parameter in url, so you can trying pass like named parameter
{% url 'messages' user_name=user.name %}
And of course you must use \w+
for the matching.
Upvotes: 1
Reputation: 15104
If you are using the django.contrib.auth.models.User
then {{ user.name }}
shouldn't return anything. I assume that you use a custom user model. If yes then you can just user {{ user.name.0 }}
to get the first member of the tuple.
If instead you are using the django.contrib.auth.models.User
then just try {{ user.username }}
to just get the username.
Update: Hmmm then restore your template again to {{ user.name }}
and change your url pattern to
url(r'^messages/(?P<user_name>\w+)?/', views.view_messages, name='messages'),
(notice the \w+
instead of the \d+
: \d
is for digits, \w
is for characters. That's why you didn't get a match).
Upvotes: 1