Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7308577
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T23:34:35+00:00 2026-05-28T23:34:35+00:00

I’m writing a simple chat with ajax and I have a problem with JSON.

  • 0

I’m writing a simple chat with ajax and I have a problem with JSON. I need username instead of id.

JSON seems like:

[{"pk": 41, "model": "chat.post", "fields": {"timestamp": "2012-01-27 22:14:46", "user": 1, "text": "weq"}}]`

I need replace "user": 1 to "user": username.

How I can do it?

My model:

    from django.db import models
    from django.contrib.auth.models import User

    class Post(models.Model):
        timestamp = models.DateTimeField(auto_now_add=True)
        text = models.TextField()
        user = models.ForeignKey(User)

        class Meta:
            ordering = ['-id']

        def __unicode__(self):
            return "[%s] %s by user: %s" % (
                self.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
                self.text,
                self.user
            )

My view:

# -*- coding: utf-8 -*-
#!/usr/bin/env python
from django.http import HttpResponse
from django.core import serializers
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.shortcuts import render_to_response

from live.chat.models import Post

@login_required
def updates_after(request, id):
    response = HttpResponse()
    response['Content-Type'] = "text/javascript"
    response.write(serializers.serialize("json",
        Post.objects.filter(pk__gt=id)))
    # __gt - greaten then > id
    return response

@login_required
def saymessage(request):
    if request.method == 'POST':
        if "text" in request.POST:
            text = request.POST["text"]
            user = request.user
            message = Post()
            message.user, message.text = user, text
            message.save()
        return HttpResponseRedirect('/')
    else:
        pass

JSON response example:
[
{
“pk”: 42,
“model”: “chat.post”,
“fields”: {
“timestamp”: “2012-01-28 18:08:44”,
“user”: 1,
“text”: “dasd”
}
}
]

My template:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />

  <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame 
       Remove this if you use the .htaccess -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

  <title>templates</title>
  <meta name="description" content="" />
  <script type="text/javascript" language="javascript" src="/media/js/jquery.min.js"></script>
  <script type="text/javascript" language="javascript">
        function update() {
            update_holder = $("#update_holder");
            most_recent = update_holder.find("div:first");
            $.getJSON("/live/updates-after/" + most_recent.attr('id') + "/",
                function(data) {
                    cycle_class = most_recent.hasClass("odd") ? "even" : "odd";
                    jQuery.each(data, function(){
                        update_holder.prepend('<div id="' + this.pk
                            + '" class="update ' + cycle_class
                            + '"><div class="timestamp">'
                            + this.fields.timestamp
                + '</div><div class="user">'
                + this.fields.user
                            + '</div><div class="text">'
                            + this.fields.text
                            + '</div><div class="clear"></div></div>'
                        );
                        cycle_class = (cycle_class == "odd") ? "even" : "odd";
                    }); 
                }

        );
        }
        $(document).ready(function() {
            setInterval("update()", 10000);
        })
  </script>
  <link rel="stylesheet" type="text/css" href="/media/css/main.css" />
</head>
<body>
{% block content %}
  <div>
    <header>
      <h1>Live Update site</h1>
      <p>Содержимое обновляется автоматически</p>
    </header>
    {% if object_list %}
        <div id="update_holder">
            {% for object in object_list %}
                <div class="update {% cycle even,odd %}" id="{{ object.id }}">
                    <div class="timestamp">
                        {{ object.timestamp|date:"Y-m-d H:i:s" }}
                    </div>
          <div class="user">
          {{ object.user }}
          </div>
                    <div class="text">
                        {{ object.text|linebreaksbr }}
                    </div>
                    <div class="clear"></div>               
                </div>
            {% endfor %}
        </div>
    {% else %}
        <p>Нет обновлений</p>
    {% endif %}
  </div>
<form enctype="multipart/form-data" action="{% url chat.views.saymessage %}" method="post">{% csrf_token %}
Введите текст сообщения: <input type="text" name="text" id="text">
<input type="submit" name="submit" value="Отправить">
</form>
{% endblock %}
</body>
</html>

Update:
I figure out this problem, we need using natural_key(), and overrive this method in user manager class, add next code to models.py:

class UserManager(models.Manager):
    def unatural_key(self):
        return self.username
    User.natural_key = unatural_key

And dont forget add argument use_natural_keys=True to serializers.serialize()

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T23:34:36+00:00Added an answer on May 28, 2026 at 11:34 pm

    You might want to look into Natural Keys. Natural keys allow you to specify what foreign key fields are serialized to. By constructing a primary key for your user, you can have the username in the serialization, instead of the ID.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have just tried to save a simple *.rtf file with some websites and
I have thousands of HTML files to process using Groovy/Java and I need to
I have some data like this: 1 2 3 4 5 9 2 6
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a jquery bug and I've been looking for hours now, I can't
this is what i have right now Drawing an RSS feed into the php,
I would like to count the length of a string with PHP. The string
I've got a string that has curly quotes in it. I'd like to replace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.