how to display userena contents in the templates of other app - python

I want to display mugshot and background from Userena in one of my APP namely UserBackground 's Template.But it seems to me that it is not a easy task to do for a person who is really new in Django like me.I have tried to do this several times but its not working.This is view which resides in my UserBackground , where i have tried to capture the Mugshot,but i failed.
from django.contrib.auth.models import User
from Photo.models import photo #Photo Model of the App
def userphoto(request,user_id):
user = Photo.objects.filter(user = user_id)
user_mugshot = get_object_or_404(User,username__iexact=user_id)
context = RequestContext(request)
ctx_dict = {'user': user,'user_mugshot' : user_mugshot}
return render_to_response('photo/user_portfolio.html',locals(),ctx_dict,context)
#return HttpResponse(ctx_photo)
and this is the urls.py
url(r'^(?P<user_id>\d+)/user_photo/$',views.userphoto,name = 'userporrfolio')
i write those codes in my View according to this link.
How to use the Django Usurena "mugshot" template variable
i am not sure is it right way to capture Mugshot from userena app in another app.

Related

Where to best execute database operations using Django framework?

Thanks in advance for any help. I am new to django specifically as well as web development in general. I have been trying to teach myself and develop a website using the Django framework and while everything is working so far, I am not sure if I am really doing things in the best possible way.
Typically, within my django app, I will have certain points where I want to modify the contents of my database model in some way. A typical use case is where I have button on my site that says "Add a post":
models.py:
from django.db import models
# data model import
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
post = models.CharField(max_length=1024)
urls.py:
from django.urls import include, path
from . import views
urlpatterns = [
path('', views.post, name='new_post'),
path('post_exec', views.post_exec, name='post_exec'),
]
views.py:
from django.contrib import messages
from django.shortcuts import render, redirect
# import data models
from django.contrib.auth.models import User
from .models import Post
def post(request):
# make sure the user has privileges
user = User.objects.get(id = request.user.id)
if not user.is_superuser:
return redirect('home')
return render(request, 'post.html')
def post_exec(request):
# make sure the user has priveledges
user = User.objects.get(id = request.user.id)
if not user.is_superuser:
return redirect('home')
# create the post
new_post = Post.objects.create()
new_post.user = user
new_post.post = request.POST['post']
new_post.save()
# this could redirect to a confirmation page or something too
return redirect('home')
You can see what I am doing here is that everytime I need a change to the database due to user input, I am executing the code to do the requested database change in a django view and then redirecting to another page following completion of the database change. While this works, it feels kind of clunky (you end up needing pages that you never actually use), it seems pretty sketchy in terms of security (although I am checking for credentials on each page), and I imagine there is a better way to do this.
Can any experience Django developers offer some advice for how I should be best structuring my project for these specific types of common database operations?
The Django's views is a good place to organize the project's CRUD system so users can manage their data. You can use the class-based views to group the GET, POST etc requests. Also there are better ways of using the authorization system with the login_required() decorator, the LoginRequiredMixin class and other solutions that you can rich here

Flask - How to properly set global values

I'm currently working on a web app where I'm using Flask and the Flask-User extension to handle authorization. At the moment I have something like this:
#application.route('/dummy')
#roles_required('Admin')
#login_required
def dummy():
in my views.py file and something like this:
{% if current_user.is_authenticated and current_user.has_roles('Admin') %}
in my templates.
Now, there's been a few times where I've changed my mind in terms of role names and then had to search through the whole project to find and replace those usages. I wanted to define something like a ADMIN_ROLE global that can be accessed inside my views.py or any templates. I'd then just change a config file whenever I wanted to change a role's name.
I tried using my config.py setting ADMIN_ROLE = "Admin" and writing #roles_required(current_app.config['ADMIN_ROLE']) but that gives me the following error:
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in a way. To solve
this set up an application context with app.app_context(). See the
documentation for more information.
so that should be wrong. What would be the most correct way to accomplish what I'm trying?
As it says, you can only access config from within the app context. Normally, you do this:
with current_app.app_context():
admin_role = current_app.config['ADMIN_ROLE']
Because you're doing this in a decorator, I don't believe there's anyway to do that. I would suggest just using a separate module. Now, it doesn't appear that you can use python import statements in jinja, so we'll still use app.config for that. Basically we'll create a module with the desired roles and then import that into the config file and your routes file.
roles.py
ADMIN = "Admin"
USER = "User"
config.py
from roles import ADMIN, USER
ADMIN_ROLE = ADMIN
USER_ROLE = USER
routes.py
from roles import ADMIN, USER
#application.route('/dummy')
#roles_required(ADMIN)
#login_required
def dummy():
views.py
{% if current_user.is_authenticated and current_user.has_roles(app.config['ADMIN_ROLE']) %}

Django: proper way to reload template library

I am using custom template tags to show site-specific content. Templates for these tags are stored in database and staff is able to edit them. I used that SO answer as reference. Each time after template changed and saved into database, I force reloading of django app (by reloading uwsgi service) or changes doesn't become visible. Looks like Django populates template library for custom tags only on first load of app.
I think reloading Django app isn't best practice to refresh DB templates, and I am searching way to do it programmatically (from model's save() or on save signal)
Template tags code:
from django.template import Template, Library
from project.custom_templates.models import DbTemplate
register = Library()
# template names
SHOW_PART_TABLE_ADMIN = 'custom/tags/show_part_table_admin.html'
SHOW_PART_TABLE_PUBLIC = 'custom/tags/show_part_table_public.html'
t_show_part_table_admin = Template(DbTemplate.objects.get(name=SHOW_PART_TABLE_ADMIN).content)
t_show_part_table_public = Template(DbTemplate.objects.get(name=SHOW_PART_TABLE_PUBLIC).content)
#register.inclusion_tag(t_show_part_table_admin)
def show_part_table_admin(parts, user, perms):
return {'parts': parts, 'user': user, 'perms': perms}
#register.inclusion_tag(t_show_part_table_public)
def show_part_table_public(parts, user, perms):
return {'parts': parts, 'user': user, 'perms': perms}

Django changing custom settings at runtime

In my settings.py there are some custom settings, a few data structures that I use. These are rarely changed.
I've noticed that changing them from a view wont work.
How can I force django to reload the settings file at runtime ?
So far the only way that works is to restart the apache web server. But I want to avoid that.
In my code. I needed to kindof reinvent the #login_required decorator for a protected (admin only restricted) page. This is what I did.
In the project/settings.py I created a variable called ACCESS_CP = False
In the app/views.py I imported
from django.conf import settings
In the def login_form
# (if the user is authenticated and the user is an Active Directory Domain Admin)
settings.ACCESS_CP = True
In the def ControlPanel:
if request.method == "GET" and settings.ACCESS_CP == False:
return redirect('login')
elif request.method == "GET" and settings.ACCESS_CP == True:
settings.ACCESS_CP = False
return render(request, 'controlpanel.html')
For your application you can store configuration parameters in redis or django model.
Here is the helpful reusable app for that https://github.com/jezdez/django-constance
Also you can check other existing solutions for django configuration management:
https://www.djangopackages.com/grids/g/configuration/
Import in view.py
import django.conf as conf
def home(request):
conf.settings.SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
conf.settings.DATABASES['default']['NAME'] = 'testdb'

Django Admin Custom Pages and Features

I'm (new to) working in Django and would like to create two features that do not rely upon models/database tables. The basis of this app is as a web-based wrapper to a Python application.
The features are:
I would like to be able to load a ConfigObj text file into a page and edit it's configuration prior to saving again.
I would like to be able to call command line python/bash scripts and display their output on a page - like exec in PHP.
At the moment I'm working on simple custom admin pages without model as described here:
Django admin, section without "model"?
Would this be the right direction to go in? I'm not sure proxy tables apply as the features I desire have nothing to do with any data.
So far I have looked at is it possible to create a custom admin view without a model behind it and a few other links. At the moment I have:
main/urls.py
url(r'^admin/weectrl', include('weectrl.urls')),
which links with weectrl/urls.py
from weectrl import views
urlpatterns = patterns('',
(r'^admin/weectrl/manage/$', weectrl_manage_view),
(r'^admin/weectrl/config/$', weectrl_config_view),
)
which points to weectrl/views.py
def weectrl_manage_view(request):
r = render_to_response('admin/weectrl/manage.html', context, RequestContext(request))
return HttpResponse(r)
def weectrl_config_view(request):
r = render_to_response('admin/weectrl/config.html', context, RequestContext(request))
return HttpResponse(r)
The current error message is name 'weectrl_manage_view' is not defined
Ok, found something that works.
In the main url.py
url(r'^admin/weectrl/', include('weectrl.urls')),
In app/urls.py
urlpatterns = patterns('',
url(r'^config/$', views.config, name='config'),
url(r'^manage/$', views.manage, name='manage'),
)
and in app/views.py
def config(request):
context = ""
return render(request, 'weectrl/config.html', context)
def manage(request):
context = ""
return render(request, 'weectrl/manage.html', context)
html files are in app/templates/app/...

Categories