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
Jo
Jan 24, 2005

:allears:
Soiled Meat
I'm really scratching my head about this one. I have two nearly identical paths set up. One works, the other doesn't. Media works, static returns 404.

In urls.py:
code:
if settings.DEBUG:
        from django.conf.urls.static import static
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
In settings.py:
code:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
In command line:
pre:
$ curl http://localhost:8000/media/test.txt
test

$ curl http://localhost:8000/static/test.txt
404
<!DOCTYPE html> 
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>Page not found at /static/test.txt</title>
EDIT: Missing STATICFILES_FOLDERS in settings.

Jo fucked around with this message at 22:51 on Jul 27, 2016

Adbot
ADBOT LOVES YOU

Cock Democracy
Jan 1, 2003

Now that is the finest piece of chilean sea bass I have ever smelled
I'd check the file permissions of the static folder and its contents. Maybe it's too restrictive, or owned by the wrong user and the app can't read it.

Jo
Jan 24, 2005

:allears:
Soiled Meat

Cock Democracy posted:

I'd check the file permissions of the static folder and its contents. Maybe it's too restrictive, or owned by the wrong user and the app can't read it.

Permissions are set correctly. They're the same between the two folders. User running the server can cat both files.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I don't remember having to do anything with the urls for STATIC_URL, just the MEDIA_URL. All I have in mine for that is:

code:
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Jo
Jan 24, 2005

:allears:
Soiled Meat

fletcher posted:

I don't remember having to do anything with the urls for STATIC_URL, just the MEDIA_URL. All I have in mine for that is:

code:
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I was missing staticfile_dirs. New change from the version I'm used to using.

Hyvok
Mar 30, 2010
Has anyone used Django-CMS? I have a pretty simple blog which just has articles, main page, comments section (with anti-spam plugin, kismet), twitter feed, some menus and a photo gallery or two, really simple stuff on WordPress right now but I would like to try out something different for a change. Updating the WP blog constantly due to security issues etc. is a bit tiresome. Also not really interested in PHP or dealing with it which discourages me from trying out some new stuff. Is Django-CMS suitable for something like this? Do I need to make a lot of stuff from scratch? I didn't find too many good articles about Django-CMS which would explain well what does it contain, what is it meant for etc.

Also interested on migration from WP to Django-CMS and if there are any readymade tools for migrating a WP blog to Django-CMS. Thankfully I don't have a huge amount of content so not a huge issue if its not very automatic but it would be more convenient.

Gounads
Mar 13, 2013

Where am I?
How did I get here?
I will never run a personal dynamic blog again. Static sites are where it's at.

But I did use mezzanine for a while. It was easy to set up and use.
http://mezzanine.jupo.org/

Eleeleth
Jun 21, 2009

Damn, that is one suave eel.
Please use wagtail for new Django CMS apps, it's pretty excellent.

http://wagtail.io/

Kudaros
Jun 23, 2006
I'm pondering creating a website for a local organization I'm involved in. Certain individuals would need access to write posts (a lightweight CMS type of thing I guess?). I would additionally have a database of member/volunteer information and a form for which visitors can offer their contact info. Some minimalist event calendar type of thing might be helpful as well.

I'm also thinking about using some analytics data from, say, R Shiny apps, or Python notebooks or something. A sort of analytics display, rather than a platform. Chloropleth maps, possibly interactive, some other types of charts, etc. These would need to be log-in protected.

Initially I thought of using Flask because I anticipated the website to be quite simple, but after working through most of the Treehouse course (I'll look at Django next) I am having second thoughts.

Any recommendations, especially for packages? Is Django a good way to go?

I'll also probably end up working on the front-end myself, which sucks, any recommendations for that? Guess I can get someone with an eye for that sort of thing to just do a base template and extend it everywhere.

My personal site is just a static pelican site. Easy. But I also don't need to manage a database or anything.

I'm a decent enough programmer I guess, but little web experience. Any advice appreciated.

MonkeyMaker
May 22, 2006

What's your poison, sir?

Kudaros posted:

Initially I thought of using Flask because I anticipated the website to be quite simple, but after working through most of the Treehouse course (I'll look at Django next) I am having second thoughts.

Sorry if I made Flask seem hard? Or did I show some limits?

Kudaros
Jun 23, 2006
I'm not certain I'm qualified to say, but I'm leaning limits. The "batteries included" approach of Django seems more appropriate for the particular need I have at the moment (basics of a multi-user CMS, integrating some numerical analysis type stuff, and so on). For smaller projects (as in the build-a-bear), I definitely see value in the Flask framework. I'm enjoying your course otherwise!

I have an absurdly busy schedule until ~October and have started too many new projects so I might rushing to conclusions on the microframework approach. Some inconvenient events have transpired which are kind of pushing me to get this done somewhat quickly.

Also, for whatever reason, switching from a scientific programming task (my daily grind unless I'm writing) to a web task is really awkward for me.

Tigren
Oct 3, 2003

Kudaros posted:

I'm not certain I'm qualified to say, but I'm leaning limits. The "batteries included" approach of Django seems more appropriate for the particular need I have at the moment (basics of a multi-user CMS, integrating some numerical analysis type stuff, and so on). For smaller projects (as in the build-a-bear), I definitely see value in the Flask framework. I'm enjoying your course otherwise!

I have an absurdly busy schedule until ~October and have started too many new projects so I might rushing to conclusions on the microframework approach. Some inconvenient events have transpired which are kind of pushing me to get this done somewhat quickly.

Also, for whatever reason, switching from a scientific programming task (my daily grind unless I'm writing) to a web task is really awkward for me.

You're basically building Django if you use Flask with an ORM, DB, Auth, Migrations, Debugs, Jinja2, Forms, etc, etc.

If you need all that stuff, I'd say go with Django

Thermopyle
Jul 1, 2003

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

Anybody here have any experience with model auditing? I'm looking to track the history of changes to fields in my models but I want to minimize performance overhead (maybe its minimal, I don't know!). I think I'm just going to implement django-reversion, but I'm feeling pretty lazy and wondering if anyone has compared it to any alternatives for performance.

Thermopyle
Jul 1, 2003

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

I ended up using django-reversion and it's working fine.

The real reason I'm posting is something I solved for myself today.

When writing or troubleshooting Celery tasks sometimes it's hard to see whats going on with your logs because you can have multiple concurrent tasks and the only way to differentiate them is the long UUID celery gives each task.

It's pretty hard to visually differentiate UUID's, so I started using gfycat-style identifiers. For those unaware, gifs/videos hosted on gfycat have unique urls whose identifier is AdjectdiveAdjectiveAnimal.

First you need the animals list: https://gist.github.com/anonymous/68db369d63e89e3d5bb94971cbbea3cf
Then you need the adjectives list: https://gist.github.com/anonymous/c3156748cbed1a6bbdc8e4d8b7cd167c

Then the function:

Python code:
def unique_str():
	"""Assumes list `adjectives` and `animals` is in-scope"""
	return '{adj1}{adj2}{animal}{number}'.format(
                                                     adj1=random.choice(adjectives).capitalize(),
	                                             adj2=random.choice(adjectives).capitalize(),
	                                             animal=random.choice(animals).capitalize(),
	                                             number=random.randint(1, 1000))
Also the class:
Python code:
class GfyTask(Task):
	def apply_async(self, *args, **kwargs):
		kwargs.setdefault('task_id', unique_str())
		return super(GfyTask, self).apply_async(*args, **kwargs)
When you create a task use GfyTask as the base:
Python code:
@shared_task(base=GfyTask)
def some_task():
	# blah blah
I stuck the random integer on the end because why not.

This gets you cool task ids like:
code:
n[21]: unique_str()
Out[21]: 
'WatchfulUnfortunateBlacklab459'
In[22]: unique_str()
Out[22]: 
'IncomparablePrudentSpider964'
In[23]: unique_str()
Out[23]: 
'ImportantTediousMockingbird682'
In[24]: unique_str()
Out[24]: 
'EmbellishedLightGar649'
And your logs are easy to parse visually like:
code:
[2016-09-14 19:17:38,980: DEBUG/Worker-2] [app.tasks.doing_stuff_task(HelpfulLimeAlaskajingle480)] blah blah blah
edit: figured out a better way of using the task_id

Thermopyle fucked around with this message at 21:01 on Sep 14, 2016

Data Graham
Dec 28, 2009

📈📊🍪😋



The django-cron guy finally fixed that 1.10 deprecation warning, wooo!

huhu
Feb 24, 2006
Edit: Solution - I deleted db.sqlite3 and it's working.



I'm getting the following error while trying to submit content via admin:
code:
OperationalError at /admin/single_page_website/post_project/add/
no such column: single_page_website_post_project_tools.tool_id
The solution I found on Google was to run
code:
manage.py makemigrations single_page_website
manage.py migrate single_page_website
Which returned:
code:
No changes detected in app 'single_page_website'
Operations to perform:
  Apply all migrations: single_page_website
Running migrations:
  No migrations to apply.
Here is my models.py file. Post_Project is for creating a new project for a portfolio and Tool will be a table with just tools that I've used for a project. What am I doing wrong?

code:
#All lines starting with from or import are lines that add some bits from other files. So instead of 
#copying and pasting the same things in every file, we can include some parts with from ... import ...


from django.db import models
from django.utils import timezone

class Tool(models.Model):
    tool = models.CharField(max_length=100)
    class Meta:
        ordering = ('tool',)

    def __str__(self):  
        return self.tool #self.title refers to title = models.CharField(max_length=200) line

class Post_Project(models.Model):                       
    author = models.ForeignKey('auth.User')            
    title = models.CharField(max_length=200)
    summary = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)
    tools = models.ManyToManyField(Tool)

    class Meta:
        ordering = ('title',)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):  
        return self.title #self.title refers to title = models.CharField(max_length=200) line

huhu fucked around with this message at 02:17 on Sep 16, 2016

TimWinter
Mar 30, 2015

https://timsthebomb.com

Thermopyle posted:


This gets you cool task ids like:
code:
n[21]: unique_str()
Out[21]: 
'WatchfulUnfortunateBlacklab459'
In[22]: unique_str()
Out[22]: 
'IncomparablePrudentSpider964'
In[23]: unique_str()
Out[23]: 
'ImportantTediousMockingbird682'
In[24]: unique_str()
Out[24]: 
'EmbellishedLightGar649'
And your logs are easy to parse visually like:
code:
[2016-09-14 19:17:38,980: DEBUG/Worker-2] [app.tasks.doing_stuff_task(HelpfulLimeAlaskajingle480)] blah blah blah
edit: figured out a better way of using the task_id

Docker has a similar system with a couple of different word lists- I've seen a few places employ something like this, and they're so good at differentiating a handful of options at a glance. At work, I've been referring to these as locally unique identifiers, as opposed to the better known UUID systems more commonly employed.

edit: I actually found the wordlist I used when originally implementing something like this, just 3 random selections from this list, concatenated: http://www.alphadictionary.com/articles/100_funniest_words.html

TimWinter fucked around with this message at 06:00 on Sep 18, 2016

Thermopyle
Jul 1, 2003

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

Those are some good words.

I've changed to using AdjectiveAdjectiveAnimalVerb.

One I just generated for a task: MealyFarawayAssFeels.


In other news, anyone using django channels for anything cool? I'm thinking about using it for an upcoming project. All of the example implementations I see out there are for websocket chat sites.

I'm thinking about serving a JSON API over websockets...

huhu
Feb 24, 2006
I've got a project submission form with images = models.ForeignKey(Project_Image, on_delete=models.CASCADE) for adding images. When I view it in Django Admin, it shows up as:


What am I doing wrong?

code:
class Project_Image(models.Model):
    title = models.CharField(max_length = 50)
    description = models.TextField()
    image = models.ImageField()
    class Meta:
        ordering = ('title',)
    def __str__(self):  
        return self.title #self.title refers to title = models.CharField(max_length=200) line

class Post_Project(models.Model):              
    author = models.ForeignKey('auth.User')         
    title = models.CharField(max_length=200)
    summary = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)
    tools = models.ManyToManyField(Tool)
    images = models.ForeignKey(Project_Image, on_delete=models.CASCADE)

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
models.ForeignKey is a many to single. So in this case, many Products to a single Product_Image.

You need to flip it and have the foreign key go from Product_Image related to Product, with a related_name of "images"

22 Eargesplitten
Oct 10, 2010



Hopefully this is more Django than Python. I've tried everything I can think of to get this to work, but I can't get it going. I'm following the instructions for setting up a Django app on Heroku's website. I've installed setuptools, I've got postgresql, but I'm still getting this error when I attempt .

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-AY0uR/psycopg2.

I've also tried installing psycopg2 by itself, same error. looking in the directory it gives, there is no pip-build-AY0uR.

Does anyone have any ideas? I'm kind of at a standstill here.

Tigren
Oct 3, 2003

22 Eargesplitten posted:

Hopefully this is more Django than Python. I've tried everything I can think of to get this to work, but I can't get it going. I'm following the instructions for setting up a Django app on Heroku's website. I've installed setuptools, I've got postgresql, but I'm still getting this error when I attempt .

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-AY0uR/psycopg2.

I've also tried installing psycopg2 by itself, same error. looking in the directory it gives, there is no pip-build-AY0uR.

Does anyone have any ideas? I'm kind of at a standstill here.

Literally the first google result http://stackoverflow.com/questions/5420789/how-to-install-psycopg2-with-pip-on-python

Data Graham
Dec 28, 2009

📈📊🍪😋



That's definitely a python question and not Django.

But my guess is that it's deleting that directory as part of the cleanup. Can you watch /tmp while the install is going and see if something is getting created then?

e: or that

22 Eargesplitten
Oct 10, 2010




Sorry, I forgot to mention that I tried that one. I googled a lot of stuff. I tend to try a lot of things and only ask for help when I'm stumped, but unfortunately I don't keep track of everything I try. It's a bad habit.

I tried the CentOS version again, and it reinstalled or updated or something, although I distinctly remember doing that last night. unfortunately now when trying to install psycopg2 it's saying failed to build wheel, and the first couple google results for that also haven't worked.

I'll ask in the Python thread.

huhu
Feb 24, 2006

Maluco Marinero posted:

models.ForeignKey is a many to single. So in this case, many Products to a single Product_Image.

You need to flip it and have the foreign key go from Product_Image related to Product, with a related_name of "images"

I moved
code:
    project = models.ForeignKey(Post_Project, on_delete=models.CASCADE)
to the Project_Image class but I don't get out to now add images to Post_Project?

Gounads
Mar 13, 2013

Where am I?
How did I get here?

huhu posted:

I moved
code:
    project = models.ForeignKey(Post_Project, on_delete=models.CASCADE)
to the Project_Image class but I don't get out to now add images to Post_Project?

set a related_name, use that on your Post_Project

Also, I feel dirty writing Post_Project, consider reading PEP-8

huhu
Feb 24, 2006

Gounads posted:

set a related_name, use that on your Post_Project

Also, I feel dirty writing Post_Project, consider reading PEP-8

I found this answer about related_name http://stackoverflow.com/questions/13997562/make-a-one-to-many-relation-in-django but it names no mention of how I would actually view the option to upload images in admin via Post_Project.

And one other question, if I have
code:
title = models.CharField(...)
upload_to = "images/" + _______
What should I put in place of _______ so that images uploaded for each project get their own folder?

Mulozon Empuri
Jan 23, 2006

Here's some ancient code to show you how you can do stuff like that.

You can also read the docs here https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.FileField.upload_to

code:
    def handle_upload_image(instance, filename):
        return "media/images/%s/%s" % (instance.project.slug, filename)

    image = models.ImageField(upload_to=handle_upload_image, blank=true)

Gounads
Mar 13, 2013

Where am I?
How did I get here?

huhu posted:

I found this answer about related_name http://stackoverflow.com/questions/13997562/make-a-one-to-many-relation-in-django but it names no mention of how I would actually view the option to upload images in admin via Post_Project.

And one other question, if I have
code:
title = models.CharField(...)
upload_to = "images/" + _______
What should I put in place of _______ so that images uploaded for each project get their own folder?

Sorry, double mistake, I thought you meant adding Post_Image records and didn't realize we were talking purely the admin app.

It's been a while since I did this, but in your admin config, look at using an InlineModelAdmin. And I think the default ImageField admin widget would do what you need after you get those appearing.

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

New question. I want to have a model where title is entered, it is saved, and a second version title_computer is created. My thought would be todo:

code:
title_human = models.CharField(max_length = 50)
title_computer = title_human.lower().replace(" " , "_")
But that's not right. What am I missing? I looked at slugs but from what I can gather I'm not sure what I need. I'd like to be able to use title_computer for creating unique IDs for HTML and save paths for images.

Thermopyle
Jul 1, 2003

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

huhu posted:

Thanks for the help thus far.

New question. I want to have a model where title is entered, it is saved, and a second version title_computer is created. My thought would be todo:

code:
title_human = models.CharField(max_length = 50)
title_computer = title_human.lower().replace(" " , "_")
But that's not right. What am I missing? I looked at slugs but from what I can gather I'm not sure what I need. I'd like to be able to use title_computer for creating unique IDs for HTML and save paths for images.

What exactly is not right?

If you're literally putting that code in your field definitions in your model that won't work because at that point title_human doesn't exist, so when python gets to the title_computer line there's nothing there to do.

In the general case, you'll usually override save() or maybe clean() if you want to generate values for fields when you save the model.

Like so:

Python code:
class AModel(models.Model):
  title_human =  models.CharField(max_length = 50)
  title_computer = models.CharField(max_length=1000000000000, blank=True)

  def save(self, *args, **kwargs):
    self.title_computer = self.title_human.lower().replace(" " , "_")
    super().save(*args, **kwargs)
I wrote this in breaks while dead while playing Overwatch, so there's more things to say, but I'm tired of writing it right now! :D

PT6A
Jan 5, 2006

Public school teachers are callous dictators who won't lift a finger to stop children from peeing in my plane

Thermopyle posted:

What exactly is not right?

If you're literally putting that code in your field definitions in your model that won't work because at that point title_human doesn't exist, so when python gets to the title_computer line there's nothing there to do.

In the general case, you'll usually override save() or maybe clean() if you want to generate values for fields when you save the model.

Like so:

Python code:
class AModel(models.Model):
  title_human =  models.CharField(max_length = 50)
  title_computer = models.CharField(max_length=1000000000000, blank=True)

  def save(self, *args, **kwargs):
    self.title_computer = self.title_human.lower().replace(" " , "_")
    super().save(*args, **kwargs)
I wrote this in breaks while dead while playing Overwatch, so there's more things to say, but I'm tired of writing it right now! :D

While this certainly works, is there a reason why title_computer needs to be stored as part of the model, instead of generated dynamically based on title_human? If title_computer is always going to be based on title_human, just write a method that returns a string based on the value of title_computer, and you'll have eliminated redundant data from your model. Obviously, this doesn't apply if that's just a default value for the field and it can change independently of title_human later on.

MonkeyMaker
May 22, 2006

What's your poison, sir?
Also, if you're just trying to make slugs,
code:
slugify()
is a thing. Docs for it

huhu
Feb 24, 2006
I feel overwhelmed every time I try to read Django documentation. Anyone else feel this from the beginning and overcome it? If so, any tips?

Thermopyle
Jul 1, 2003

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

huhu posted:

I feel overwhelmed every time I try to read Django documentation. Anyone else feel this from the beginning and overcome it? If so, any tips?

Django has some of the best open source documentation out there! I think this is a pretty widely-held opinion.

It sounds like maybe you don't really know Django and are kind of jumping in and out of the documentation?

I kinda feel like maybe you've just got to do more work with Django...have you worked through the tutorial in the docs?

There's only so much any documentation can do for you. When it comes down to it you've got to just do work with the thing and kind of get a lay of the land through trial and error.

huhu
Feb 24, 2006

Thermopyle posted:

Django has some of the best open source documentation out there! I think this is a pretty widely-held opinion.

It sounds like maybe you don't really know Django and are kind of jumping in and out of the documentation?

I kinda feel like maybe you've just got to do more work with Django...have you worked through the tutorial in the docs?

There's only so much any documentation can do for you. When it comes down to it you've got to just do work with the thing and kind of get a lay of the land through trial and error.

I tried reading through the tutorial and failed. I found the DjangoGirls.org tutorial which was awesome and got me through a lot of the stuff. Since I now understand at least the basics of things like admin, views, urls, templates, etc I guess I'll start with rereading the official tutorial.

epswing
Nov 4, 2003

Soiled Meat

huhu posted:

I tried reading through the tutorial and failed.

If you can determine the exact point in the tutorial where you got stuck, I'm sure someone here could help you.

Echoing the sentiment that Django docs are some of the best in the business.

Data Graham
Dec 28, 2009

📈📊🍪😋



I mean if you think Django docs are bad I dare you to even try to make your way through Javadocs :v:

PT6A
Jan 5, 2006

Public school teachers are callous dictators who won't lift a finger to stop children from peeing in my plane
I felt confused until I actually did the tutorial, instead of just reading through it. There's nothing like having a working example of something to screw around with, to actually gain an understanding of the system. Plus, then if you don't understand something, you can ask a more informed question and get a better answer from a place like this thread or StackOverflow.

P.S. Here's an interesting thing I found: if you're going to have a Django view spawn a background process using a Popen object, you need to pass close_fds=True to the constructor or else the response will not be sent until the process completes. I'm not sure if the same applies outside view methods (such as in a pre-save method on a model object), but it certainly might.

Adbot
ADBOT LOVES YOU

Thermopyle
Jul 1, 2003

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

I just want to note that often you don't want to spawn background processes from a view.

Instead you might want to be using celery, rq, or even channels (which will be part of Django in future versions).

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