How to write django form to a text file
I m creating a django site (using django forms) that lets users subscribe their email. How do I get that email into a text file? Currently I have a cron job that runs a python script sending an email to all subscribers every morning. Is this the best way to do this or there is some built-in 开发者_Python百科functionalities in django-forms that I can use?
If I understand you correctly, you have a list of users from their email address saved into the database, and want to save that list to a text file?
Well you could go into ./manage.py shell
and type something like this:
# I assumed the email addresses are in User.email; modify as needed to conform to your model.
with open('email.txt','w') as f:
for u in User.objects.all():
f.write(u.email + '\n')
You could also write a management command to do this: http://docs.djangoproject.com/en/dev/howto/custom-management-commands/
or create a simple view & template that creates a text file with all your email addresses in a list. Though for the sake of your users not being spammed password protect this, and don't make this publicly accessible. Something simple like (that is not private) should work:
urls.py:
from django.views.generic.list_detail import object_list
urlpatterns = patterns('',
(r'^full_emails/$', 'object_list', {'template': 'template/text.txt', 'queryset'=User.objects.all()}
)
template/text.txt:
{% for user in object_list %}
{{ user.email }}
{% endfor %}
精彩评论