Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
huhu
Feb 24, 2006
Specific dumb questions ahoy.

code:
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>
How is the Question.objects.get(pk=1) a shortcut?

Adbot
ADBOT LOVES YOU

Data Graham
Dec 28, 2009

📈📊🍪😋



It's in case your primary key is called something other (longer) than "id".

Don't know this for sure, but it's also worded to suggest that what it's really a shortcut for is Question.objects.get(id__exact=1), which might have been standard usage earlier than "id=1".

Not a great piece of documentation there.

huhu
Feb 24, 2006

Data Graham posted:

It's in case your primary key is called something other (longer) than "id".

Don't know this for sure, but it's also worded to suggest that what it's really a shortcut for is Question.objects.get(id__exact=1), which might have been standard usage earlier than "id=1".

Not a great piece of documentation there.

Ah ok, thanks.

New question, I've got an About_Author model, with an About_Author_Link model that let's there be multiple social media links for the author.

code:
class About_Author(models.Model):
    title = models.CharField(max_length=200)
    summary = models.TextField()
    photo = models.ImageField(upload_to = 'single_page_website/media/img/' )
    class Meta:
        ordering = ('title',)
    def __str__(self):  
        return self.title 

class About_Author_Link(models.Model):
    url_title = models.CharField(max_length = 50)
    url_path = models.CharField(max_length = 300)
    about = models.ForeignKey(About_Author, related_name='about_author_link')
    class Meta:
        ordering = ('url_title',)
    def __str__(self):  
        return self.url_title #self.title refers to title = models.CharField(max_length=200) line
Relevant part of views.py:
code:
	about = About_Author.objects.all()[0]
	
        return render(request, 'single_page_website/index.html', {'about':about})
How would I display each of the links from About_Author_Link in a template? This was my guess:

code:
					{% for each_url in about.about_author_link %}
						<h1>{{each_url.url_title}}</h1>
					{% endfor %}

Data Graham
Dec 28, 2009

📈📊🍪😋



Your "about" is just pulling the first record from the About_Author model. It's not a thing you can loop over.

What you want is probably this:

code:
links = About_Author_Link.objects.filter(about=<some_author_instance>) # Assuming you want to iterate through all the links for a given author
code:
{% for link in links %}
	<h1>{{link.url_title}}</h1>
{% endfor %}
A couple of notes:

Object naming in Django wants to use names like AboutAuthor and AboutAuthorLink, not About_Author and About_Author_Link. It's kind of opinionated about underscores. If you use them in model names you'll end up with some confusing-rear end database table names.

For clarity on what the models are for, you might want to try to keep their names more concise and specific. So if it's an author, just call it Author. And if the link objects are for social media outlets, something like SocialMedia might be better. Or MediaLink if you want it to be more generic. No reason to mention Author in the model name.

That way your ForeignKey field can refer more clearly to the model it's referencing. So your SocialMedia object will have an "author" field, not an "about" field (which feels like a misleading name). Then your code can convey its meaning a lot more semantically, like

code:
social_media_links = SocialMedia.objects.filter(author=<some_author_instance>)

for link in social_media_links:
    print social_media_link.author.title

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

huhu posted:

Specific dumb questions ahoy.

code:
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>
How is the Question.objects.get(pk=1) a shortcut?

Just to expand: Primary key does not have to be the id. It is by default, but you can set primary_key=True on any field in your model.

huhu posted:

code:
class About_Author(models.Model):

It's a good idea to get used to PEP-8 compliant naming of stuff. Not that it makes a real difference to the functionality of your code, but it makes it easier to follow a standard when others have to read your code (and others includes you when you come back to it in a year).

In this case the name should be AboutAuthor.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I was alerted to this thread after asking Django stuff in the general questions thread. I am repeating a question here. Is there a module or nice built-in that will give a good try at dumping my model on to the screen? I'm thinking like the admin view but for regular users. I was hoping there were similar things to qualify how it did the dumping. I'm just finding it tedious to create an HTML file for a generic template and then trying to not make it look too much like rear end. I figured there was a better way.

epswing
Nov 4, 2003

Soiled Meat

Rocko Bonaparte posted:

I was alerted to this thread after asking Django stuff in the general questions thread. I am repeating a question here. Is there a module or nice built-in that will give a good try at dumping my model on to the screen? I'm thinking like the admin view but for regular users. I was hoping there were similar things to qualify how it did the dumping. I'm just finding it tedious to create an HTML file for a generic template and then trying to not make it look too much like rear end. I figured there was a better way.

I'm not a Django expert, but I think you can just create a ModelForm for your model, specify what you want included/excluded, create a a form using an instance of the model, and just drop {{ form }} on the page, which will generate all the default html controls based on the types in the model.

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

huhu
Feb 24, 2006

epalm posted:

I'm not a Django expert, but I think you can just create a ModelForm for your model, specify what you want included/excluded, create a a form using an instance of the model, and just drop {{ form }} on the page, which will generate all the default html controls based on the types in the model.

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

Tutorial for such a form, specifically creating a create blog post webpage:

https://tutorial.djangogirls.org/en/django_forms/

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

epalm posted:

I'm not a Django expert, but I think you can just create a ModelForm for your model, specify what you want included/excluded, create a a form using an instance of the model, and just drop {{ form }} on the page, which will generate all the default html controls based on the types in the model.

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

This gives me the compactness, but now I have a form for the thing, when I just wanted to see it without editing. Well, editing it was next...

Data Graham
Dec 28, 2009

📈📊🍪😋



If you're making a view-and-edit interface for end users, you kinda just have to make your peace with the fact that you have to explicitly know what attributes your model has and code them all into the HTML. Trying to programmatically dump model fields in a way that sorts nicely and handles different field types properly (e.g. dates) is more trouble than it's worth.

If you literally just want a dump of the object for debugging purposes, you can echo the whole thing with {{ object_name }}, or you can convert the whole model instance to an array in the view function like this and then iterate over it in the template.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

You might be able to wire something barebones together using Django Rest Framework and just dumping the JSON to screen. Depends on how important it is that it looks good...

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

Data Graham posted:

If you're making a view-and-edit interface for end users, you kinda just have to make your peace with the fact that you have to explicitly know what attributes your model has and code them all into the HTML. Trying to programmatically dump model fields in a way that sorts nicely and handles different field types properly (e.g. dates) is more trouble than it's worth.

If you literally just want a dump of the object for debugging purposes, you can echo the whole thing with {{ object_name }}, or you can convert the whole model instance to an array in the view function like this and then iterate over it in the template.

I might be hallucinating, but I have this vague memory from dicking around with ASP.NET that it could take a decent guess at displaying a model for viewing purposes without having to do much of any embedded HTML. I just assumed there was something similar with Django since just about everything else has been similar.

So if I have to spit it out in HTML, is there a few quick things to get at least a palatable view? Are there some default style sheets or something?

MonkeyMaker
May 22, 2006

What's your poison, sir?

Rocko Bonaparte posted:

I might be hallucinating, but I have this vague memory from dicking around with ASP.NET that it could take a decent guess at displaying a model for viewing purposes without having to do much of any embedded HTML. I just assumed there was something similar with Django since just about everything else has been similar.

So if I have to spit it out in HTML, is there a few quick things to get at least a palatable view? Are there some default style sheets or something?

No, Django won't make those assumptions. You can always use Bootstrap or Foundation, though. They both have example templates.

huhu
Feb 24, 2006
Thanks again for all the help thus far.

I've uploaded an image before and it went to:
/media/single_page_website/media/img/

Just uploaded some new images and they're broken and pointing to:
single_page_website/media/img/

What am I forgetting to do?

Data Graham
Dec 28, 2009

📈📊🍪😋



./manage.py collectstatic

huhu
Feb 24, 2006

Data Graham posted:

./manage.py collectstatic

Didn't work.

huhu
Feb 24, 2006

huhu posted:

Thanks again for all the help thus far.

I've uploaded an image before and it went to:
/media/single_page_website/media/img/

Just uploaded some new images and they're broken and pointing to:
single_page_website/media/img/

What am I forgetting to do?

To clarify. I have an image hosted at /media/single_page_website/media/img/ and they display. That's where images used to get uploaded. I just uploaded a new image, it's located in the directory I just mentioned but the img src is pointing to single_page_website/media/img/. The /media/ is missing.

Data Graham
Dec 28, 2009

📈📊🍪😋



What template is this in? One you wrote yourself, or one that's part of some package?

huhu
Feb 24, 2006

Data Graham posted:

What template is this in? One you wrote yourself, or one that's part of some package?

I wrote it myself.

Data Graham
Dec 28, 2009

📈📊🍪😋



So... I don't get it then. Don't you have control over your HTML code? Why is the img src= not up to you?

huhu
Feb 24, 2006

Data Graham posted:

So... I don't get it then. Don't you have control over your HTML code? Why is the img src= not up to you?

I do, I don't know what is writing /media/ to some src fields and not to others. The src is being generated by Django.

Data Graham
Dec 28, 2009

📈📊🍪😋



What does your template code look like? I'm not picturing what part Django is playing in your HTML structure.

Unless you're using {% static %} tags, but I figured collectstatic would have dealt with that.

huhu
Feb 24, 2006
Ended up being that my {{image}} was missing .url. Thanks for your help in pushing me towards figuring this out.

Data Graham
Dec 28, 2009

📈📊🍪😋



Aha, I didn't realize your images were themselves variables/data. I thought this was an issue with static files you'd uploaded.

Glad to hear you found it.

Mad Jaqk
Jun 2, 2013

huhu posted:

code:
class About_Author_Link(models.Model):
    url_title = models.CharField(max_length = 50)
    url_path = models.CharField(max_length = 300)
    about = models.ForeignKey(About_Author, related_name='about_author_link')
    class Meta:
        ordering = ('url_title',)
    def __str__(self):  
        return self.url_title #self.title refers to title = models.CharField(max_length=200) line
How would I display each of the links from About_Author_Link in a template? This was my guess:

code:
{% for each_url in about.about_author_link %}
	<h1>{{each_url.url_title}}</h1>
{% endfor %}

A few days late, but this code would work if you changed it to {% for each_url in about.about_author_link.all %}. When you use a related_name for a reverse look-up, you need to specify the .all (or .filter or .count or another queryset method). A lot of the syntax for this is the same as for a ManyToManyField.

huhu
Feb 24, 2006

Mad Jaqk posted:

A few days late, but this code would work if you changed it to {% for each_url in about.about_author_link.all %}. When you use a related_name for a reverse look-up, you need to specify the .all (or .filter or .count or another queryset method). A lot of the syntax for this is the same as for a ManyToManyField.

Thank you so much for this. Was a lot of help just now on a new issue.

huhu
Feb 24, 2006
I've got a single page website that I'd like to split up into multiple html files. I tried the following but it's not working. What am I missing?
Index.html:
code:
<body>
    {% block home %}
    {% endblock %}

    {% block about %}
    {% endblock %}	
</body>
</html>
home.html:
code:
    {% extends 'website/index.html' %}
    {% block home%}
        Content
    {% endblock %}

Gounads
Mar 13, 2013

Where am I?
How did I get here?
Did you change your view to render home.html instead of index.html?

edit: Thinking more, you're trying to use blocks for the opposite reason they're intended. They're useful when you have a bunch of pages that all have common pieces. They're not very useful for single page sites.

epswing
Nov 4, 2003

Soiled Meat

huhu posted:

it's not working

How so? What does "not working" mean in this case?

Are you sure 'website/index.html' exists? Depending on which version of Django, and assuming your site is called 'website', index.html should be located at project_root/website/templates/website/index.html

epswing fucked around with this message at 20:17 on Oct 14, 2016

Pumpkin Pirate
Feb 2, 2005
???????
I think Gounads is on the right track here. With just the two files you've given, it should work if you make sure that your view is rendering home.html, but if your idea is that you'll also have a separate about.html file with the about content, you should be looking into {% include %} rather than {% block %} and {% extends %}.

huhu
Feb 24, 2006
code:
Instead of hardcoding the secret key in your settings module, consider loading it from an environment variable:

import os
SECRET_KEY = os.environ['SECRET_KEY']
or from a file:

with open('/etc/secret_key.txt') as f:
    SECRET_KEY = f.read().strip()
Could anyone in the simplest of terms explain why?

Edit: How much of this https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ do I really need to care about? I know debug = false is important, I got a new secret key generated and settings.py is now in my .gitignore. I've got a single page website where I'm the only one creating new content via the admin panel.

huhu fucked around with this message at 17:34 on Oct 15, 2016

Data Graham
Dec 28, 2009

📈📊🍪😋



Because your settings module will probably end up in source control, and you don't want to keep things like passwords and secret keys in source control.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Also you should read https://12factor.net/

Environment variables are good for this kind of stuff.

huhu
Feb 24, 2006
Ok so read up on storing the security key somewhere else and I'm good to go?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

huhu posted:

Ok so read up on storing the security key somewhere else and I'm good to go?

Well not just the key, anything that is variable across deployments and/or anything else you may want to keep out of source control.

Hed
Mar 31, 2004

Fun Shoe
For example db creds, API keys. If you had a storefront you might have a development and testing settings.py with test PayPal/Stripe keys and a db with no creds, but in production you will obviously have your real API keys and database creds. It's a lot easier to set in the environment or other state, and as mentioned keeps it out of source control.

huhu
Feb 24, 2006
Edit: After way too much reading and being completely lost... I think I need to do something with this: https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/modwsgi/#serving-files to get static media to load.

My settings.py currently looks like:
code:
DEBUG = False 

...

STATIC_ROOT = '/home/huhu/webapps/eng30_static_media/static'
MEDIA_ROOT =  '/home/huhu/webapps/eng30_static_media/media'

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
I've run collectstatic and my static files are in /home/huhu/webapps/eng30_static_media/static I still have no idea what to do with the media files. What am I missing here? I currently don't have any static js, static img, static css, or media uploaded via the admin panel showing.

edit5: :suicide: I figured it out. Good lord that was complicated. Glad my hosting has amazing documentation/community and when I decided to start searching there I finally found an answer.

huhu fucked around with this message at 03:01 on Oct 20, 2016

Data Graham
Dec 28, 2009

📈📊🍪😋



Has anyone fought through this one?

I'm using Django with MySQL; my tables are all utf8mb4 with collation utf8mb4_general_ci. I'm able to save four-byte Unicode strings (i.e. 💩) into the TextFields of my models through the admin just fine; but CharFields give me an error:

code:
OperationalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x92\\xA9' for column 'object_repr' at row 1")
What's weird is that I can paste 💩 directly into the database field via a GUI like Sequel Pro and it takes it just fine, whether it's a VARCHAR (i.e. CharField) or a TEXT (i.e. TextField) field. In other words MySQL itself doesn't seem to care. But Django does.

This happens with CharFields with max_length set to 255 or 50.

I've read this https://docs.djangoproject.com/en/1.10/ref/databases/#mysql-collation and this http://blog.manbolo.com/2014/03/31/using-emojis-in-django-model-fields, but nothing seems to acknowledge that there's a difference in behavior between CharField and TextField, or that it's something in Django that's breaking because the MySQL client takes 4-byte strings fine.

Is there some trick to making my CharFields use the same character encoding that TextFields use?




E: AAHH gently caress. I poked through the DB for "object_repr" columns, and of course there's one in the django_admin_log table, and of course it's set to latin1 :doh:

Data Graham fucked around with this message at 05:44 on Nov 2, 2016

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've got a simple little Django app and I want to switch out MySQL for PostgreSQL. I've been fiddling around with mysqldump, psql, and a bunch of random migration scripts I found through google to try and get this working, but it's not going very well so far.

I don't really give a poo poo about migrating the schema, I just want the data. I was thinking about just making a little python script that dumps all my model fields to a CSV, and then another little script to read the CSV and save the new records.

Is there something I can use to make this easier? It seems like a simple script in itself, just wanted to double check before I went down that path.

I don't care about migrating the auth/user/etc tables, just my custom models.

Adbot
ADBOT LOVES YOU

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
You could try using manage.py dumpdata. That dumps all your data into JSON files that can then run into manage.py loaddata.

That way you avoid having to worry about conversion from MySQL to Postgres, however be aware constraints are not relaxed while you use loaddata, so it's important to segment your loaddata json payloads sometimes so you don't get integrity errors on foreign keys. As long as you have a nice environment to run some tests you can just smash away at it til you find a sequence that works.

https://docs.djangoproject.com/en/1.10/ref/django-admin/#dumpdata

Note that you can be very specific dumping single models and apps and things.

Maluco Marinero fucked around with this message at 00:48 on Nov 3, 2016

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply