Hiding auto-generated Django form fields

2012-07-12 Thread DF
I'm attempting to hide an auto-generated form field in a Django form using 
CSS. Unfortunately, to remove the entire field, the "control group" class 
requires an ID. The other IDs just use remove the form but leave the label.

Is there any way to achieve this? I need the form to remain there invisibly 
for auto-generated information but want to hide this from the user.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/0PQVngNKcCsJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django comments flag "cancel" returns incorrect url

2012-07-09 Thread DF
I've set up django's built in comments in my application and I'm employing 
the flagging ability. The flagging works fine, but the 'cancel" link that 
appears on the template returns the following error when clicked:

could not find http

The template/form is as follows:

{% extends "base.html" %}
{% load i18n %}

{% block title %}{% trans "Flag this comment" %}{% endblock %}

{% block content %}
{% trans "Are you sure you want to flag this comment?" %}

 {{ comment|linebreaks }}
 {% csrf_token %}
{% if next %}{% endif %}

 or cancel

  
 {% endblock %}
Any insight into this would be greatly appreciated.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/P1J0N0SiO4gJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Missing 'SITE_ID' breaks first Django app

2012-07-05 Thread DF
 

Hi. I just delayed my first Django app via Heroku and I'm having an issue 
that's proving very difficult to resolve. I have django-registration and 
profiles installed and apparently something runs afoul unless the 
'django.contrib.sites', and SITE_ID is removed from settings (this wasn't 
the case prior to deployment). Unfortunately, when content is submitted 
from a user to be displayed. I'm getting the following error:: 

TemplateSyntaxError at /Caught AttributeError while rendering: 'Settings' 
object has no attribute 'SITE_ID'. 

Adding these back just kills the whole app. Looking to see if anyone had 
any insight or advice on how to resolve this.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/TmDzJJKawfYJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Converting to Postgres database; error with UserProfile model

2012-07-05 Thread DF
This happened when I ran sync.db. All the other tables were created.

I'm using South but I ran sync.db first to create the initial tables. When 
I ran South, the 'profiles' app still didn't appear.

There's also a signals.py file with the following:

def create_profile(sender, instance, signal, created, **kwargs):
"""When user is created also create a matching profile."""
 
from stentorian.report.models import UserProfile
 
if created:
UserProfile(user = instance).save()

On Thursday, July 5, 2012 1:06:26 PM UTC-4, DF wrote:
>
> I have a problem that I hope someone with insight can aid with. My first 
> Django project is near completion and I’m currently transitioning to a 
> Postgres database in anticipation of deploying via Heroku. The process was 
> going fairly smoothly until this occurred when I ran python manage.py 
> syncdb:
>
> django.db.utils.DatabaseError: relation "report_userprofile" does not exist
> LINE 1: INSERT INTO "report_userprofile" ("user_id", "first_name", "...
>
> Apparently, it did not create DB tables for the UserProfile model. I’m now 
> getting this exception when I attempt to run the server:
>
> xception Type: DoesNotExist at /accounts/login/
> Exception Value: Site matching query does not exist.
>
> Among the additional apps I'm using for the project is django-profiles, 
> which I had some issues setting up which are apparently common. The 
> "Missing Manual" site –
> http://birdhouse.org/blog/2009/06/27/django-profiles/ – helped resolve 
> those but may have led to the current problem.
>
> I am using the signals.post_save.connect(create_profile, sender=User) 
> recommended there. I was researching what might have gone wrong and came 
> across this post on Google Groups and answer which states that “If you’re 
> using a post_save signal on User you can’t do that because it results in a 
> race condition." I’m wondering if this may be causing the issue and, 
> obviously, what would be best to resolve it and get these tables into the 
> new database and functioning.
>
> This is the database model:
>
> class UserProfile(models.Model):
>
> user = models.OneToOneField(User, unique=True, related_name="profile")
>
> first_name = models.CharField(max_length=25)
>
> last_name = models.CharField(max_length=35)
>
> email = models.EmailField()
>
> birth_date = models.DateField(blank=True, null=True)
>
> city = models.CharField(max_length=25)
>
> state = models.CharField(max_length=20)
>
> zip_code = models.CharField(max_length=10)
>
> profile_pic = models.ImageField(upload_to='profilepictures', 
> blank=True)
>
>
> def __unicode__(self):
>
> return " %s" % (self.user)
>
>
> def get_absolute_url(self):
>
> return ('profiles_profile_detail', (), { 'username': 
> self.user.username })
>
> get_absolute_url = models.permalink(get_absolute_url)
>
> signals.post_save.connect(create_profile, sender=User)
>
>
> Any insight into how to remedy this issue would be greatly appreciated.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/0eVvl2dDNI8J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Converting to Postgres database; error with UserProfile model

2012-07-05 Thread DF
I have a problem that I hope someone with insight can aid with. My first 
Django project is near completion and I’m currently transitioning to a 
Postgres database in anticipation of deploying via Heroku. The process was 
going fairly smoothly until this occurred when I ran python manage.py 
syncdb:

django.db.utils.DatabaseError: relation "report_userprofile" does not exist
LINE 1: INSERT INTO "report_userprofile" ("user_id", "first_name", "...

Apparently, it did not create DB tables for the UserProfile model. I’m now 
getting this exception when I attempt to run the server:

xception Type: DoesNotExist at /accounts/login/
Exception Value: Site matching query does not exist.

Among the additional apps I'm using for the project is django-profiles, 
which I had some issues setting up which are apparently common. The 
"Missing Manual" site –http://birdhouse.org/blog/2009/06/27/django-profiles/ – 
helped resolve those but may have led to the current problem.

I am using the signals.post_save.connect(create_profile, sender=User) 
recommended there. I was researching what might have gone wrong and came 
across this post on Google Groups and answer which states that “If you’re 
using a post_save signal on User you can’t do that because it results in a 
race condition." I’m wondering if this may be causing the issue and, 
obviously, what would be best to resolve it and get these tables into the 
new database and functioning.

This is the database model:

class UserProfile(models.Model):

user = models.OneToOneField(User, unique=True, related_name="profile")

first_name = models.CharField(max_length=25)

last_name = models.CharField(max_length=35)

email = models.EmailField()

birth_date = models.DateField(blank=True, null=True)

city = models.CharField(max_length=25)

state = models.CharField(max_length=20)

zip_code = models.CharField(max_length=10)

profile_pic = models.ImageField(upload_to='profilepictures', blank=True)


def __unicode__(self):

return " %s" % (self.user)


def get_absolute_url(self):

return ('profiles_profile_detail', (), { 'username': 
self.user.username })

get_absolute_url = models.permalink(get_absolute_url)

signals.post_save.connect(create_profile, sender=User)


Any insight into how to remedy this issue would be greatly appreciated.


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/tuKKBCicojMJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Inheriting template with a form into an existing template

2012-07-03 Thread DF
I have a simple note taking part of my application I'm trying to converge 
into one template. Currently, I have one template and view that renders and 
posts the form and another that displays the results. I'd like to 
amalgamate these into one where the form exists and the results are 
displayed on the same page.

This seems to be something that be achieved with template inheritance, but 
I'm not sure how to alter the views so that both of these results can 
appear in the same template. I've looked around for answers but can't seem 
to find what I need to achieve this. Any help that could also inform me on 
how to properly achieve this moving forward would be appreciated. This is 
one of those areas I've been anticipating learning but it's been more 
difficult that I assumed. The essential code is posted below:

Views for submitting and displaying notes:

@login_required
def submit_note(request):
if request.method == 'POST':
notes_form = NotesForm(request.POST, request.FILES)
if notes_form.is_valid():
new_note = notes_form.save(commit=False)
new_note.author = request.user
new_note.save()
return HttpResponseRedirect( "" )
else:
notes_form = NotesForm()
return render_to_response("write_note/notes.html", {'form': 
notes_form}, context_instance=RequestContext(request))

@login_required
def all_notes(request):
all_notes = Notes.objects.all().order_by('-date')
paginate = paginated_stories(request, all_notes)
return render_to_response("report/notes.html",
   {'notes': paginate},
context_instance=RequestContext(request))

Current basic templates to submit and display:

{% extends 'base.html' %}
{% block page_title %}Notebook{% endblock %}
{% block headline %}Notebook{% endblock %}
{% block content %}
Write and save notes, quotes and other story info



{% csrf_token %}
{{ form.as_p }}





{% endblock %}

{% extends 'base.html' %}
{% block page_title %}Notebook{% endblock %}
{% block headline %}Notebook{% endblock %}

{% block content %}


{% if notes %}
{% for note in user.notes.all reversed %}
{{ note.title }}
{{ note.date }}
{{ note.copy }}
{% endfor %}
 {% else %}
You have no notes stored.
 {% endif %}


{% endblock content %}

And the two urls:

url(r'^write_note/$', 'stentorian.report.views.submit_note', 
name='write_note'),
url(r'^notes/', 'stentorian.report.views.all_notes', name='all_notes')

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/IG6vV9MaSVoJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Using django-ratings; need help

2012-07-02 Thread DF
I've been trying for two weeks to implement the highly regarded 
django-ratings with zero success.

I've followed all directions, which are not that detailed, and cannot 
figure out how to actually present a means for a user to submit a rating 
with the template.

There are no directions on how to load template tags associated with it, so 
it resulted in errore. After looking through the code, it appears "ratings" 
was the proper way to load the tags within the template, so I employed that.

I added 'djangoratings' to settings.py.

The following to my model:

rating = RatingField(range=5)

I also did the following to urls.py:

from djangoratings.views import AddRatingFromModel

url(r'rate-my-post/(?P\d*)/(?P\d*)/', 
AddRatingFromModel(), {
'app_label': 'report',
'model': 'story',
'field_name': 'rating',
}),

Added this to the template:

{% rating_by_user user on story.rating as vote %}

And nothing appears. No means for the user to vote. Nothing.

I cannot figure out what may be wrong here and after two weeks of tweaking 
and trying different methods, nothing works.

If anyone has an idea of what is required to present some interface for a 
user to vote using this app, I would be extremely grateful.




-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/MPTvcHpbZ5QJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Implementing Django Search

2012-06-19 Thread DF
Thank you. I ended up using Haystack but I appreciate your insight.

On Tuesday, June 19, 2012 12:08:44 AM UTC-4, Daniel Sokolowski wrote:
>
> I also found that piece of code when I needed to implement search - it 
> was confusing so I ended up with my own approach that was easier to 
> understand and simpler at least to me - I pasted an example of live code 
> here: http://dpaste.org/KYhUq/ 
>
> The searching piece of code is in the form_valid() method: 
>
> query = (query.filter(name__icontains=bit) | 
> query.filter(description__icontains=bit)) 
>
> This filters the query down on each loop of the word user typed, you 
> would adjust that according to your model fields. 
>
> Hope that helps. 
>
> On 18/06/2012 14:23, DF wrote: 
> > I'm working on my first project and I'm attempting to implement a 
> > basic search function where users can search for a specific terms. 
> > 
> > There are many options available, most a bit too heavy for what I 
> > require. I found this posting which illustrates how to implement a 
> > basic search function that sounds ideal: 
> > 
> > 
> http://julienphalip.com/post/2825034077/adding-search-to-a-django-site-in-a-snap#disqus_thread
>  
> > 
> > The problem: the documentation is a bit incomplete, especially for a 
> > newbie. And I could use some help from those with experience on how to 
> > implement this. 
> > 
> > The first action is to create a file within the project � say 
> > search.py � with the following code: 
> > 
> > import re 
> > 
> > from django.db.models import Q 
> > 
> > def normalize_query(query_string, 
> > findterms=re.compile(r'"([^"]+)"|(\S+)').findall, 
> > normspace=re.compile(r'\s{2,}').sub): 
> > ''' Splits the query string in invidual keywords, getting rid of 
> > unecessary spaces 
> > and grouping quoted words together. 
> > Example: 
> > >>> normalize_query('  some random  words "with   quotes  " and   
> spaces') 
> > ['some', 'random', 'words', 'with quotes', 'and', 'spaces'] 
> > ''' 
> > return [normspace(' ', (t[0] or t[1]).strip()) for t in 
> > findterms(query_string)] 
> > 
> > def get_query(query_string, search_fields): 
> > ''' Returns a query, that is a combination of Q objects. That 
> > combination 
> > aims to search keywords within a model by testing the given 
> > search fields. 
> > ''' 
> > query = None # Query to search for every search term 
> > terms = normalize_query(query_string) 
> > for term in terms: 
> > or_query = None # Query to search for a given term in each field 
> > for field_name in search_fields: 
> > q = Q(**{"%s__icontains" % field_name: term}) 
> > if or_query is None: 
> > or_query = q 
> > else: 
> > or_query = or_query | q 
> > if query is None: 
> > query = or_query 
> > else: 
> > query = query & or_query 
> > return query 
> > 
> > Then the next step would be to import this file into the views � 
> > import search (not sure if the app name should proceed this). Then add 
> > this view, with the object detail changed to match my model: 
> > 
> > def search(request): 
> > query_string = '' 
> > found_entries = None 
> > if ('q' in request.GET) and request.GET['q'].strip(): 
> > query_string = request.GET['q'] 
> > entry_query = get_query(query_string, ['title', 'body',]) 
> > found_entries = 
> > Entry.objects.filter(entry_query).order_by('-pub_date') 
> > 
> > return render_to_response('search/search_results.html', 
> >   { 'query_string': query_string, 
> > 'found_entries': found_entries }, 
> >   context_instance=RequestContext(request)) 
> > 
> > After this, I'm a bit stumped. 
> > 
> > I assume this requires a basic url for the urls.py file, which seems 
> > straightforward enough. But I'm not sure how to place this within a 
> > template, what tags to use, etc. I have a search bar form on my main 
> > template page to which I would like to attach this. But returning the 
> > search/search_results.html template with the appropriate tags is a bit 
> > head scratching. 
> > 
> > This is a fairly long post but if anyone could provide some insight on 
> > implementing this s

Re: Implementing Django Search

2012-06-18 Thread DF
Does it provide instructions on connecting it to a search form? Dumb 
question, but sometimes documentation can be lacking.

On Monday, June 18, 2012 2:40:58 PM UTC-4, Nikolas Stevenson-Molnar wrote:
>
> I've used Haystack with Whoosh: http://haystacksearch.org/. It's 
> straight-forward, well documented, and mimics the Django ORM. No need to 
> parse the query yourself or anything like that, just pass the raw input 
> to Haystack and enjoy delicious search results :) 
>
> _Nik 
>
> On 6/18/2012 11:23 AM, DF wrote: 
> > I'm working on my first project and I'm attempting to implement a 
> > basic search function where users can search for a specific terms. 
> > 
> > There are many options available, most a bit too heavy for what I 
> > require. I found this posting which illustrates how to implement a 
> > basic search function that sounds ideal: 
> > 
> > 
> http://julienphalip.com/post/2825034077/adding-search-to-a-django-site-in-a-snap#disqus_thread
>  
> > 
> > The problem: the documentation is a bit incomplete, especially for a 
> > newbie. And I could use some help from those with experience on how to 
> > implement this. 
> > 
> > The first action is to create a file within the project � say 
> > search.py � with the following code: 
> > 
> > import re 
> > 
> > from django.db.models import Q 
> > 
> > def normalize_query(query_string, 
> > findterms=re.compile(r'"([^"]+)"|(\S+)').findall, 
> > normspace=re.compile(r'\s{2,}').sub): 
> > ''' Splits the query string in invidual keywords, getting rid of 
> > unecessary spaces 
> > and grouping quoted words together. 
> > Example: 
> > 
> > >>> normalize_query('  some random  words "with   quotes  " 
> > and   spaces') 
> > ['some', 'random', 'words', 'with quotes', 'and', 'spaces'] 
> > 
> > ''' 
> > return [normspace(' ', (t[0] or t[1]).strip()) for t in 
> > findterms(query_string)] 
> > 
> > def get_query(query_string, search_fields): 
> > ''' Returns a query, that is a combination of Q objects. That 
> > combination 
> > aims to search keywords within a model by testing the given 
> > search fields. 
> > 
> > ''' 
> > query = None # Query to search for every search term 
> > terms = normalize_query(query_string) 
> > for term in terms: 
> > or_query = None # Query to search for a given term in each field 
> > for field_name in search_fields: 
> > q = Q(**{"%s__icontains" % field_name: term}) 
> > if or_query is None: 
> > or_query = q 
> > else: 
> > or_query = or_query | q 
> > if query is None: 
> > query = or_query 
> > else: 
> > query = query & or_query 
> > return query 
> > 
> > Then the next step would be to import this file into the views � 
> > import search (not sure if the app name should proceed this). Then add 
> > this view, with the object detail changed to match my model: 
> > 
> > def search(request): 
> > query_string = '' 
> > found_entries = None 
> > if ('q' in request.GET) and request.GET['q'].strip(): 
> > query_string = request.GET['q'] 
> > 
> > entry_query = get_query(query_string, ['title', 'body',]) 
> > 
> > found_entries = 
> > Entry.objects.filter(entry_query).order_by('-pub_date') 
> > 
> > return render_to_response('search/search_results.html', 
> >   { 'query_string': query_string, 
> > 'found_entries': found_entries }, 
> >   context_instance=RequestContext(request)) 
> > 
> > After this, I'm a bit stumped. 
> > 
> > I assume this requires a basic url for the urls.py file, which seems 
> > straightforward enough. But I'm not sure how to place this within a 
> > template, what tags to use, etc. I have a search bar form on my main 
> > template page to which I would like to attach this. But returning the 
> > search/search_results.html template with the appropriate tags is a bit 
> > head scratching. 
> > 
> > This is a fairly long post but if anyone could provide some insight on 
> > implementing this search function, it would be much appreciated. Thanks. 
> > 
> > 
> > 
> > -- 
> > You received this messag

Implementing Django Search

2012-06-18 Thread DF
I'm working on my first project and I'm attempting to implement a basic 
search function where users can search for a specific terms.

There are many options available, most a bit too heavy for what I require. 
I found this posting which illustrates how to implement a basic search 
function that sounds ideal: 

http://julienphalip.com/post/2825034077/adding-search-to-a-django-site-in-a-snap#disqus_thread

The problem: the documentation is a bit incomplete, especially for a 
newbie. And I could use some help from those with experience on how to 
implement this.

The first action is to create a file within the project – say search.py – 
with the following code:

import re

from django.db.models import Q

def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r'\s{2,}').sub):
''' Splits the query string in invidual keywords, getting rid of 
unecessary spaces
and grouping quoted words together.
Example:

>>> normalize_query('  some random  words "with   quotes  " and   
spaces')
['some', 'random', 'words', 'with quotes', 'and', 'spaces']

'''
return [normspace(' ', (t[0] or t[1]).strip()) for t in 
findterms(query_string)] 

def get_query(query_string, search_fields):
''' Returns a query, that is a combination of Q objects. That 
combination
aims to search keywords within a model by testing the given search 
fields.

'''
query = None # Query to search for every search term
terms = normalize_query(query_string)
for term in terms:
or_query = None # Query to search for a given term in each field
for field_name in search_fields:
q = Q(**{"%s__icontains" % field_name: term})
if or_query is None:
or_query = q
else:
or_query = or_query | q
if query is None:
query = or_query
else:
query = query & or_query
return query

Then the next step would be to import this file into the views – import 
search (not sure if the app name should proceed this). Then add this view, 
with the object detail changed to match my model:

def search(request):
query_string = ''
found_entries = None
if ('q' in request.GET) and request.GET['q'].strip():
query_string = request.GET['q']

entry_query = get_query(query_string, ['title', 'body',])

found_entries = 
Entry.objects.filter(entry_query).order_by('-pub_date')

return render_to_response('search/search_results.html',
  { 'query_string': query_string, 'found_entries': 
found_entries },
  context_instance=RequestContext(request))

After this, I'm a bit stumped.

I assume this requires a basic url for the urls.py file, which seems 
straightforward enough. But I'm not sure how to place this within a 
template, what tags to use, etc. I have a search bar form on my main 
template page to which I would like to attach this. But returning the 
search/search_results.html template with the appropriate tags is a bit head 
scratching.

This is a fairly long post but if anyone could provide some insight on 
implementing this search function, it would be much appreciated. Thanks.



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/6jWgePRRzQYJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How to add Google Map Markers With Django Template Tags

2012-05-31 Thread DF
That's interesting, but mine seems like it could be less involved. This is 
what I attempted, which failed:

http://dpaste.org/55T9x/

On Thursday, May 31, 2012 12:32:26 PM UTC-4, DF wrote:
>
> I'm trying to place markers based on the latitude and longitude stored in 
> a model on a Google Map using the API and HTML5 geolocation.
>
> The issue is how to loop through the lat/lon info for each object stored 
> in the database within JavaScript tags using template keywords, which I'm 
> not sure can be done in Django.
>
> I found a similar question which I mildly modified and placed within a 
> template – not a separate script file – but it doesn't seem to work:
>
> function loadMarkers(){
> {% for story in stories %}
> var point = new 
> google.maps.LatLng({{story.latitude}},{{story.longitude}});
> var marker = new google.maps.Marker({
> position: point,
> map: map
> });
> {% endfor %}
> }
>
> Any insight on how to properly loop through items in a stored Django 
> object with lat, lon info and place these on a Google Map using the API 
> would be very appreciated.
>

On Thursday, May 31, 2012 12:32:26 PM UTC-4, DF wrote:
>
> I'm trying to place markers based on the latitude and longitude stored in 
> a model on a Google Map using the API and HTML5 geolocation.
>
> The issue is how to loop through the lat/lon info for each object stored 
> in the database within JavaScript tags using template keywords, which I'm 
> not sure can be done in Django.
>
> I found a similar question which I mildly modified and placed within a 
> template – not a separate script file – but it doesn't seem to work:
>
> function loadMarkers(){
> {% for story in stories %}
> var point = new 
> google.maps.LatLng({{story.latitude}},{{story.longitude}});
> var marker = new google.maps.Marker({
> position: point,
> map: map
> });
> {% endfor %}
> }
>
> Any insight on how to properly loop through items in a stored Django 
> object with lat, lon info and place these on a Google Map using the API 
> would be very appreciated.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/016Mbbw0JsoJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



How to add Google Map Markers With Django Template Tags

2012-05-31 Thread DF
I'm trying to place markers based on the latitude and longitude stored in a 
model on a Google Map using the API and HTML5 geolocation.

The issue is how to loop through the lat/lon info for each object stored in 
the database within JavaScript tags using template keywords, which I'm not 
sure can be done in Django.

I found a similar question which I mildly modified and placed within a 
template – not a separate script file – but it doesn't seem to work:

function loadMarkers(){
{% for story in stories %}
var point = new 
google.maps.LatLng({{story.latitude}},{{story.longitude}});
var marker = new google.maps.Marker({
position: point,
map: map
});
{% endfor %}
}

Any insight on how to properly loop through items in a stored Django object 
with lat, lon info and place these on a Google Map using the API would be 
very appreciated.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/zTEN_VxzQkAJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django, PyCharm Module Error (Time Machine, Directory Duplication)

2012-05-26 Thread DF
The following issue has been plaguing me for many hours now and was hoping 
someone might have some insight.

I've been working on my first Django project in PyCharm with few issues. 
This morning, to update software, I closed the file and restarted the 
computer. When i opened the file and ran the server again, I received the 
following error:

ImportError: No module named Stentorian

Stentorian is the name of the project. I have not been able to find any 
remedy. I was researching for hours and decided to go back through the Time 
Machine on the Mac to see if anything changed from previous versions. When 
doing so, I found a strange inconsistency that may be related to this issue.

The project folder/directory is named "stentorian." Some time during the 
last week, the directory replicated another copy of the folder/directory 
called "Stentorian" – capitalized – in the same parent directory. While 
going through Time Machine, some time in the pre-dawn hours, the second 
folder/directory "Stentorian" disappeared. When I reopened the file this 
morning after installing software updates and rebooting, I received the 
above error, which has been impossible to resolve. What seems notable is 
that the module missing has the uppercase "Stentorian," the same folder 
that seemingly vanished.

I'm not sure why the duplicate, uppercase folder/directory was created to 
begin with, why it disappeared and how this may be related to my problem. I 
cannot find any documentation about this. I also added the lowercase 
directory to the sys.path to no avail. I also tried to restore the 
mysterious duplicate "Stentorian" from Time Machine to the current 
directory but it wouldn't restore it because it was the same name, just 
uppercase. If anyone can shed some light on what might be happening and how 
to resolve this, I'd be most appreciative. This is very strange and I'm at 
a bit of a loss.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/-XaS8BpMntYJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django Projects Working Fine; Reopened and Import Module Error

2012-05-26 Thread DF
I've been working on a Django project, my first, with no issues. I closed 
the file and restarted the computer for software updates and I'm now 
receiving the following error:

Traceback (most recent call last):
  File "manage.py", line 14, in 
execute_manager(settings)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py",
 
line 436, in execute_manager
setup_environ(settings_mod)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py",
 
line 419, in setup_environ
project_module = import_module(project_name)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py",
 
line 35, in import_module
__import__(name)

ImportError: No module named Stentorian

The module name is the name of the project. I cannot figure out what could 
possibly be going wrong to cause this error. Any insight into the would be 
most appreciated.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/hm3iNCgsTe0J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django Error; how to empty tmp directory, cache

2012-05-26 Thread DF


A TemplateSyntaxError error has occurred in my previously functional 
project and after trying for hours to resolve it, it was determined it 
might be a cache error and to empty the tmp directory at the root (the 
template had been working fine for a week and nothing was changed that 
might have affected it).

I've searched online and can't seem to find a safe means of performing 
this. I don't want to inadvertently remove any essential information. If 
anyone knows how to perform this safely, it would be much appreciated. 

I found this but not sure if it's safe:

$ python manage.py shell

>>> from django.core.cache import cache
>>> cache.clear()

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/D8yGV1c5De8J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django GeoIP Module not found; can't remedy

2012-05-24 Thread DF
It appeared an import statement error caused the initial problem. But once 
that was fixed, the following error results:

">>> from django.contrib.gis.utils.geoip import GeoIP
Traceback (most recent call last):
  File "", line 1, in 
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/gis/utils/geoip.py",
 
line 68, in 
lgeoip = CDLL(lib_path)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py",
 
line 353, in __init__
self._handle = _dlopen(self._name, mode)
OSError: dlopen(/usr/local/lib/libGeoIP.dylib, 6): no suitable image found. 
 Did find:
/usr/local/lib/libGeoIP.dylib: mach-o, but wrong architecture"

Anyone have a clue on how to remedy this?

On Thursday, May 24, 2012 7:10:50 PM UTC-4, DF wrote:
>
> I've spent several hours attempting to resolve my problems setting up 
> GeoIP in Django to no avail and was hoping to get some guidance on what the 
> problem(s) might be.
>
> I'm working on an existing Django application that required some 
> geolocation abilities, specifically getting a users IP and lat/long and 
> then placing that info on a map marker. GeoIP and the associated libraries 
> appeared to be the best solution for the first step.
>
> I installed GeoIP on a Mac using Homebrew. I then manually created a 
> folder in the root directory of my project with the GeoIPv6.data and 
> GeoLiteCity.dat files. After this, I added the path in my settings file:
>
> import os
>
> DEBUG = True
>
> TEMPLATE_DEBUG = DEBUG
>
> BASE_DIR = os.path.dirname(os.path.abspath(__file__))
>
> GEOIP_PATH = os.path.join(BASE_DIR, 'geoip'),
>
> I then opened a command shell for the project and received the following 
> error:
>
> >>> from django.contrib.gis.geoip import GeoIP
>
> Traceback (most recent call last):
>
>   File "", line 1, in 
>
> ImportError: No module named geoip
>
> I can't seem to remedy this problem. One issue that may be the cause is 
> extracting the two dat.gz files was an issue. Neither could be unzipped 
> from the command line – neither are .zip files – and had to use Stuffit 
> Expander to open these. The resulting dat files in my project IDE (pyCharm) 
> have a VLC (?) icon on each. Perhaps this is part of the issue (finding a 
> way to uncompress the file was a challenge in itself). I'm not sure as the 
> module was not even found.
>
> Any help would be extremely appreciated in resolving this issue as I can't 
> progress any further without figuring out what's wrong.
>
> Many thanks.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/HYN3pfOXCNIJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django GeoIP Module not found; can't remedy

2012-05-24 Thread DF


I've spent several hours attempting to resolve my problems setting up GeoIP 
in Django to no avail and was hoping to get some guidance on what the 
problem(s) might be.

I'm working on an existing Django application that required some 
geolocation abilities, specifically getting a users IP and lat/long and 
then placing that info on a map marker. GeoIP and the associated libraries 
appeared to be the best solution for the first step.

I installed GeoIP on a Mac using Homebrew. I then manually created a folder 
in the root directory of my project with the GeoIPv6.data and 
GeoLiteCity.dat files. After this, I added the path in my settings file:

import os

DEBUG = True

TEMPLATE_DEBUG = DEBUG

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

GEOIP_PATH = os.path.join(BASE_DIR, 'geoip'),

I then opened a command shell for the project and received the following 
error:

>>> from django.contrib.gis.geoip import GeoIP

Traceback (most recent call last):

  File "", line 1, in 

ImportError: No module named geoip

I can't seem to remedy this problem. One issue that may be the cause is 
extracting the two dat.gz files was an issue. Neither could be unzipped 
from the command line – neither are .zip files – and had to use Stuffit 
Expander to open these. The resulting dat files in my project IDE (pyCharm) 
have a VLC (?) icon on each. Perhaps this is part of the issue (finding a 
way to uncompress the file was a challenge in itself). I'm not sure as the 
module was not even found.

Any help would be extremely appreciated in resolving this issue as I can't 
progress any further without figuring out what's wrong.

Many thanks.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/krtmdm5BjQ4J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: GeoIP install failure, advice needed

2012-05-24 Thread DF
Tried that. Got this:

"Cowardly refusing to `sudo brew link'"



On Thursday, May 24, 2012 5:41:39 PM UTC-4, Andre Terra (airstrike) wrote:
>
> sudo brew link geoip? Total guess, btw.
>
>
> Cheers,
> AT
>
> On Thu, May 24, 2012 at 6:39 PM, DF <donfernan...@gmail.com> wrote:
>
>> Several hours of frustration here and looking to see if anyone has any 
>> advice.
>>
>> I'm trying to install GeoIP vie Homebrew and receive the following error 
>> just prior to the install finishing:
>>
>> "Error: The linking step did not complete successfully
>> The formula built, but is not symlinked into /usr/local
>> You can try again using `brew link geoip'"
>>
>>
>> brew link geoip returned this error:
>>
>> "Error: Could not symlink file: 
>> /usr/local/Cellar/geoip/1.4.8/etc/GeoIP.conf.default
>> /usr/local/etc is not writable. You should change its permissions."
>>
>>
>> I'm not entirely familiar with permissions and such and was wondering 
>> what I needed to do from the command line to get this to link properly. Any 
>> help greatly appreciated.
>>
>>  -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msg/django-users/-/nmmmuD9eA0gJ.
>> To post to this group, send email to django-users@googlegroups.com.
>> To unsubscribe from this group, send email to 
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at 
>> http://groups.google.com/group/django-users?hl=en.
>>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/XCT3B0AnL5UJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



GeoIP install failure, advice needed

2012-05-24 Thread DF
Several hours of frustration here and looking to see if anyone has any 
advice.

I'm trying to install GeoIP vie Homebrew and receive the following error 
just prior to the install finishing:

"Error: The linking step did not complete successfully
The formula built, but is not symlinked into /usr/local
You can try again using `brew link geoip'"


brew link geoip returned this error:

"Error: Could not symlink file: 
/usr/local/Cellar/geoip/1.4.8/etc/GeoIP.conf.default
/usr/local/etc is not writable. You should change its permissions."


I'm not entirely familiar with permissions and such and was wondering what 
I needed to do from the command line to get this to link properly. Any help 
greatly appreciated.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/nmmmuD9eA0gJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Inserting HTML5 Coordinates Into Django Form

2012-05-21 Thread DF
I'm wading – carefully – into some basic geolocation using HTML5. I 
currently have a meta form that has space for lat and long coordinates and 
have found the proper code to obtain those coordinates using the Google 
Maps API (pretty simple stuff).

Next step: inserting those coordinates automatically into the form. The 
application would ideally allow users to make posts and store their 
coordinates for future reference and filtering (this is a big endeavor one 
step at a time).

I haven't yet explored mixing JavaScript with Django in this manner and was 
looking to see if there's a straightforward manner for doing this. Any 
resources, experience or expertise on this would be greatly appreciated. In 
the end, for context's sake, I would like users to have the ability to 
search for localized posts via the map and have the posts corresponding to 
the area display on screen.

Thanks for any insight.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/CkxAVz64tgQJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Trying to Edit Existing Post; Can't Get Form to Display

2012-05-21 Thread DF
Thanks for that insight. It's always good to reinforce best practices for 
newcomers like myself.

On Monday, May 21, 2012 7:47:33 AM UTC-4, bruno desthuilliers wrote:
>
> On May 19, 5:41 pm, Jonathan Baker  
> wrote: 
>
> Just a note about best practises: 
>
> > 
> > # views.py 
>
> (snip) 
>
> > return HttpResponseRedirect("/report/all/") 
>
> Better to use named urls and django.core.urlresolvers.reverse, this 
> avoids quite a lot of pain and trouble when you have to change your 
> urls schemes. 
>
> My 2 cents...

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/cVBo6dUQIlkJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Trying to Edit Existing Post; Can't Get Form to Display

2012-05-19 Thread DF
Perfect! That worked!

Thank you so much! I was stumped. Your revisions were much simpler and easy 
to understand as well. I really appreciate when I can learn something, 
especially a more straightforward process that is less complex and achieves 
the same desired results.

Thank you, again!

On Saturday, May 19, 2012 11:41:51 AM UTC-4, jondbaker wrote:
>
> OK, I spent some more time with this. Firstly, I've included a different 
> way to populate the author field. With this update, the ModelForm only 
> needs the following:
>
> # forms.py
> class StoryForm(forms.ModelForm):
> class Meta:
> model = Story
> exclude = ('author',)
>
> Next I simplified your views a little bit. When dealing with the .save() 
> method of a ModelForm, commit=True is the default. This allows you to use 
> commit=False, and then manually adjust attributes of the object, and then 
> save it when you're done. This is a great opportunity to save the author 
> field.
>
> # views.py
> @login_required
> def submit_story(request):
> if request.method =="POST":
> story_form = StoryForm(request.POST, request.FILES)
> if story_form.is_valid():
> new_story = story_form.save(commit=false)
> new_story.author = request.user
> new_story.save()
> return HttpResponseRedirect("/report/all/")
> else: # GET request
> story_form = StoryForm()
> return render_to_response("report/report.html", {'form': story_form}, 
> context_instance=RequestContext(request))
>
> @login_required
> def edit_story(request, story_id)
> story = get_object_or_404(Story, pk=story_id, author=request.user)
> if request.method == 'POST':
> story_form = StoryForm(request.POST, request.FILES, instance=story)
> if story_form.is_valid():
> story_form.save()
> return HttpResponseRedirect("/profiles/user_profile")
> else: # GET request
> story_form = StoryForm(instance=story)
> return render_to_response('report/storyedit.html', {'form': 
> story_form}, context_instance=RequestContext(request))
>
> I hope this helps a little.
> Jonathan
>
>
> On Fri, May 18, 2012 at 5:19 PM, DF <donfernan...@gmail.com> wrote:
>
>> Thanks. I get this error using that code:
>>
>> TypeError at /report/detail/30/edit/ 
>>
>> __init__() takes at least 2 arguments (1 given)
>>
>> This is referring to this line:
>>
>>   story_form = StoryForm(instance=story)
>>
>> I added a "story_id" argument to this, which brought up the form, but 
>> when I submitted it, it returned the form with errors listing all the 
>> fields as empty.
>>
>> This is far trickier than I thought.
>>
>>
>>
>> On Friday, May 18, 2012 7:01:25 PM UTC-4, jondbaker wrote:
>>>
>>> Hmmm... I don't think you need to pass 'request.user' in as an argument. 
>>> Also, you want to be sure that the 'instance' you pass as an argument to 
>>> the model form is the model record you want to update. For instance:
>>>
>>> def edit_story(request, story_id)
>>> story = get_object_or_404(Story, pk=story_id)
>>> if request.method == 'POST':
>>> story_form = StoryForm(request.POST, request.FILES, 
>>> instance=story)
>>> if story_form.is_valid():
>>> story_form.save()
>>> return HttpResponseRedirect("/**profiles/user_profile")
>>> else: # GET request
>>> story_form = StoryForm(instance=story)
>>> return render_to_response('report/sto**ryedit.html', {'form': 
>>> story_form}, context_instance=RequestContex**t(request))
>>>
>>>
>>>
>>> On Fri, May 18, 2012 at 4:52 PM, DF <donfernan...@gmail.com> wrote:
>>>
>>>> Thanks. This worked:
>>>>
>>>> else:
>>>> story_form = StoryForm(request.user, instance=story_form)
>>>>
>>>>
>>>> One problem: it just adds a new version of the story instead of 
>>>> updating the previous version. So "editing" just creates multiple versions 
>>>> instead of actually editing the existing story.
>>>>
>>>> Is there a way to remedy this?
>>>>
>>>> On Friday, May 18, 2012 5:37:44 PM UTC-4, jondbaker wrote:
>>>>>
>>>>> The lines:
>>>>> #else:
>>>>> #story_form = StoryForm(instance=story_form)
>>>>> ...appear to be handling the G

Re: Trying to Edit Existing Post; Can't Get Form to Display

2012-05-18 Thread DF
Thanks. I get this error using that code:

TypeError at /report/detail/30/edit/

__init__() takes at least 2 arguments (1 given)

This is referring to this line:

  story_form = StoryForm(instance=story)

I added a "story_id" argument to this, which brought up the form, but when 
I submitted it, it returned the form with errors listing all the fields as 
empty.

This is far trickier than I thought.



On Friday, May 18, 2012 7:01:25 PM UTC-4, jondbaker wrote:
>
> Hmmm... I don't think you need to pass 'request.user' in as an argument. 
> Also, you want to be sure that the 'instance' you pass as an argument to 
> the model form is the model record you want to update. For instance:
>
> def edit_story(request, story_id)
> story = get_object_or_404(Story, pk=story_id)
> if request.method == 'POST':
> story_form = StoryForm(request.POST, request.FILES, instance=story)
> if story_form.is_valid():
> story_form.save()
> return HttpResponseRedirect("/profiles/user_profile")
> else: # GET request
> story_form = StoryForm(instance=story)
> return render_to_response('report/storyedit.html', {'form': 
> story_form}, context_instance=RequestContext(request))
>
>
>
> On Fri, May 18, 2012 at 4:52 PM, DF <donfernan...@gmail.com> wrote:
>
>> Thanks. This worked:
>>
>> else:
>> story_form = StoryForm(request.user, instance=story_form)
>>
>>
>> One problem: it just adds a new version of the story instead of updating 
>> the previous version. So "editing" just creates multiple versions instead 
>> of actually editing the existing story.
>>
>> Is there a way to remedy this?
>>
>> On Friday, May 18, 2012 5:37:44 PM UTC-4, jondbaker wrote:
>>>
>>> The lines:
>>> #else:
>>> #story_form = StoryForm(instance=story_form)
>>> ...appear to be handling the GET request, and they're commented out.
>>>
>>> On Fri, May 18, 2012 at 3:22 PM, DF <donfernan...@gmail.com> wrote:
>>>
>>>> Newbie question. I have an application where registered users can 
>>>> submit stories. The posting and display works great but I wanted users to 
>>>> have the ability to edit any of their stories. The goal would be for a 
>>>> user 
>>>> to find a list of their stories on their profile page, choose one that 
>>>> they 
>>>> would like to edit, and then retrieve the form they initially submitted 
>>>> with the current information filled in to make the necessary edits.
>>>>
>>>> I composed a view, url and template to achieve this. The page displays, 
>>>> the story number from the url appears in the address bar but the form is 
>>>> nowhere to be found. I can't figure out if what I'm doing is an error in 
>>>> the template or the view (I'm thinking the former but can't be sure).
>>>>
>>>> Here is the model:
>>>>
>>>> class Story(models.Model):
>>>> objects = StoryManager()
>>>> title = models.CharField(max_length=**100)
>>>> topic = models.CharField(max_length=**50)
>>>> copy = models.TextField()
>>>> author = models.ForeignKey(User, related_name="stories")
>>>> zip_code = models.CharField(max_length=**10)
>>>> latitude = models.FloatField(blank=False, null=False)
>>>> longitude = models.FloatField(blank=False, null=False)
>>>> date = models.DateTimeField(auto_now=**True, auto_now_add=True)
>>>> pic = models.ImageField(upload_to='**pictures', blank=True)
>>>> caption = models.CharField(max_length=**100)
>>>>
>>>> def __unicode__(self):
>>>> return " %s" % (self.title)
>>>>
>>>> Here is the form:
>>>>
>>>> class StoryForm(forms.ModelForm):
>>>> class Meta:
>>>> model = Story
>>>> exclude = ('author',)
>>>>
>>>> def __init__(self, author, *args, **kwargs):
>>>> super(StoryForm, self).__init__(*args, **kwargs)
>>>> self.author = author
>>>>
>>>>
>>>> def save(self, commit=True):
>>>> self.instance.author = self.author
>>>> return super(StoryForm, self).save(commit)
>>>>
>>>> Here are the submit and edit views:
>>>>
>>>> @login_required
>>>> def submit_story(request):
>>

Re: Trying to Edit Existing Post; Can't Get Form to Display

2012-05-18 Thread DF
Thanks. This worked:

else:
story_form = StoryForm(request.user, instance=story_form)


One problem: it just adds a new version of the story instead of updating 
the previous version. So "editing" just creates multiple versions instead 
of actually editing the existing story.

Is there a way to remedy this?

On Friday, May 18, 2012 5:37:44 PM UTC-4, jondbaker wrote:
>
> The lines:
> #else:
> #story_form = StoryForm(instance=story_form)
> ...appear to be handling the GET request, and they're commented out.
>
> On Fri, May 18, 2012 at 3:22 PM, DF <donfernan...@gmail.com> wrote:
>
>> Newbie question. I have an application where registered users can submit 
>> stories. The posting and display works great but I wanted users to have the 
>> ability to edit any of their stories. The goal would be for a user to find 
>> a list of their stories on their profile page, choose one that they would 
>> like to edit, and then retrieve the form they initially submitted with the 
>> current information filled in to make the necessary edits.
>>
>> I composed a view, url and template to achieve this. The page displays, 
>> the story number from the url appears in the address bar but the form is 
>> nowhere to be found. I can't figure out if what I'm doing is an error in 
>> the template or the view (I'm thinking the former but can't be sure).
>>
>> Here is the model:
>>
>> class Story(models.Model):
>> objects = StoryManager()
>> title = models.CharField(max_length=100)
>> topic = models.CharField(max_length=50)
>> copy = models.TextField()
>> author = models.ForeignKey(User, related_name="stories")
>> zip_code = models.CharField(max_length=10)
>> latitude = models.FloatField(blank=False, null=False)
>> longitude = models.FloatField(blank=False, null=False)
>> date = models.DateTimeField(auto_now=True, auto_now_add=True)
>> pic = models.ImageField(upload_to='pictures', blank=True)
>> caption = models.CharField(max_length=100)
>>
>> def __unicode__(self):
>> return " %s" % (self.title)
>>
>> Here is the form:
>>
>> class StoryForm(forms.ModelForm):
>> class Meta:
>> model = Story
>> exclude = ('author',)
>>
>> def __init__(self, author, *args, **kwargs):
>> super(StoryForm, self).__init__(*args, **kwargs)
>> self.author = author
>>
>>
>> def save(self, commit=True):
>> self.instance.author = self.author
>> return super(StoryForm, self).save(commit)
>>
>> Here are the submit and edit views:
>>
>> @login_required
>> def submit_story(request):
>> story_form = None
>> if request.method =="POST":
>> story_form = StoryForm(request.user, data=request.POST, 
>> files=request.FILES)
>> if story_form.is_valid():
>> new_story = story_form.save(commit=True)
>> return HttpResponseRedirect("/report/all/")
>>
>> return render_to_response("report/report.html", {'form': story_form 
>> or StoryForm(request.user) }, context_instance=RequestContext(request))
>>
>> @login_required
>> def edit_story (request, story_id):
>> story_form = None
>> if story_id:
>> story_form = get_object_or_404(Story, pk=story_id)
>> if story_form.author != request.user:
>> return HttpResponse("You can only edit your own stories!")
>>
>> if request.method == 'POST':
>> story_form = StoryForm(request.user, data=request.POST, 
>> files=request.FILES)
>> if story_form.is_valid():
>> story_form.save(commit=True)
>> return HttpResponse("/profiles/user_profile")
>> #else:
>> #story_form = StoryForm(instance=story_form)
>>
>> return render_to_response('report/storyedit.html', {'form': 
>> story_form or StoryForm(request.user) }, 
>> context_instance=RequestContext(request))
>>
>>
>> The urls:
>>
>> url(r'^report/$', 'project.report.views.submit_story', 
>> name='write_story'),
>> url(r'^detail/(?P\d*)/edit/$', 
>> 'project.report.views.edit_story', )
>>
>> And the edit template:
>>
>> {% extends 'base.html' %}
>> {% load report %}
>> {% block page_title %}Edit Story{% endblock %}
>> {% block headline %}Edit Story{% endblock %}
>> {% block content %}
>>
>> 
>> 
>>   

Trying to Edit Existing Post; Can't Get Form to Display

2012-05-18 Thread DF
Newbie question. I have an application where registered users can submit 
stories. The posting and display works great but I wanted users to have the 
ability to edit any of their stories. The goal would be for a user to find 
a list of their stories on their profile page, choose one that they would 
like to edit, and then retrieve the form they initially submitted with the 
current information filled in to make the necessary edits.

I composed a view, url and template to achieve this. The page displays, the 
story number from the url appears in the address bar but the form is 
nowhere to be found. I can't figure out if what I'm doing is an error in 
the template or the view (I'm thinking the former but can't be sure).

Here is the model:

class Story(models.Model):
objects = StoryManager()
title = models.CharField(max_length=100)
topic = models.CharField(max_length=50)
copy = models.TextField()
author = models.ForeignKey(User, related_name="stories")
zip_code = models.CharField(max_length=10)
latitude = models.FloatField(blank=False, null=False)
longitude = models.FloatField(blank=False, null=False)
date = models.DateTimeField(auto_now=True, auto_now_add=True)
pic = models.ImageField(upload_to='pictures', blank=True)
caption = models.CharField(max_length=100)

def __unicode__(self):
return " %s" % (self.title)

Here is the form:

class StoryForm(forms.ModelForm):
class Meta:
model = Story
exclude = ('author',)

def __init__(self, author, *args, **kwargs):
super(StoryForm, self).__init__(*args, **kwargs)
self.author = author


def save(self, commit=True):
self.instance.author = self.author
return super(StoryForm, self).save(commit)

Here are the submit and edit views:

@login_required
def submit_story(request):
story_form = None
if request.method =="POST":
story_form = StoryForm(request.user, data=request.POST, 
files=request.FILES)
if story_form.is_valid():
new_story = story_form.save(commit=True)
return HttpResponseRedirect("/report/all/")

return render_to_response("report/report.html", {'form': story_form or 
StoryForm(request.user) }, context_instance=RequestContext(request))

@login_required
def edit_story (request, story_id):
story_form = None
if story_id:
story_form = get_object_or_404(Story, pk=story_id)
if story_form.author != request.user:
return HttpResponse("You can only edit your own stories!")

if request.method == 'POST':
story_form = StoryForm(request.user, data=request.POST, 
files=request.FILES)
if story_form.is_valid():
story_form.save(commit=True)
return HttpResponse("/profiles/user_profile")
#else:
#story_form = StoryForm(instance=story_form)

return render_to_response('report/storyedit.html', {'form': story_form 
or StoryForm(request.user) }, context_instance=RequestContext(request))


The urls:

url(r'^report/$', 'project.report.views.submit_story', 
name='write_story'),
url(r'^detail/(?P\d*)/edit/$', 
'project.report.views.edit_story', )

And the edit template:

{% extends 'base.html' %}
{% load report %}
{% block page_title %}Edit Story{% endblock %}
{% block headline %}Edit Story{% endblock %}
{% block content %}




Edit your story, {{user.username}}!





{% generic_form form %}







{% endblock %}


This is likely a stupid error but hours of scratching my head led me to 
seek some guidance. Any help welcomed and appreciated. Trying very hard to 
learn.


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/arNGcd_FldoJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Can't get sorl.thumbnail to work

2012-05-16 Thread DF
Like a charm!

Thanks for your patience. I was working on this, my first django project, 
for months then put it away two months ago when things got too hectic. 
Still brushing off the cobwebs with some things,

Many, many thanks.



On Wednesday, May 16, 2012 9:43:34 PM UTC-4, Irfan Baig wrote:
>
> {% if profile.user.profile_pic %} 
>
>> {% thumbnail item.image "50x50" crop="center" as im %} 
>> > width="{{ im.width }}" height="{{ im.height }}"> 
>> {% endthumbnail %} 
>> {% endif %} 
>>
>>
> Looks like you have a lot of mistakes in the variables you are referencing 
> above. Your first {% if %} tag refers to profile.user.profile_pic, though 
> I'm almost certain you want to reference profile.profile_pic.
>
> Also, your thumbnail tag should look like this:
> {% thumbnail profile.profile_pic "50x50" crop="center" as im %} 
>
> Finally, since you are assigning the thumbnail to the im var, you'd want 
> the image src to point to {{ im.url }}, not {{ profile.profile_pic_url }}. 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/EGZA9A-tQL0J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Can't get sorl.thumbnail to work

2012-05-16 Thread DF
This is my first time using this app and I can't seem to get it
working within the template. No errors. It's just that nothing shows
up (which is obviously an error).

Here's the snippet from the template:

{% extends 'base.html' %}
{% load thumbnail %}
{% block page_title %}User Profile{% endblock %}
{% block headline %}User profile for {{profile.user.username}}{%
endblock %}


{% block content %}
{% if profile.user.profile_pic %}
{% thumbnail item.image "50x50" crop="center" as im %}

{% endthumbnail %}
{% endif %}


Something to note. In my models file, the "from sorl.thumbnail import
ImageField" is shaded out using PyCharm, so I'm curious as to whether
that's affecting it (although the docs say that sorl.thumbnail's
ImageField is not required). Also, using django-profiles and django-
registration, but everything with those is working smoothly.

Any help greatly appreciated as this is a stickler.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Is it time to start sqlite3 DB from scratch?

2012-03-02 Thread DF
The solution appears the have been simple: delete the offending
tables.

I have not tried to upload an actual image yet yet everything appears
9knock wood) to be working properly thus far.

Thanks for the advice, especially about how South isn't so friendly
with sqlite3!

On Mar 2, 10:02 pm, DF <donfernan...@gmail.com> wrote:
> Thanks. I'm having a bear of a time after I added an ImageFile and
> media folder and then tried to make a migration with South (made
> another post about this). I figure it might be best to just chuck it
> and start again.
>
> On Mar 2, 9:59 pm, Shawn Milochik <sh...@milochik.com> wrote:
>
>
>
>
>
>
>
> > On 03/02/2012 09:55 PM, DF wrote:
>
> > > Thanks. Still not sure how to wipe the database before starting fresh
> > > with South.
>
> > If it's a sqlite database you just delete the file.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Is it time to start sqlite3 DB from scratch?

2012-03-02 Thread DF
Thanks. I'm having a bear of a time after I added an ImageFile and
media folder and then tried to make a migration with South (made
another post about this). I figure it might be best to just chuck it
and start again.

On Mar 2, 9:59 pm, Shawn Milochik <sh...@milochik.com> wrote:
> On 03/02/2012 09:55 PM, DF wrote:
>
> > Thanks. Still not sure how to wipe the database before starting fresh
> > with South.
>
> If it's a sqlite database you just delete the file.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Is it time to start sqlite3 DB from scratch?

2012-03-02 Thread DF
Thanks. Still not sure how to wipe the database before starting fresh
with South.

On Mar 2, 8:50 pm, Shawn Milochik  wrote:
> If it's dummy data then you can always wipe it and reset South.
>
> There are some issues with sqlite. Not all constraints are enforced and
> it doesn't support removing fields, for two biggies. So you can't delete
> a field from a model (the migration will fail), and you can't use the
> 'unique_together' meta feature either. It will never raise an error and
> it'll let you put duplicate records in.
>
> A lot of people develop locally with sqlite for the convenience then
> deploy PostgreSQL for a robust DB.
>
> To answer your questions:
>
> 1. If you're going to wipe the DB and start over then you're already set.
> However, if you want to start South from scratch (it'll make your tests
> run faster because you'll have fewer migrations), you can do this:
>     A: ./manage.py reset south
>     B: rm appname/migrations/*
>     C: ./manage.py convert_to_south appname
>
> 2. If you wipe the DB it'll obviously destroy all data and you'll have
> to reload. You could export fixtures first, but restoring them will
> depend on whether they were tied to your app's data.
>
> 3. No.
>
> 4. Not if you're not worried about losing any data.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Adding ImageField to Existing Models Results in Errors...and Confusion

2012-03-02 Thread DF
I'm currently working on my first Django project and have hit a
roadblock in regard to adding an ImageField to an existing model.

I currently have a model for a user posting content and one for django-
profiles. For the former, I added an ImageField so the used can submit
a photo to accompany the text content. For the latter, I want to allow
users to upload a profile photo (not worried at the moment about
avatar resizing).

Things were working well until I added ImageFields to both models. I
then synced the database with South. What resulted when I try to pull
up the once working templates for profiles is:

"no such column: report_userprofile.profile_pic"

A similar error occurs when trying to view the submitted text content.

I set both of the fields to "blank=True" so it seemed as if not having
an image file would not cause an error. I'm obviously wrong.

I did not initially put these fields in the models, which in hindsight
was a big mistake. I've also just set up the MEDIA_ROOT and MEDIA_URL
as follows:

MEDIA_ROOT = 'os.path.join(BASE_DIR, "media")'

MEDIA_URL = 'http://localhost:8000/media'
The models I'm now using are:

class Story(models.Model):
title = models.CharField(max_length=100)
topic = models.CharField(max_length=50)
copy = models.TextField()
author = models.ForeignKey(User)
zip_code = models.CharField(max_length=10)
latitude = models.FloatField(blank=False, null=False)
longitude = models.FloatField(blank=False, null=False)
date = models.DateTimeField(auto_now=True, auto_now_add=True)
pic = models.ImageField(upload_to='pictures', blank=True)
def __unicode__(self):
return " %s" % (self.title)

class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=35)
email = models.EmailField()
birth_date = models.DateField(blank=True, null=True)
city = models.CharField(max_length=25)
state = models.CharField(max_length=20)
zip_code = models.CharField(max_length=10)
profile_pic = models.ImageField(upload_to='pictures', blank=True)

The accompanying forms for submission:

class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile

class StoryForm(forms.ModelForm):
class Meta:
model = Story
exclude = ('author',)

The URLs file is set up as follows:

url(r'^admin/', include(admin.site.urls)),

(r'^media/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT},

The core problem here is I have no idea what the error(s) might be
(the previous templates aren't set up properly since there was no
ImageField in the existing form for input? i didn't set up the
MEDIA_ROOT and URL earlier?). Or better yet, errors, as I'm sure I've
made several. It's a bit of a soup right now along with the resulting
distress.

Just as an FYI, I have installed the PIL.

Part of the issue may be that when I used South to add these fields it
didn't appear to migrate properly (I posted earlier about possibly
wiping the sqlite3 clean and starting from scratch). But I tried the
files on another computer without the potentially erroneous database
and the same error resulted.

Any insight at all, even a small insight, into what I need to do to
remedy this situation would be beyond appreciated. I've searched for
similar issues but none this specific emerges. (The first lesson for
the future would be to obviously set up the ImageFiles when initially
assembling the models.)

Usually I can figure things out by researching previous questions or
making a basic inquiry, but this time I'm in a hole. Hopefully, i can
learn from this episode.

Many thanks.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Is GeoDjango Too Much For This?

2012-02-27 Thread DF
Ethan:

What a generous answer. Thank you so much. Here are my responses with
a few other questions:

> What is your operating system?  On Ubuntu I've found all the installation
> to be very easy.

I'm on a Mac. The Django GeoDjango installation instructions are
somewhat obtuse and there aren't alternative sites I've found with
more straightforward instructions. It's lame that these are confusing
but, well, they are. I will no doubt review the sites you recommended.

As a newcomer who suddenly feels he may be biting off more than he can
chew, one of my worries it that if I utilize the sqlite3 database for
development with Spatialite, when I finally deploy this to, say, a
Postgres database, it won't transition correctly. This is most likely
due to my naiveté about databases, but I'm just concerned once it's
deployed, it won't work because I screwed something up by using
sqlite3 and I'm now trying to use another type of database.

>From your textbook descriptions (awesome) it seems that GeoIP is what
I'm looking for. Essentially, a logged-in user's coordinates would be
taken from their IP address (not sure if GeoDjango has a way to do
this without front-end JS work (more terror)) and be able to identify
their location on, let's say, a Google Map. When the user posts
content, it would be identified and recorded in the database the same
way. So if they're in a new location, the application can detect where
they are through the IP address and record those coordinates in the
database. This content could then be sorted via location (e.g., find
posts within a 10 mile radius), perhaps through a search or maybe
through a map with markers.

The problem with using HTML5 is, while it seems easy (there's pre-
formatted code out there that makes it a cinch to identify IP
location), it really provides no simple way to store or search for
content that's identified via GeoIP.

So, from reading your finely detailed response, it seems a valid and
straightforward way to proceed would be:

- GeoDjango using the GeoIP features
- OpenLayers (have heard about it; need to research more)
- Google Maps or another mapping service, being wary of limits

>From what I can discern, this is not an extremely advanced use of
GeoDjango or geolocation in general. It may actually be simple. But
I'm just now getting over my fears of Django proper so GeoDjango seems
like jumping from the kiddie pool into deep-dea diving. Another person
who responded focused his very kind and generous response on having to
be adept at trig to make GeoDjango work. I've avoided trig since I was
14. What have I gotten into? :)

Your response, again, was awesome. Any more guidance is not only
appreciated, but welcomed.

What a great and kind resource this forum is.






On Feb 27, 11:57 am, Ethan Jucovy <ethan.juc...@gmail.com> wrote:
> On Sat, Feb 25, 2012 at 7:50 PM, DF <donfernan...@gmail.com> wrote:
> > GeoDjango though, to be honest, sounds frightening and extremely
> > advanced. I've been reviewing the installation requirements and, at
> > least according to how these were written, is intense and ripe for
> > many errors.
>
> What is your operating system?  On Ubuntu I've found all the installation
> to be very easy.
>
> FWIW, when I was starting out with GeoDjango I found these tutorials to be
> useful -- they're written for specific OSes/distributions/database backends
> but I still found them easier to follow than the official documentation:
> [1,2,3]
>
> > Part of the qualms I'm having is I've been developing on
> > the internal sqlite3 database. According to most of the documentation,
> > Postgres with GIS is recommended. This is concerning.
>
> I haven't used the spatial extensions to SQLite (SpatiaLite) but I believe
> SpatiaLite is fully supported by GeoDjango and has all the features you
> will need.  (As long as the features you need don't include multiple users
> writing to the database at the same time!  For production you will probably
> want Postgres instead of Sqlite, for reasons that have nothing to do with
> GIS.)
>
> > Essentially, I want to be able to have the application immediately
> > detect a users longitude and latitude and have all the content they
> > contribute be identified with those coordinates.
>
> Depending what you mean by "immediately detect", you'll want to look into
> "geocoding" and/or "GeoIP" and/or the W3C/HTML5 "geolocation API".
>
> Geocoding is the process of translating a text address into a lat/long,
> e.g. when an end-user types in his address in order to center a map there.
>  GeoDjango doesn't provide any direct geocoding features, but it's easy to
> implement in your GeoDjango-based application.  You'll most likely want to
> use a web service for this -- Google, Yahoo, and many other services
> (including

Re: Is GeoDjango Too Much For This?

2012-02-25 Thread DF

Thanks for all the feedback. It is tremendously insightful.

Here are my qualms:

I'm a Django rookie, with basic Python knowledge. I'm using Django to
work on my master's project, which is a specific web application that
utilizes  some form of geolocation, the latter of which is a mystery.

I have a good skeleton thus far for basic functionality. It's taken a
month, but I'm happy with what's been accomplished considering my
knowledge (also using django-registration and django-profiles, which
are terrific apps).

GeoDjango though, to be honest, sounds frightening and extremely
advanced. I've been reviewing the installation requirements and, at
least according to how these were written, is intense and ripe for
many errors. Part of the qualms I'm having is I've been developing on
the internal sqlite3 database. According to most of the documentation,
Postgres with GIS is recommended. This is concerning.

Essentially, I want to be able to have the application immediately
detect a users longitude and latitude and have all the content they
contribute be identified with those coordinates. I'd like a map
illustrating their location to appear with each content post. Finally,
I want to provide users the ability to search for nearby posts or
within a certain boundary (from the documentation I've read, this is
what GeoDjango apparently excels at).

Perhaps this is isn't a monumental task and I'm letting my mind get
the best of me, as it often does. But it sounds quite intimidating.

I appreciate any feedback, realistic expectations and advice. And I
also appreciate the tolerance of experienced and skilled programmers
at addressing annoying novice questions like mine. I've learned that
asking questions is one of the keys to learning.

Many thanks.

DF


On Feb 25, 5:07 pm, Ethan Jucovy <ethan.juc...@gmail.com> wrote:
> Whoops, quick correction:
>
> On Sat, Feb 25, 2012 at 5:03 PM, Ethan Jucovy <ethan.juc...@gmail.com>wrote:
>
> > * You'll want to add a line ``objects = GeoManager`` on each model that
> > you will want to perform geospatial queries against.
>
> That should be ``objects = GeoManager()`` (imported from
> django.contrib.gis.db.models).
>
> And, I meant to link to the docs on 
> that:https://docs.djangoproject.com/en/dev/ref/contrib/gis/model-api/#geom...
>
> -Ethan

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Saving Django User in Form

2012-02-25 Thread DF
Thanks for the advice. I want to make sure it's secure.

What's the best way to override the save I posted in the code above
without causing issues?

On Feb 25, 2:10 am, Bernhard Schandl 
wrote:
> Hi,
>
> > I tried that before your answer arrived and it worked like a charm. I
> > just excluded the author field from the form and kept everything else
> > the same. It works perfectly, as the user was already passed to the
> > author field in the view. A logged in user can now automatically post
> > a story now through the form and it appears under their username.
>
> > So simple. I asked elsewhere and received extremely convoluted answers
> > that caused more confusion and chaos rather than comfort.
>
> > Thank you for reaffirming. Although, I didn't have to override the
> > form (new_story.save()) to make it work. I should probably just leave
> > it alone and enjoy the functionality!
>
> You should only check that, although the user field now does not appear in 
> the form, the user cannot override the user field by changing the POST 
> request that is sent to your server after submitting. So it's definitively 
> safer to explicitly override the user field in your model on save(), instead 
> of relying on a pre-filled field.
>
> best
> Bernhard

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Saving Django User in Form

2012-02-24 Thread DF
I tried that before your answer arrived and it worked like a charm. I
just excluded the author field from the form and kept everything else
the same. It works perfectly, as the user was already passed to the
author field in the view. A logged in user can now automatically post
a story now through the form and it appears under their username.

So simple. I asked elsewhere and received extremely convoluted answers
that caused more confusion and chaos rather than comfort.

Thank you for reaffirming. Although, I didn't have to override the
form (new_story.save()) to make it work. I should probably just leave
it alone and enjoy the functionality!

On Feb 24, 11:02 pm, Shawn Milochik  wrote:
> Read the Django docs about ModelForms, then use the 'exclude' kwarg to
> exclude the author from your ModelForm.
>
> Then, use request.user to get the appropriate user in your view and pass
> that to the form save(), which you must override to accept the extra
> argument, and use that user in the save() method to set the author directly.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Saving Django User in Form

2012-02-24 Thread DF
I'm currently working on my first Django app, which allows registered
users to submit content through a basic form.

It works thus far with one caveat: when the form is displayed, the
user ("Author") is presented with a drop-down list of all users
instead of automatically populating that field with the user's name.
This is obviously not acceptable.

This goal is to have the registered user's name automatically populate
the form. I've seen some various potential solutions to similar
problems, but nothing that addresses anything this specific.

I attempted setting the Author field in the model to "unique=True,"
but that resulted in a database error when migrating it.

Any insight would be greatly appreciated:

Model:

class Story(models.Model):
title = models.CharField(max_length=100)
topic = models.CharField(max_length=50)
copy = models.TextField()
author = models.ForeignKey(User)
zip_code = models.CharField(max_length=10)
latitude = models.FloatField(blank=False, null=False)
longitude = models.FloatField(blank=False, null=False)
date = models.DateTimeField(auto_now=True, auto_now_add=True)
def __unicode__(self):
 return " %s" % (self.title)

Form:

class StoryForm(forms.ModelForm):
class Meta:
model = Story

View:

@login_required
 def submit_story(request):
if request.method == "GET":
story_form = StoryForm()
return render_to_response("report/report.html",
 {'form': story_form},
 
context_instance=RequestContext(request))
elif request.method =="POST":
story_form = StoryForm(request.POST)
if story_form.is_valid():
new_story = Story()
new_story.title = story_form.cleaned_data["title"]
new_story.topic = story_form.cleaned_data["topic"]
new_story.copy = story_form.cleaned_data["copy"]
new_story.author = request.user
new_story.zip_code = story_form.cleaned_data["zip_code"]
new_story.latitude = story_form.cleaned_data["latitude"]
new_story.longitude = story_form.cleaned_data["longitude"]
new_story.save()
return HttpResponseRedirect("/report/all/")
else:
story_form = StoryForm()
return render_to_response("report/report.html",
{'form': story_form},
 
context_instance=RequestContext(Request))

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Is GeoDjango Too Much For This?

2012-02-23 Thread DF
I'm currently building my first Django-based app, which is proceeding
fairly well, thus far. One of the goals is to allow users to post
information (text, pics, video) and for the app to be able to
automatically detect the location where they posted this information.
That data would then ideally be able to be filtered later, such as
viewing the posts that were made within a specific radius.

I've been reading a bit about GeoDjango and it sounds intriguing. A
colleague, though, suggested everything that can be done using
GeoDjango is equally efficient utilizing the Google Maps API with
JavaScript or JQuery to obtain the proper coordinates.

Essentially, I'm looking to see what benefits GeoDjango would give
this project over using just the Google Maps API. If I've already
started a project in basic Django, is incorporating GeoDjango
problematic?  I'm still attempting to master the basics of Django and
venturing into GeoDjango may be too much. Or not.

Any insight appreciated.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Accessing parent classes within admin site list_display function

2006-09-02 Thread DF

Thanks for the help Rajesh.  I had seen that quote before but it really
didnt click quite right until made painfully obvious.

Is there a cleaner way to acess parent model fields easily with the
list_display function itself?  The only way I have been able to do so
is like this:
###
class Log(models.Model):
def gettaskdescription(self):
return self.Task.description
timestamp = models.DateTimeField('date completed')
comments = models.TextField()
active = models.BooleanField()
task = models.ForeignKey(Task)
taskdesc = gettaskdescription
def __str__(self):
return '%s' % self.timestamp
class Admin:
list_display =
('timestamp','comments','task','taskdesc')
###

Please forgive my noobness to DJango.  Hopefully I didnt completely
miss this being covered in the models examples somewhere.

 - DF


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Accessing parent classes within admin site list_display function

2006-09-01 Thread DF

I am trying to access parent class objects within the admin site with
the list display function.

The following are my models:
###
class Device(models.Model):
make = models.CharField(maxlength=30)
model = models.CharField(maxlength=50)
partno = models.CharField('part number', maxlength=30)
serial = models.CharField('serial number', maxlength=30,
primary_key=True)
asset = models.CharField('asset tag', maxlength=30)
recievedate = models.DateTimeField('date received')
active = models.BooleanField()
def __str__(self):
return '%s (%s)' % (self.serial, self.asset)
class Admin:
list_display = ('make','model','serial','asset')

class Plan(models.Model):
shortname = models.CharField(maxlength=30, primary_key=True)
description = models.CharField(maxlength=100)
active = models.BooleanField()
device = models.ForeignKey(Device)
def __str__(self):
return '%s' % self.shortname
class Admin:
pass

class Task(models.Model):
description = models.CharField(maxlength=30)
frequency = models.IntegerField()
active = models.BooleanField()
plan = models.ForeignKey(Plan)
def __str__(self):
return '%s|%s' % (self.plan,self.description)
class Admin:
pass

class Log(models.Model):
timestamp = models.DateTimeField('date completed')
comments = models.TextField()
active = models.BooleanField()
task = models.ForeignKey(Task)
def __str__(self):
return '%s' % self.timestamp
class Admin:
list_display = ('timestamp','comments','task')
###

So, when I view Logs via the admin interface, I see the timestamp,
comments, and the return of __str__ for the parent task object.
However, I was really wanting to be able to view and sort based off of
some of the device fields (make, model, serial, etc).  Is there a way
to step up the ForeignKey bindings to higher level objects within the
Admin class?

Push come to shove, I could write a seperate functions to get the data
I am looking for, but then I would not be able to sort based on it.

I wasnt able to find a whole lot on how to do this in the DJango
documentation.  Although, I could be looking in the wrong places.  Any
help would be apprecaited.

Thanks!
 - DF


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---