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
Pollyanna
Mar 5, 2005

Milk's on them.


Maluco Marinero posted:

Show me your current admin code and I'll see how I can help.

models.py:

Python code:
from django.db import models


class Feeling(models.Model):
    name = models.CharField(max_length=100)
    rating = models.IntegerField()


class Thought(models.Model):
    text = models.TextField(max_length=300)
    belief = models.IntegerField()


class MoodLog(models.Model):
    # Each mood log has an associated date.

    publish_date = models.DateTimeField(auto_now_add=True)

    # Step one: Identify the upsetting situation.
    # One large text entry field.

    event = models.TextField(max_length=200, unique=True)

    # Step two: Record negative feelings.
    # More than one feeling can be created.
    # Each feeling is associated with a single integer from 0-100.

    negative_feeling = models.ForeignKey(Feeling)

    # Step three: Triple-column technique.
    # This is a table...kinda tricky.
    # One column is "automatic thoughts" of thought:rating associations.
    # Second column is "distortions", all text fields/charfields. (Maybe add a dropdown list?)
    # Third is a repeat of column 1, but with different key-value pairs.

    automatic_thought = models.ForeignKey(Thought)

    distortion = models.CharField(max_length=40)

    revised_thought = models.ForeignKey(Thought)

    # Step four: How do you feel now?

    purest_feeling = models.TextField(max_length=300)

    def __unicode__(self):
        return unicode(self.publish_date)
admin.py:

Python code:
from django.contrib import admin
from logs.models import MoodLog, Feeling, Thought

class MoodLogInline(admin.TabularInline):
    model = MoodLog
    fk_name = 'automatic_thought'

class FeelingAdmin(admin.ModelAdmin):
    inlines = [
        MoodLogInline,
    ]

class ThoughtAdmin(admin.ModelAdmin):
    inlines = [
        MoodLogInline
    ]

admin.site.register(MoodLog, MoodLogInline)
admin.site.register(Feeling, FeelingAdmin)
admin.site.register(Thought, ThoughtAdmin)
The initial problem I had was that I only got a list of ------- for the attribute on the admin side. Now it just plain doesn't work. I'm lost :(

Adbot
ADBOT LOVES YOU

Dominoes
Sep 20, 2007

I'd like to allow a user to add additional fields by pressing a button. I've set up a basic system for having multiple fields, and am already having trouble. I have a loop to add additional fields and store them in a list, but storing them in a list doesn’t add them to the form's visible fields attribute, which I'm looping over in the template. The fields are implicitly added when simply stored to a variable within the class, but I can't figure out how to do that with a loop.

Stripped down code:
Python code:
class InputForm(forms.Form):
    fields = []

    fields.append(forms.CharField(widget=forms.Textarea(attrs={
        'cols': 75, 'rows': 30}), max_length=10000, help_text="Paste text here:"))

    extra_fields = 3
    for field in range(extra_fields):
        fields.append(forms.CharField(widget=forms.Textarea(attrs={
            'cols': 75, 'rows': 30}), max_length=10000,
            help_text="Enter additional text here:"))

    for field in fields:
        self.visible_fields.append(field) # attemped fix; not working.    
I'm using this standard bit in my template:

Python code:
            {% for hidden in form.hidden_fields %}
                {{ hidden }}
            {% endfor %}

            {% for field in form.visible_fields %}
                {{ field.errors }}
                {{ field.help_text}}<br/>
                {{ field }}
            {% endfor %}

Dominoes fucked around with this message at 14:21 on Dec 7, 2013

fuf
Sep 12, 2004

haha
I am going crazy trying to figure out how to get django set up with pip and virtualenv and all that jazz.

The Tango with Django tutorial wants you to use pythonbrew and "switch" to Python 2.7.5. This works fine, but then when I use pip to install django it installs under the system version of python, not the pythonbrew version. So everything stops with "module django not found".

So I figured I would forget pythonbrew and skip straight to using virtualenv and virtualenvwrapper, because they seem to be so popular. But it seems like virtualenv projects just use the system version of python? How do I get it to use Python 2.7.5?

Basically I have two questions. The first is the most important, because it'll give me something to aim for:

1) How do pros deploy django on a production server? Assuming I want it running on my own server and not on pythonanywhere etc. Do people run actual deployed django apps in virtual environments? Or is that just a development thing? Do you use the system install of Python, or a separate one? (PyPy?)

My other question is lazier, but any help appreciated:
2) What's the easiest way to install and use python 2.7.5 and django 1.5.4 on my development server?

Dominoes
Sep 20, 2007

Skip the virtual environment stuff for now; you don't need it to do TWD. You don't need the specific version they run either.

fuf
Sep 12, 2004

haha
Alright cool, I'll just use the system python interpreter while I do the tutorial and hope for the best.

But eventually I'll have to deal with the deployment question, and whether or not to use an isolated python interpreter, so I'd still be interested in hearing how other people do it. :)

evilentity
Jun 25, 2010
You can use specific python version with virtualenv with --python flag. Check the docs.

My dev server is a PI and it works fine with virtualenv. Prod will depend on the server at your disposal.

reitetsu
Sep 27, 2009

Should you find yourself here one day... In accordance with your crimes, you can rest assured I will give you the treatment you deserve.
I've just started my very first Django project, which right now aims to be a character builder for a tabletop roleplaying system. One day maybe I'll figure out how to do input not through the admin panel, but I'm taking it very slow so I don't get overwhelmed. My current stumbling block is an issue of display. I've got the contents of my database displaying just fine in a simple website, but I'd like to have it display as a repeating series of characters rather than just the stored integer.

My code right now is pretty simple, displaying like so in a table:
HTML code:
<table width="60%" border="0" align="center">
  <caption>
    <strong>Attributes</strong>
  </caption>
  <tr> 
    <td>Intelligence</td>
    <td>{{ character.intelligence }}</td>
    <td>Strength</td>
    <td>{{ character.strength }}</td>
    <td>Presence</td>
    <td>{{ character.presence }}</td>
  </tr>
</table>
I'd like to have the integer display a number of "O" equal to the value of a given Attribute, so if a character's Intelligence was 3, the box would display OOO. Later I'll actually make a graphic dot. But what I at least know how to do in Python in a simple for loop I don't know how to accomplish here.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

morcant posted:

I've just started my very first Django project, which right now aims to be a character builder for a tabletop roleplaying system. One day maybe I'll figure out how to do input not through the admin panel, but I'm taking it very slow so I don't get overwhelmed. My current stumbling block is an issue of display. I've got the contents of my database displaying just fine in a simple website, but I'd like to have it display as a repeating series of characters rather than just the stored integer.

My code right now is pretty simple, displaying like so in a table:
HTML code:
<table width="60%" border="0" align="center">
  <caption>
    <strong>Attributes</strong>
  </caption>
  <tr> 
    <td>Intelligence</td>
    <td>{{ character.intelligence }}</td>
    <td>Strength</td>
    <td>{{ character.strength }}</td>
    <td>Presence</td>
    <td>{{ character.presence }}</td>
  </tr>
</table>
I'd like to have the integer display a number of "O" equal to the value of a given Attribute, so if a character's Intelligence was 3, the box would display OOO. Later I'll actually make a graphic dot. But what I at least know how to do in Python in a simple for loop I don't know how to accomplish here.

I think you should be able to do something like this:


Python code:

    <td>Intelligence</td>
    <td>
	{% for i in character.intelligence %}
         *
        {% endfor %}
    </td>

EDIT: I was horribly wrong... I just tested and that doesn't work.


The "right" way would be to add a class to an element in the TD and have a tiling sprite image background. To do it your way you'll need to either create the strings and add them to the context, or make ranges and add them to the context, and then iterate over those ranges in the template.

Lumpy fucked around with this message at 16:28 on Dec 18, 2013

MonkeyMaker
May 22, 2006

What's your poison, sir?

morcant posted:

HTML code:
<table width="60%" border="0" align="center">
  <caption>
    <strong>Attributes</strong>
  </caption>
  <tr> 
    <td>Intelligence</td>
    <td>{{ character.intelligence }}</td>
    <td>Strength</td>
    <td>{{ character.strength }}</td>
    <td>Presence</td>
    <td>{{ character.presence }}</td>
  </tr>
</table>

So, this is possibly a bit beyond where you are but this is a great time to learn about custom template tags.

You mention being able to do it in Python. Well, tags let you write custom python to use in your templates.

Start off by creating a directory named `templatetags` in your app and create an `__init__.py` in there. Then create a file to hold your template tags and filters. Generally this is `<app_name>_tags.py` but you can call it whatever you want. I'll call it `character_tags.py` because I can.

So, in `character_tags.py`, we'll do:

code:
from django import template

register = template.Library()

def attribute_display(attribute):
	return ''.join(['o' for x in xrange(attribute)])

register.simple_tag(attribute_display)
Then, in your template, import the tag library and use it

HTML code:
{% load character_tags %}
<table width="60%" border="0" align="center">
  <caption>
    <strong>Attributes</strong>
  </caption>
  <tr> 
    <td>Intelligence</td>
    <td>{% atrtribute_display character.intelligence %}</td>
    <td>Strength</td>
    <td>{% attribute_display character.strength %}</td>
    <td>Presence</td>
    <td>{% attribute_display character.presence %}</td>
  </tr>
</table>
Now, I haven't tested this, but it should work. I'll leave it up to you to figure out how to register the tag through a decorator instead of the assignment call (it's a little cleaner and more common).

reitetsu
Sep 27, 2009

Should you find yourself here one day... In accordance with your crimes, you can rest assured I will give you the treatment you deserve.

It worked! Thank you very much! I'm not sure what decorators are as yet, but I'll do some research. :) I'll definitely figure it out for my second draft when I'll (hopefully) have stuff that responds to appropriate Attribute value - you can't be "Indomitable" without Resolve >= 3, etc.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
This logging thing is driving me mad. I don't even want to actually log SQL queries, I just want to know why it's not working.

Added my logger:
code:
LOGGING = {
...
    'loggers': {
        'django.db.backends': {
            'handlers': ['file'],
            'level': 'DEBUG'
        }
    }
}
Now pop into the python shell
code:
$ ./manage.py shell
>>> import logging
>>> logging.getLogger('django.db.backends').handlers[0].baseFilename
'/var/log/django/www.myawesomesite.com.log'
Ok, so it's got my file handler, try writing to it...
code:
>>> logging.getLogger('django.db.backends').debug('hello world')
That works fine - I'm tailing the log and I saw that entry get added.

When I hit my Django app through the webserver, however, nothing from django.db.backends gets written to the logs. If I change DEBUG=False to DEBUG=True in my settings, lots of stuff from django.db.backends gets written to the logs. I can't find anything that would suggest the logging is tied to that DEBUG setting though.

edit: ughhhh how did I miss this:

quote:

For performance reasons, SQL logging is only enabled when settings.DEBUG is set to True, regardless of the logging level or handlers that are installed.

fletcher fucked around with this message at 02:43 on Dec 19, 2013

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
code:
>>> MyAwesomeObject.objects.filter(some_field='').count()
1673
>>> change_some_data()
>>> MyAwesomeObject.objects.filter(some_field='').count()
1673
How come the count never changes until I disconnect from the shell and fire up a new one? When I run the COUNT(*) queries manually before and after change_some_data() the counts are different as expected, but not when I do it in the manage.py shell like above.

Dad Jokes
May 25, 2011

It's been a while since I last used Django, so has anyone used RedirectView on Django 1.6? I'm having some trouble getting the url reversal part to work, and Googling around isn't helping too much.

Essentially, I want to be able to direct urls like mysite.com/100?image=44 to urls like mysite.com/100/100?image=44 while preserving the query string.

I have a project with the app "mainapp". In my project-level urls.py, I have the following code:
Python code:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns("",
    url(r"^admin/", include(admin.site.urls)),
    url(r"^", include("mainapp.urls", namespace="mainapp"))
)
and in mainapp/urls.py, I have the following code:
Python code:
from django.conf.urls import patterns, url
from mainapp import views

urlpatterns = patterns("",
    url(r"^(?P<targWidth>\d+)/(?P<targHeight>\d+)/$", views.requestSize, name="request_size"),

    # redirect single-dimension square requests to 
    # corresponding width/height request
    url(r"^(?P<targSize>\d+)/$", views.SquareRedirectView.as_view(), name="request_square")
)
Finally, mainapp/views.py only has the following code:
Python code:
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.views.generic.base import RedirectView

def requestSize(request, targWidth, targHeight):
    return HttpResponse("Size requested: (%s, %s)" % (targWidth, targHeight))

# redirect view for redirecting a square dimension request 
# to a corresponding width/height request
class SquareRedirectView(RedirectView):
    permanent = False
    query_string = True
    pattern_name = "mainapp:request_size"

    def get_redirect_url(self, *args, **kwargs):
        targSize = kwargs.pop("targSize")
        kwargs["targWidth"] = kwargs["targHeight"] = targSize

        return super(SquareRedirectView, self).get_redirect_url(args, kwargs)
Although I'd expect request_square urls to be redirected to request_size urls, what happens instead is that get_redirect_url always returns None.

The Github source code just uses the reverse method, and if I debug by adding the line
Python code:
print reverse(self.pattern_name, args, kwargs)
to the get_redirect_url method before the return statement, I get an NoReverseMatch error that
pre:
u'mainapp' is not a registered namespace


However, if I have the request_square url call the following view code instead, things work fine, so I'm completely lost why it wouldn't work as a RedirectView.

Python code:
def requestSquare(request, targSize):
    return redirect(reverse('mainapp:request_size', 
                            kwargs={"targWidth":targSize,
                                    "targHeight":targSize})) 
Am I overlooking something on how reverse namespacing works for RedirectView classes? Googling just has people saying to add a namespace param to the project-level urls.py file, which I already have. :psyduck:

Dominoes
Sep 20, 2007

Anyone know how to run South? I did 'from south.db import db', and was greeted with "ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings."

I tried south.settings.configure() and django.settings.confgure(), but neither are valid commands.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Dominoes posted:

Anyone know how to run South? I did 'from south.db import db', and was greeted with "ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings."

I tried south.settings.configure() and django.settings.confgure(), but neither are valid commands.

I've been using South but I've never had to manually write an import statement like that, all I ever do is:

code:
$ ./manage.py schemamigration my_app --auto
$ ./manage.py migrate my_app
What is it that you are trying to do?

Also, you can specify that environment variable at the top of your script (none of my migrations actually do this though):
code:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings'
Did you follow the tutorial? http://south.readthedocs.org/en/latest/tutorial/part1.html

Dominoes
Sep 20, 2007

I was going off this Stack overflow thread

I'm trying to rename a column. I don't understand why Databases (and therefore Django models) are so finicky about changing things, but apparently South is the solution.

I want to run this: 'db.rename_column('app', 'old', 'new')', which requires importing db. I don't need to migrate anything, I just want to be able to change database columns without starting from scratch each time.

Dominoes fucked around with this message at 22:17 on Jan 14, 2014

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Dominoes posted:

I was going off this Stack overflow thread

I'm trying to rename a column. I don't understand why Databases (and therefore Django models) are so finicky about changing things, but apparently South is the solution.

I want to run this: 'db.rename_column('app', 'old', 'new')', which requires importing db. I don't need to migrate anything, I just want to be able to change database columns without starting from scratch each time.

I see, you want a data migration then.

First create an empty data migration:
code:
(myapp)greg@greg-mint15 ~/code/my_app $ ./manage.py datamigration myapp rename_thing1_to_thing2
Created 0018_rename_thing1_to_thing2.py.
Now open up the ####_rename_thing1_to_thing2.py file it created and add your db.rename_column stuff from that stackoverflow post.

Then run the migration:
code:
$ ./manage.py migrate myapp

Gmaz
Apr 3, 2011

New DLC for Aoe2 is out: Dynasties of India
I have a (probably) simple question regarding querying in Django.

Basically I have a time table and I want to query times around a certain value. For instance if I query for 15:00 I want it to show me the two nearest results that are higher and two that are lower than that time. I can't chain two slices together so I'm not sure how to limit results both higher and lower. Should I make two separate queries and then merge them together or is there a more elegant way?

Dominoes
Sep 20, 2007

Thanks fletcher - got it sorted using the first two lines you linked, after adding south to my installed apps, and running convert_to_south.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Cool! Glad you got it working.

My turn for a question - Is there a better way I should be doing something like this? I want it to handle the case where last_id might not be specified, or if it is, making sure it's the right data type.

code:
try:
    filter_criteria['id__gt'] = int(request.GET.get('last_id'))
except (TypeError, ValueError):
    pass

Dominoes
Sep 20, 2007

I've got an Openshift/Django issue:

I'm having difficulty getting stylesheets and my SQLite database working in Openshift. When attempting to access a page that uses the database, I get the following Django debug message: "no such table: mytable". I get the same in rhc tail. Everything else appears to work.


My local file setup:
code:
project
    project
        settings.py etc
    app
        normal django files and custom code here
    templates
        my templates are here
    static
        stylesheet is here
    mydatabase.db
For openshift, I modify the directory as follows:
code:
openshift appname
    wsgi
        project
            project
                settings.py etc
            app
                normal django files and custom code here
            templates
                my templates are here
            static
                stylesheet is here (NOT WORKING)
            mydatabase.db (NOT WORKING)
Relevant bits of my setup.py file:

Python code:
BASE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)
STATIC_PATH = os.path.join(BASE_DIR, 'static')
DATABASE_PATH = os.path.join(BASE_DIR, 'mydatabase.db')

...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': DATABASE_PATH,
    }

...

STATIC_ROOT = ''
STATIC_URL = '/static/'

Any ideas? It works fine when running locally.

Dominoes fucked around with this message at 18:49 on Jan 16, 2014

ass
Sep 22, 2011
Young Orc
Is The Django Book a good book to start with? I read some of it and I really liked it, but I was told it's extremely outdated.

ufarn
May 30, 2009

Cowabanga posted:

Is The Django Book a good book to start with? I read some of it and I really liked it, but I was told it's extremely outdated.
It is. It's a great explanation of why Django was designed the way it was, and truly the best programming/framework guide I've ever read, but I'd worry it teaches you something wrong or bad habits at this point.

ass
Sep 22, 2011
Young Orc

ufarn posted:

It is. It's a great explanation of why Django was designed the way it was, and truly the best programming/framework guide I've ever read, but I'd worry it teaches you something wrong or bad habits at this point.

Do you suggest an alternative?

ufarn
May 30, 2009

Cowabanga posted:

Do you suggest an alternative?
It's been asked and answered a billion times, but my answer should be somewhere in my post history.

I'd say try out the Django Book and find some example project to work on, and figure out what things you need to complete it.

etcetera08
Sep 11, 2008

Newer guides are http://gettingstartedwithdjango.com/ and http://www.tangowithdjango.com/

ass
Sep 22, 2011
Young Orc

Yeah, I'm really paranoid I'm gonna have a hard time with a tutorial that's crazy outdated, so these should do. Thanks!

Dominoes
Sep 20, 2007

Cowabanga posted:

Yeah, I'm really paranoid I'm gonna have a hard time with a tutorial that's crazy outdated, so these should do. Thanks!
TWD's fantastic, and current.

etcetera08
Sep 11, 2008

Once you get past the basics, I recommend spending some time reading through applicable Django source code too. Some of it isn't the best Python but most of it is well-documented and tested and I learned more about what I was doing through that method than anything else.

Of course, it won't make much sense until you get past the basics anyways.

Dominoes
Sep 20, 2007

Another tip: While you'll be fine with the official Django tutorial and TWD, if you're reading a tutorial that involves multiple third-party tools that are not working and/or confusing you, run.

Pythagoras a trois
Feb 19, 2004

I have a lot of points to make and I will make them later.

Dominoes posted:

Another tip: While you'll be fine with the official Django tutorial and TWD, if you're reading a tutorial that involves multiple third-party tools that are not working and/or confusing you, run.

Honestly, the tutorial and the docs will get you plenty far on their own as well.

Megaman
May 8, 2004
I didn't read the thread BUT...
I'm using aws for my django application, and I'm getting timeouts when uploading large files. Does anyone have an elegant solution for doing django uploads that don't timeout? I think the timeout is something to do with s3 not contacting the django app to say "there is still a connection, don't timeout for the user".

Dominoes
Sep 20, 2007

Megaman posted:

I'm using aws for my django application, and I'm getting timeouts when uploading large files. Does anyone have an elegant solution for doing django uploads that don't timeout? I think the timeout is something to do with s3 not contacting the django app to say "there is still a connection, don't timeout for the user".
Shot in the dark: Are you using read() instead of chunk()?

Megaman
May 8, 2004
I didn't read the thread BUT...

Dominoes posted:

Shot in the dark: Are you using read() instead of chunk()?

I'm using chunk

Damiya
Jul 3, 2012
So, potentially dumb question here but I've spent some time googling and have come up empty.

I have an app that users log into, and when a user logs in I want to spawn a persistent socket connection to an external service and associate that connection with the user

On a conceptual level, I basically want a stateful worker that I can use to drive events in my frontend via long polling or what have you.

Can anyone point me in the right direction?

Megaman
May 8, 2004
I didn't read the thread BUT...

Megaman posted:

I'm using chunk

Any ideas?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Megaman posted:

Any ideas?

What are you using to transfer the files from your django app server to S3?

Megaman
May 8, 2004
I didn't read the thread BUT...

fletcher posted:

What are you using to transfer the files from your django app server to S3?

Files are uploaded to the actual servers, then uploaded to s3. This seems like a step too many? Do people usually use forms to have users directly upload to s3 to get around using the servers? Then the issue is uuid/keys of said files.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Megaman posted:

Files are uploaded to the actual servers, then uploaded to s3. This seems like a step too many? Do people usually use forms to have users directly upload to s3 to get around using the servers? Then the issue is uuid/keys of said files.

That sounds fine, your servers probably have to be the proxy to s3 to avoid cross domain security stuff. But what are you using to communicate with S3? If you eliminate the S3 step and just save them to your servers, does the upload still timeout?

Adbot
ADBOT LOVES YOU

Megaman
May 8, 2004
I didn't read the thread BUT...

fletcher posted:

That sounds fine, your servers probably have to be the proxy to s3 to avoid cross domain security stuff. But what are you using to communicate with S3? If you eliminate the S3 step and just save them to your servers, does the upload still timeout?

Nope, the timeout happens between the server and s3. We also can't store on the server, we have tons of data, thus s3. I was thinking the client could upload from our app directly to s3, wouldn't that be a valid solution to this? We could just cut out the server.

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