Get image from Flickr using django-syncr - django

I have my photos located on Flickr. I want to sync them between Flickr and my Django app using django-syncr. It's installed, Flickr section is visible in Admin site. I can sync photo data from Flickr to my local database. In a few words -- it works.
But, I don't understand how to get these data from my database using views.py and template file?I mean, how to make my Flickr's photos visible on my site?
I got something like this on my site:
* IMG_2467
* Morning fog on Halong bay
I used these files but get only title from all data and didn't anything else, including photos.
views.py
from django.shortcuts import render_to_response
from syncr.flickr.models import Photo
def index(request):
get_photo = Photo.objects.all()
return render_to_response('index.html', {'get_photo': get_photo})
index.html
<html>
<title>
Test page
</title>
<body>
{% if get_photo %}
<ul>
{% for photo in get_photo %}
<li>{{ photo }}</li>
{% endfor %}
</ul>
{% else %}
<p>No photos are available.</p>
{% endif %}
</body>
</html>

maybe you should add <img src='{{photo.url}}' /> ? I don't see how do you plan to show images if you're just importing the names.

Related

How to Fetch and Publish the latest data and list data in django

I am currently working on django , Need some help how to achive my below goal
I need to publish the latest data and list data in a web app .
Below is the set of steps i followed
Created the Model.py
import datetime
from statistics import mode
from django.db import models
Create your models here.
class documents(models.Model):
author= models.CharField(max_length=30)
title=models.CharField(max_length=50)
description=models.TextField()
creation_date=models.DateTimeField()
update_date=models.DateTimeField()
View.py
from django.shortcuts import render
from django.views.generic.list import ListView
from .models import documents
# Create your views here.
class documentlist(ListView):
template_name='app/document_list.html'
model=documents
context_object_name='document'
HTML snippet
{% extends 'base.html' %}
{% block title %} MY HOMEPAGE {% endblock %}
{% block css %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
{% endblock %}
{% block content %}
<nav class=" navbar navbar-dark bg-primary">
<a class="navbar-brand mb-0 h1" href="#">MEDICARE</a>
</nav>
{% for d in document %}
<td>{{d.title}}</td>
{% endfor %}
{% endblock %}
How can we render both latest data and list of data from a model class in django?I am clear about rendering the list data using listview . can someone help in understanding how to display the latest data from the list to the listview.html
Thanks,Sid
I have figured out the issue and this helped me resolve the issue.
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['latest_post'] = documents.objects.latest('update_date')
return context
Thanks,
SIdh
Well you would go about getting your recent publish data in your listview like this:
class documentlist(ListView):
template_name='app/document_list.html'
model=documents
context_object_name='document'
def get_queryset(self):
return documents.objects.filter(author=request.user).order_by('creation_date')
in your html template you can do something like this to render the latest post
% extends 'base.html' %}
{% block title %} MY HOMEPAGE {% endblock %}
{% block css %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
{% endblock %}
{% block content %}
<nav class=" navbar navbar-dark bg-primary">
<a class="navbar-brand mb-0 h1" href="#">MEDICARE</a>
</nav>
{% for doc in document %}
<td>{{doc.title}}</td>
{% endfor %}
{% endblock %}
Just add ordering by id in descending order:
class documentlist(ListView):
template_name='app/document_list.html'
model=documents
context_object_name='document'
ordering = ['-id']
I know that this post is old enough but not closed yet, it may be useful for someone else.
But i need to show the latest data as the latest post and show as a
fetured one , i have attached screenshot as per my requirement
Facing this equation this is how I did:
My view:
And this is my template

Reorder nav bar from django admin

So I am currently working on a project and the client has asked for this requirement.
Basically, I have to provide some sort of mechanism in the admin panel so that the admin can order the navbar items.
Current nav bar
Like in the image above, admin should be able to set the order to eg. SIGN-IN SIGN-UP ABOUT HOME
I'm new to Django but have decent programming skill. Can anyone point me in the right direction?
You will have to make the navbar display data-driven.
Create a model for the navbar display.
from django.db import models
class Navbar(models.Model):
name = models.CharField(max_length=100)
display_order = models.IntegerField(null=True, blank=True)
Register the model so the user can modify in the admin.
from django.contrib import admin
from .models import Navbar
admin.site.register(Navbar)
Create objects for the model class for each of the desired navbar links.
Use content_processors to pass the navbar object to the template that contains the navbar (generally base.html). This link explains in detail how to use content processors.
How can i pass data to django layouts (like 'base.html') without having to provide it through every view?
Your function in content_processors.py should be similar to this.
from .models import Navbar
def add_navbar_data_to_base(request):
return {
'navbar': Navbar.objects.all().order_by('display_order')
}
Now you can add the links to base.html template using a for loop and they will display in the order specified by the display_order which can be modified in the admin.
#base.html
<!DOCTYPE html>
{% load static %}
<html>
<head>
</head>
<body>
{% block nav %}
<nav class="navbar sticky-top navbar-expand navbar-light">
<ul class="navbar-nav">
{% for link in navbar %}
<li class="nav-item">
<a class="nav-link">{{ link }}</a>
</li>
{% endfor %}
</ul>
</nav>
{% endblock %}
{% block content %}
{% endblock %}
</body>
</html>
This code has not been tested but the general idea should work.

Flask Admin Custom View

I am pretty new to Flask/Flask-Admin.
I have followed the tutorial on flask admin and managed to get the admin panel working but slightly lost on how to get the below things implemented.
https://github.com/flask-admin/flask-admin/tree/master/examples/auth
When logged in as a normal user I can only see "home" page.
How can I expose other views to "normal user" and restrict actions such as read only etc.
I have created a "baseview" which is not associated with any other models as below:
class SitesView(MyBaseView):
#expose('/')
def index(self):
return self.render('views/testviews.html')
admin.add_view(SitesView(name='Test views', endpoint='test views'))
and html as below:
{% extends 'admin/master.html' %}
{% block body %}
{{ super() }}
{% if current_user.has_role('view1') %}
Site1
{% endif %}
{% if current_user.has_role('view2') %}
<a>Site2</a>
{% endif %}
{% if current_user.has_role('view3') %}
<a>Site3</a>
{% endif %}
{% if current_user.has_role('view4') %}
<a>Site4</a>
{% endif %}
{% endblock %}
This gives me a new tab with different views with works as expected.
What I am trying to achieve here is when user click the Site1 link they go to Site1 page within flask-admin interface but I am not sure how to do that. I could create a new route for this but the problem is I can't(don't know how to) extend flask admin template.
For example this works but it redirect the page outside flask-admin template:
#app.route('/views/')
def views():
return render_template('views/views1.html')
and modified the templates>admin>index.html page with below:
<ul class="lead text-center list-group">
{% if current_user.has_role('view1') %}
<li class="list-group-item">View1</li>
{% endif %}
{% if current_user.has_role('view2') %}
<li class="list-group-item">View2</li>
{% endif %}
{% if current_user.has_role('view3') %}
<li class="list-group-item">View3</li>
{% endif %}
{% if current_user.has_role('view4') %}
<li class="list-group-item">View4</li>
{% endif %}
</ul
I want to build the whole web site using flask admin so that I can keep user experience consistence. Am I doing this the wrong way?
Thanks for your time.
Please do let me know if you want me to provide more information on this issue.
Kind Regards.
So after going through documentations and tutorials I have found the solution to my issue.
For my first question:
When logged in as a normal user I can only see "home" page. How can I
expose other views to "normal user" and restrict actions such as read
only etc.
We can do this by overwriting our view functions is_accessible method as below:
def is_accessible(self):
if not current_user.is_active or not current_user.is_authenticated:
return False
if current_user.has_role('superuser') or current_user.has_role('user') or current_user.has_role('view1'):
return True
return False
For my second question we just need to give the endpoint as for our BaseView as below:
class MyView(BaseView):
#expose('/')
def index(self):
return self.render('views.html')
admin.add_view(MyView(name='Custom Views', endpoint='customviews'))
And then in your jinja template you need to call it:
href="{{ url_for('customviews.index') }}
Just one thing to note, doing this:
current_user.has_role('superuser') or current_user.has_role('user') or current_user.has_role('view1')
could get quite messy if we have so many roles, not sure how we would approach this but hoping this will help someone.
Thanks all.
I know this is an old question, but for the following code
current_user.has_role('superuser') or current_user.has_role('user') or current_user.has_role('view1')
What I like to do is having a hybrid_property (available on both Peewee and SQLAlchemy) inside my User class that consolidates these properties. So it'd look something like this:
#hybrid_property
def user_has_administrative_rights(self):
return self.has_role('superuser') or self.has_role('user')

Simple vote button in Django

I'm an absolute beginner to django (and programming in general), I've tried the django Polls tutorial and all went well, however I am trying to get a minimal voting button to work. Basically I have set up a database with two columns, my models.py looks like this
from django.db import models
class Imgurl(models.Model):
urlvar = models.URLField(max_length=200)# a URL linking to an image
urlvote = models.IntegerField(default=0)# my intended vote count
def __unicode__(self):
return self.urlvar
I have made an input box where I can copy and paste an image url, this image then displays on a separate page(this works fine). What I want is to have a voting button next to each displayed image, where a user can click on the button (I am trying to use a submit button) and the number of votes will increase in the db(no redirecting to a new page, or anything fancy).
I think this is a trivial question and I am trying to learn the basics of POST and database handling in django (also, I have read the relevant chapters in the djangobook... maybe I'm just a little slow?)
my views looks like this
def urlvotes(request):
if request.method=='POST':
if 'voteup' in request.POST:
v=Imgurl(forloop.counter)
v.urlvote +=1
else:
pass
votetotal=v.urlvote # attempt to give the template some kind of context
return render_to_response('display.html', {'votetotal':votetotal}, context_instance=RequestContext(request))
and my template looks like this:
{% extends "base.html" %}
{% block head %}Image display{% endblock %}
{% block content1 %}
Home
{% if links %}
<ul>
{% for link in links %}
<li><img src="{{ link }}"></li>
<li><form action="{% url urlvotes %}" method="post">
{% csrf_token %}
<input type="submit" name="voteup" value='vote'/></p>
<p>{{votetotal}}</p>
</form></li>
{% endfor %}
</ul>
{% else %}
<p>No uploads.</p>
{% endif %}
{% endblock %}
when I run this, as is, I get a csrf verification failed error
Any help would be greatly appreciated
Try adding the #csrf_protect to your view
#csrf_protect
def urlvotes(request):
if request.method=='POST':
if 'voteup' in request.POST:
v=Imgurl(forloop.counter)
v.urlvote +=1
else:
pass
votetotal=v.urlvote # attempt to give the template some kind of context
return render_to_response('display.html', {'votetotal':votetotal}, context_instance=RequestContext(request))

Using Django to show YouTube videos in templates

I'm attempting to store a list of YouTube links in a model then passing it as a list to a template where it's rendered using YouTube's embed code. Everything seems to be working fine, the variables are passed properly except the videos don't show up. The YouTube iframe code is just blank whereas a copy/pasted of YouTube embed code displays just fine.
The code in the Model:
from django.db import models
class Video(models.Model):
link = models.URLField()
def __str__(self):
return self.link
The code in the View:
def index(request):
full_list = Video.objects.all()
return render_to_response('index.html', {'full_list': full_list})
The code in the Template:
<h1>YouTube list</h1>
{% if full_list %}
<ul>
{% for video in full_list %}
<li>
<!-- link passed to embed code, this shows up as blank -->
<iframe width="560" height="345" src="{{ video.link }}?rel=0" frameborder="0" allowfullscreen></iframe>
<!-- YouTube embed link copy/pasted as is -->
<iframe width="560" height="345" src="http://www.youtube.com/embed/vLmNvYTTWXM?rel=0" frameborder="0" allowfullscreen></iframe>
</li>
{% endfor %}
</ul>
{% else %}
<p>No videos available</p>
{% endif %}
Screenshot of the browser: https://img.skitch.com/20110910-t78bm288mxh6nmyjmcbxyjr37n.png
I'm guessing that the templates are rendered first and the variable is added second hence YouTube's server is not even called. Is this a correct assumption and if so how do I go about fixing it?
Your code is correct as I can see.
Mb you will show us result html code?
The only thing thay may be wrong is lack of __unicode__ method in your model.
You should use not __str__ but __unicode__.
I wrote a template tag, which does exactly what's needed above.
https://gist.github.com/chhantyal/5396911
You could use this library to make your life easier:
https://github.com/jazzband/django-embed-video
Embed Videos the Easiest Way:
models.py
from django.db import models
from embed_video.fields import EmbedVideoField
class Item(models.Model):
video = EmbedVideoField() # same like models.URLField()
template
{% load embed_video_tags %}
The video tag:
{% video item.video as my_video %}
URL: {{ my_video.url }}
Thumbnail: {{ my_video.thumbnail }}
Backend: {{ my_video.backend }}
{% video my_video "large" %}
{% endvideo %}
Or embed shortcut:
{% video my_video '800x600' %}