1

Per the problem set, I've not changed any of the Python that's included within the problem set for 'Mail'. I've only been tweaking with the JS and the HTML thus far. That's not to say my JS is necessarily correct, just that I don't think it's what's causing my current issue...

At the moment, I've written a couple of JS functions which are looking to load the inboxes of whichever inbox the user has clicked on.

function load_mailbox(mailbox) {
  
  // Show the mailbox and hide other views
  document.querySelector('#emails-view').style.display = 'block';
  document.querySelector('#compose-view').style.display = 'none';

  // Show the mailbox name
  document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
  // Call my get_email function to load the relevant mailbox.
  get_email(mailbox);

}

The only line added to the load_mailbox function is the calling of my own function, get_email, which looks as below.

function get_email(mailbox) {
  fetch(`emails/${mailbox}`)
  .then(response => response.json())
  .then(emails => {
  console.log(emails);
      // Now to load the emails properly
    emails.forEach(add_email);
    })
  }


function add_email(contents) {

  const email = document.createElement('div');
  email.className = 'email';
  email.innerHTML = contents;

  document.querySelector('#emails-view').append(email);
}

It's unlikely that the above JS code is correct however that's not where I need help (at least not yet) as I'm more than happy to try debug as I go.

If I then go to the "Archived" inbox whilst logged in and check the console, I can see I'm getting back an empty JS Array in the console. This makes sense to me as I know there are no archived emails at this point in time.

However, when I load the inbox page within the application and go to the console, I'm greeted by two errors, the first being: "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" and the second "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0".

When I then check my terminal (Windows PowerShell) to see a line by line breakdown of what's going on, it's showing me the below error.

File "C:\Tom\Coding\Python\CS50\mail\mail\models.py", line 27, in serialize "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"), ValueError: Invalid format string [31/Aug/2020 10:17:53] "GET /emails/sent HTTP/1.1" 500 80259 enter image description here

I'm really quite uncertain when it comes to JS so I don't know if there's some formatting that I've inadvertently put in my code that disagrees with the Python formatting within the email model, or whether I've omitted to include a module within the modules.py file perhaps?

For reference, the models.py file looks as below. From what I can tell reading the documentation of strftime, there's nothing wrong with how this is set up...

class Email(models.Model):
    user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails")
    sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent")
    recipients = models.ManyToManyField("User", related_name="emails_received")
    subject = models.CharField(max_length=255)
    body = models.TextField(blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    read = models.BooleanField(default=False)
    archived = models.BooleanField(default=False)

    def serialize(self):
        return {
            "id": self.id,
            "sender": self.sender.email,
            "recipients": [user.email for user in self.recipients.all()],
            "subject": self.subject,
            "body": self.body,
            "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"),
            "read": self.read,
            "archived": self.archived
        }

Welcome any thoughts as to where I'm going wrong on this one.

Cheers,

3

So, this is what I might class a 'half answer'. I'm still not entirely sure why I was getting an error with the timestamp string being incorrectly formatted as the governing documentation for strftime suggested it was fine.

Nevertheless, I initially commented out that particular line within the Model in order to sense check that this was definitely what was causing my issues. As suspected, it was, and the JavaScript was then correctly console logging the JS Objects I was receiving from the API.

I've subsequently amended the format of the timestamp string being created by the Model, to "%m/%d/%Y, %H:%M:%S". This has seemingly resolved the issue and the JS Objects are now being received including this amended timestamp string format.

If anyone's able to further clarify what the original issue with the timestamp string format was then I'd be most interested. Otherwise, the above works as a solution in the interim.

1
  • 1
    i add the same thing and this fix did the job for me !!! thanks !! – MartinD Sep 23 '20 at 1:49
2

I think it's because of how UNIX and Windows format their timestamps.

From https://strftime.org/:

The Python docs contain all the format codes that the C standard (1989 version) requires, and these work on all platforms with a standard C implementation. Note that the 1999 version of the C standard added additional format codes. These include codes for non-zero-padded numbers, that can be obtained by appending a dash (-) (UNIX) or hash (#) (Windows) after the percent (%) sign.

1

I had that problem too! well I don't know why but in Windows I got same error but in Mac OS it runs without any problem... You can fix it by replacing timestamp line with:

"timestamp": self.timestamp.strftime("%A, %d. %B %d/%m/%Y %I:%M%p"),

I just changed the format of the timestamp and it worked! hope this answer helps you:)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .