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 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 %}
Related
I want to display the contents of a table called recommendation in the interface Django of the user in the morning of each day because I'm collecting recommendations and saving them in a table (each user have his own recommendations of course ) and I want to delete them after he check them.
So I'm doing this but that is going to display the recommendations directly if I refreshed the page.
HTML interface :
<li class="word-bot-sent"><p>Do you want some recommendations today? </p></li>
{% for obj in Recommendation %}
{% if obj.user == request.user %}
<li class="word-bot-sent"><p>{{ obj.title }}</p></li>
<li class="word-bot-sent"><p>{{ obj.text }}</p></li>
{%endif%}
{% empty %}
{% endfor %}
How can I tackle this?
You'll probably want to take a look at Django's time zones docs. You could do something like:
from django.utils import timezone
from django.views.generic import ListView
from .models import Recommendation
class RecommendationListView(ListView):
model = Recommendation
template_name = 'mytemplate.html'
context_object_name = 'recommendations'
def get_queryset(self):
current_hour = timezone.now().hour
if current_hour > 8 and current_hour < 11:
queryset = Recommendation.objects.filter(user=self.request.user)
# force the queryset to be evaluated
eval_query = list(queryset)
# delete the data from the database now that you have them in a list
queryset.delete()
return eval_query
else:
return Recommendation.objects.none()
... but you will have to take into account if your users are in the same time zone as you, and if not, how you can set things up so that they work properly. You'll also have to consider that it's likely that users might try to abuse the system if you make the site timezone-aware/adjusted based on the users' timezones. e. g. they might try to pose as being in a different time zone to get the recommendations earlier.
Also, the above method of deletion isn't really appropriate because if for whatever reason (say if the user's internet connection is finicky) the user doesn't receive the server's response and tries to access the page again, the data have already been removed. I'm sure there is a better solution which avoids this issue. What you would need is some confirmation from the user that they've actually seen the page, or use AJAX to collect an indication of the user viewing the page. You can see some additional discussion on a similar topic in this SO thread.
I just started using django and I have some problems understanding how to use auth on my web app. So, basically, what I cannot understand how to implement is displaying different content on my page for each user
My app is an online editor that each user can use to write their code and have it stored. I have implemented the sign up/sign in and what I need to do now is to have a different filesystem for each user and display it appropriately.
I don't know why I can't find this answer anywhere but I am really overwhelmed with this problem and I have done zero progress.
You have 2 easy ways to do this:
1 - Inside template
2 - Inside Views
Which to prefer when:
Template - When you have less content to be segregated then go with template way.
How to do that?
`{% if user.is_superuser %}
<some html>
#Your html for Superuser
#you can also include a another html file
{% include "App_name/Superuser_view.html" %}
{% else %}
<some html>
#Your html for Staff or whoever
#you can also include a another html file
{% include "blazon/employee_view.html" %}
{% endif %}`
Inside Views : when you need to render lot of html differences among the user types then go with this method.
def view(request):
if request.user.is_superuser():
#your View Function & return it individually
elif request.user.is_admin():
#your View Function
else request.user.is_staff():
#your View Function
You can check what permissions does a user have and implement different logic in view for different types of users:
def some_view(request):
if request.user.is_admin:
# logic for Admin users
elif request.user.is_staff:
# logic for Staff only
else:
# logic for all other users
If you want to implement your custom permissions you can check docs.
After setting up the All-Auth app, when user logs in, he gets redirected to: accounts/profile/ page which tells us that the view doesn't exist.
I'm trying to figure out what kind of thing to include there, and decided to allow the user to change their basic information.
I have a users app with a Teacher model, which is set up as follows:
class Teacher(models.Model):
user = models.ForeignKey(User, unique=True)
rate = models.CharField(max_length=200)
availability = models.BooleanField(default=False)
verified = models.BooleanField(default=False)
I want the accounts/profile/ page to show a form, containing this information. The user can edit these fields and also edit their Firstname, Lastname and Email, which belong to a different Model - User.
I can't seem to get started on this. When I created a detailed view for the profile page, I get an error saying:
No PK or SLUG provided
I want Django to change the current users info, not based on the primary key in the URL. Do I need a custom view? I've looked at [other solutions1
but they seem to be utilising the private key parameter.
What I need is a working view function, something similar to (not working):
def get_teacher_info(request):
current_user = request.user
teacher = get_object_or_404(Teacher, username=current_user.username)
return render(request, 'account/profile.html', {
'user':current_user,
'teacher': teacher,
'error_message': "The field is blank",
})
and in the accounts/urls.py I've added:
url(r"^profile/$", views.get_teacher_info, name="account_profile"),
but when I make calls like {% teacher.rate %} in the html template, I get:
Invalid block tag on line 5: 'teacher.rate'. Did you forget to register or load this tag?
The def get_teacher_info(request) function and the urls.py entry are working. Looks like the issue may be in the template. Use {{ instead of {% tags. So use {{ teacher.rate }} not {% teacher.rate %} in the template.
Redirecting to /accounts/profile/ After the login is the default behavior of Django. django-allauth is using the same default behavior from Django settings.
Now if you want to modify this default redirect url then change it to
LOGIN_REDIRECT_URL = '/custom/redirect-url'
Important Note: Without a starting / you're redirecting to a path that is appended to the CURRENT URL. You need to use a leading slash to redirect to a path that is appended to the domain root. further details on it. In short, without a starting / you will end up with
../login/callback/custom.redirect-url (appended to current url)
I am developing an app where employees would log in and search for already uploaded data,
I want to create a page for admin users where they can see which employees are online/offline/onBreak
How can i achieve this ?
After a lot of searching and re-searching i finally got the answer!
In views.py
def get_current_users(request):
active_sessions = Session.objects.filter(expire_date__gte=timezone.now())
user_id_list = []
for session in active_sessions:
data = session.get_decoded()
user_id_list.append(data.get('_auth_user_id', None))
return User.objects.filter(id__in=user_id_list)
def userList(request):
users = User.objects.all()
online = get_current_users([])
context = {
"users_list": users,
"online_list": online,
}
return render(request, 'Index/users.html',context)
Create this two views.(as a beginner that the best i could do feel free to manipulate the code)
in urls.py
url(r'^users/$', views.userList, name="user"),
then in users.html
{% extends "Index/header.html" %} {% block content %}
{% for user in users_list %}
{{ user }}
{% if user in online_list %}
online
{%else%}
offline
{% endif %}
{% endfor%}
{% endblock %}
What its basically doing is :
First its collecting all the logged in users
then gathering all listed users the cross checking weather users in the user list with logged in user list. If true its printing online if not its printing offline beside the user name.
To detect whether a user is online or offline you can follow the below
strategy.
Create new DB table which will track the records of all the online
users.
Steps -
Create model let say online_user_tracking with the fields ( id, user_id, entry_timestamp )
When user logs in, add an entry to this model with mentioned fields
When user log out delete the entry from this model
Now it could be possible that user may not log out properly and go away, in that case, you have to use keep alive (Polling) mechanism as
mentioned below -
Polling ( Keep alive ) -
When user login to your site the entry will be created to the model "online_user_tracking". Then on every 5 second's you have to
update its timestamp field for the current logged in user_id. Now on
the backend we have to write a script wich will be executed in every 5
seconds ( May have to schedule a CRON job on the server ) and check if
any records have not updated it's timestamp in last 3 minutes those
entries should be deleted.
That's how we can keep the records of online and offline users of the site.
Hope this explanation will help...
You can use django-socketio and define it to give the user status to the server from the client HTML. This will keep polling to the server about the status change.
My Django app currently has URLs which are protected by 'permission_required()' functions.
This function is called in three different ways.
As a decorator in views.py, with hardcoded parameters.
As a plain function, with autogenerated parameter, in custom Class Based Generic Views.
As a function invoking views in urls.py, with hardcoded parameters.
I'm now adding a menu system to the app, and I need to make menu entries reflect whether the user has permission to request the URL of each menu entry. (Either by greying-out or hiding said entries.)
Is there a way of query the permissions required to a URL without requesting the URL?
The only solution I've thought of so far is to replace the decorator with a parameterless 'menu_permssion_required()' decorator and hardcode all of the permissions into a Python structure. This seems like a step backwards, as my custom Class Based Generic Views already autogenerate their required permissions.
Any suggestions on how to make a menu system which reflects URL permissions for the current user?
Here is an example of how to solve your problem:
First, Create a decorator wrapper to use instead of permission_required:
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
from django.core.exceptions import PermissionDenied
from functools import wraps
from django.utils.decorators import available_attrs
def require_perms(*perms):
def decorator(view_func):
view_func.permissions = perms
#wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
for perm in perms:
return view_func(request, *args, **kwargs)
raise PermissionDenied()
return _wrapped_view
return decorator
Then, use it to decorate your views:
#require_perms('my_perm',)
def home(request):
.....
Then, add a tag to use for your menu items:
from django.core.urlresolvers import resolve
def check_menu_permissions(menu_path, user):
view = resolve(menu_path)
if hasattr(view.func, "permissions"):
permissions = view.func.permissions
for perm in permissions:
if user.has_perm(perm):
return True # Yep, the user can access this url
else:
return False # Nope, the user cannot access this url
return True # or False - depending on what is the default behavior
And finally, in your templates, when building the menu tree:
<button href="{{ some_path }} {% if not check_menu_permissions some_path request.user %}disabled="disabled"{% endif %} />
N.B. I've not tested the last part with the tag, but I hope you got the idea. The magic thing here is to add the permissions to the view_func in the decorator, and then you can access this using resolve(path). I'm not sure how this will behave in terms of performance, but after all that's just an idea.
EDIT: Just fixed a bug in the example..
Is there a way of query the permissions required to a URL without requesting the URL?
User.has_perm() and User.has_module_perms()
Any suggestions on how to make a menu system which reflects URL permissions for the current user?
I really like this question, because it concerns anyone that makes a website with django, so I find it really relevant. I've been through that myself and even coded a menu "system" in my first django project back in 2008. But since then I tried Pinax, and one of the (so many) things I learnt from their example projects is that it is completely unnecessary bloat.
So, I have no suggestion which I would support on how to make a menu "system" which respects the request user permissions.
I do have a suggestion on how to make a simple menu which respects the request user permissions, so that might not be completely unrelated.
Just make your menu in plain HTML, it's not like it's going to change so often that it has to be generated. That will also keep your Python code simpler.
Add to settings.TEMPLATE_CONTEXT_PROCESSORS: 'django.core.context_processors.PermWrapper'
Use the {{ perms }} proxy to User.has_perms.
Example:
{% if perms.auth %}
<li class="divider"></li>
{% if perms.auth.change_user %}
<li>
{% trans 'Users' %}
</li>
{% endif %}
{% if perms.auth.change_group %}
<li>
{% trans 'User groups' %}
</li>
{% endif %}
{% endif %}
{# etc, etc #}
That's how I keep navigation simple, stupid, and out of the way. But also I always include an autocomplete not far from the menus to allows the user to navigate to any detail page easily. So, that's all I know about navigation in django projects, I'm eager to read other answers !
I had a similar issue, but it went a little deeper. Instead of just permissions, I also wanted other tests based on the lidded in user (ie, is_staff, or user.units.count() > 1). Duplicating these in the view and the template seems prone to errors.
You can introspect a view object, and see all of the decorators wrapping it, and work out if they are checks (in my case: the first argument I'd u or user). If they all pass, then allow rendering the link.
Get all decorators wrapping a function describes the technique in a little more detail. You can find the app that wraps this up into a handy replacement for {% url %} at Django-menus.