Django encrypted-filefield - django

I currently try to figure out how to implement the following:
https://github.com/danielquinn/django-encrypted-filefield
I only want to transparently encrypt my uploaded Data for later use on e.g. S3
First Problem is that I'm not able to get
from django.contrib.auth.mixins import AuthMixin
imported. I get the following exception:
from django.contrib.auth.mixins import AuthMixin
ImportError: cannot import name 'AuthMixin'
I'm simply not able to find it. At what package is it located?
and second is that I have no idea how to implement the view if I only want encrypt and decrypt the file on the fly.
Any suggestions?
my models.py
from django.db import models
from django.utils import timezone
from smartfields import fields
from smartfields.dependencies import FileDependency
from smartfields.processors import ImageProcessor
from django_encrypted_filefield.fields import EncryptedFileField
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField(max_length=10000)
tag = models.CharField(max_length=50, blank=True)
postattachment = EncryptedFileField(upload_to='postattachment/%Y/%m/%d/', blank=True, null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', blank=True, null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 300, 'max_height': 300}))
])
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
views.py
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'quickblog/post_detail.html', {'post': post})
Thank you :)

That mixin is not present in the django mixins. Maybe, the demo refers to a class extending any of the mixins you can find in django.
Having a look at the django sources, try with the class:
from django.contrib.auth.mixins import AccessMixin
In the view, try to show the encoded file, it must be stored already encrypted.

Related

ValueError: Cannot assign "'1'": "Post.user" must be a "User" instance

I am doing a group project for a bootcamp and we just started Django for the back-end. We also are using React for front-end. Our project is basically a knockoff reddit.
We have a User model:
`from django.db import models
class User(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
email = models.CharField(max_length=100, unique=True)
username = models.CharField(max_length=32, unique=True)
password = models.CharField(max_length=255)
def __str__(self):
return '%s' % (self.username)`
and a Post model:
`from django.db import models
from auth_api.models import User
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=255)
formBody = models.TextField(null=True, blank=True)
imageURL = models.CharField(max_length=200, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)`
Our Post Serializers(pretty unfamiliar with this):
`from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
user = serializers.CharField(required=True)
class Meta:
model = Post
fields = ('id', 'user', 'title', 'formBody', 'imageURL', 'created',)`
And our Post Views:
`from django.shortcuts import render
from rest_framework import generics
from .serializers import PostSerializer
from .models import Post
from auth_api.models import User
class PostList(generics.ListCreateAPIView):
queryset = Post.objects.all().order_by('id')
serializer_class = PostSerializer
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Post.objects.all().order_by('id')
serializer_class = PostSerializer`
The idea was when a user created a post their info would be saved with the post so that way when we display the post we could say who created at. Also we could have a user profile that could see all of their posts. I assumed that what would happen is the user info would get saved inside a object in the user column, but the first way we tried only saved the userID and we couldn't access any of the users info. The second way(what we have now) keeps giving us this error: ValueError: Cannot assign "'1'": "Post.user" must be a "User" instance.The 1 is the userID that we pass in from the frontend of the user that created the post. I am unsure of where to go from here and have been stuck for a while on this. Hopefully I provided enough info

My views.py is returning null from django admin object

I would really appreciate some help on this because I'm completely stuck. I've started up a simple django app (trying to make an instagram clone). However, when I try to display the post objects (which I created in the django admin page) nothing is displayed in index.html, so I tried printing out the objects in the views.py and it's returning to me an empty query set. I don't quite understand what I'm doing wrong and why I can't access the objects? When I print out the username I am able to get that, but then nothing for both post and stream objects. Please I'm so stuck any advice would be appreciated.
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.template import loader
from django.http import HttpResponse
# Create your views here.
from post.models import post, stream
#login_required
# we are getting all of the string objects that are created for the user
def index(request):
user = request.user
print(user)
posts = stream.objects.filter(user=user)
print(posts)
group_ids = []
#then looping through and getting post id to a list
for posted in posts:
group_ids.append(posted.post_id)
print(group_ids)
#then filtering them so that you can display it in the index
#selecting a specific post by id
post_items = post.objects.filter(id__in=group_ids).all().order_by('-date')
template = loader.get_template('index.html')
context = {'post_items' : post_items}
return(HttpResponse(template.render(context, request)))
models.py
from django.db import models
from django.contrib.auth.models import User
import uuid
# Create your models here.
from django.db.models.signals import post_save
from django.utils.text import slugify
from django.urls import reverse
def user_directory_path(instance,filename):
# this file is going to be uploaded to the MEDIA_ROOT /user(id)/filename
return('user_{0}/{1}'.format(instance.user.id,filename))
class tag(models.Model):
title = models.CharField(max_length = 80, verbose_name = 'tag')
slug = models.SlugField(null = False, unique = True)
class Meta:
verbose_name = 'tag'
verbose_name_plural = 'tags'
# for when people click on the tags we can give them a url for that
# def get_absolute_url(self):
# return(reverse('tags', args = [self,slug]))
def __str__(self):
return(self.title)
def save(self,*args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
return(super().save(*args, **kwargs))
class post(models.Model):
# will create a long id for each post
id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable = False)
image = models.ImageField(upload_to = user_directory_path, verbose_name= 'image', null = True)
caption = models.TextField(max_length = 2000, verbose_name = 'caption')
date = models.DateTimeField(auto_now_add = True)
tags = models.ManyToManyField(tag, related_name='tags')
user = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.IntegerField()
def get_absolute_url(self):
return reverse('postdetails', args=[str(self.id)])
# def __str__(self):
# return(self.user.username)
class follow(models.Model):
follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower')
following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following')
class stream(models.Model):
following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stream_following')
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(post, on_delete=models.CASCADE)
date = models.DateTimeField()
def add_post(sender, instance,*args, **kwargs):
# here we are filtering all the users that are following you
post = instance
user = post.user
followers = follow.objects.all().filter(following=user)
for follower in followers:
streams = stream(post=post, user=follower.follower, date = post.date, following = user)
streams.save()
post_save.connect(stream.add_post, sender=post)
output from print statements
user
<QuerySet []>
[]
I figured it out. It wasn't an issue with the code, but the way that I was creating posts in the admin panel. So because you can only view posts from users that you are following, the posts that I was creating weren't showing up. So I had to create another user, and follow that user, then have the new user post something. Then the post shows up in the page!

how to upload an image from django rest framework using browse button?

i am new to django-rest-framework,i am unble to get the image as browse button in my rest framework,i am getting text field,here is my code as follows...........
views.py
from django.shortcuts import render
from serializers import *
from rest_framework import viewsets
class newsViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = news.objects.all()
serializer_class = newsSerializer
class news_categoriesViewSet(viewsets.ModelViewSet):
queryset = news_categories.objects.all()
serializer_class = news_categoriesSerializer
models.py
from django.db import models
from django.utils.encoding import smart_unicode
class news_categories(models.Model):
cat_name = models.CharField(max_length=30, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return smart_unicode(self.cat_name)
def Content_files(instance, filename):
return '/'.join(['Media','News Image', filename])
class news(models.Model):
name = models.CharField(max_length=30,null=True)
description = models.TextField()
cat_id = models.ForeignKey('news_categories')
image = models.FileField(upload_to=Content_files,null=True)
date = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return smart_unicode(self.name)
serializers.py
from django.forms import widgets
from rest_framework import serializers
from models import *
class newsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = news
fields = ('url','id','name','description','cat_id','image','date')
class news_categoriesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = news_categories
fields = ('url','id','cat_name')
Any one can Help me?Thanks in Advance....
the problem with settings.py and version of rest framework ,use 2.4.4
I stumbled upon the same problem when I updated to version 3.0. The solution is to define the FileField or ImageField in your serializer using a style attribute:
file = serializers.FileField(style = {'input_type': 'file'})

Django cms display plugin data in template

I have created custom events plugin and now I want to display closest event on my home page (django-cms page with home.html template).
How can I do it? This is my event/models.py
from django.core.urlresolvers import reverse
from django.db import models
from adminsortable.models import Sortable
from easy_thumbnails.fields import ThumbnailerImageField
from cms.models.fields import PlaceholderField
from cms.models.pluginmodel import CMSPlugin
class Event(Sortable):
class Meta:
app_label = 'event'
event_name = models.CharField(
blank=False,
default='',
max_length=64,
)
date = models.DateField(
auto_now=False,
auto_now_add=False,
)
photo = ThumbnailerImageField(
upload_to='events',
blank=True,
)
def __unicode__(self):
return self.event_name
To get the latest event, you can override the render method of your plugin:
class YourCMSPlugIn(CMSPluginBase):
model = Event
...
def render(self, context, instance, placeholder):
context.update({
'latest_event': self.model.objects.all()[:1],
'placeholder': placeholder
})
return context
See: http://docs.django-cms.org/en/latest/extending_cms/custom_plugins.html#storing-configuration for more information.

Correctly returning object through Many to Many relationship

My objective is to display a readable list of Articles that belong to my user named 'Admin'
In other words, give me all articles that Admin owns. In my sample data I have Admin owning 1 article.
Problem: When I return the object, its a completely unreadable and unhelpful representation of this object. I'm thinking of adding a unicode() method to my model here but I don't know how!!
Model.py:
from django.db import models
from django.contrib.auth.models import User
class Article (models.Model):
question = models.CharField(max_length=255, unique=True, blank=False)
keywords = models.TextField(max_length=500, blank=True, null=True)
def __unicode__(self):
return self.question
class ArticleUserOwnership (models.Model):
article = models.ManyToManyField(Article)
user = models.ManyToManyField(User)
-- you can see here I'm hooking into the admin user table
Views.py:
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from GeorgiaArticleManager.models import Article, ArticleUserOwnership
from django.shortcuts import render
def myarticles(request):
if request.user.is_authenticated():
# articles of admin with id= 1
my_articles = ArticleUserOwnership.objects.filter(user=1)
context = {'my_articles': my_articles}
return render(request, 'template/myview.html', context)
myview.html:
ul
{% for ArticleUserOwnership in my_articles %}
li{{ ArticleUserOwnership }}/li
{% endfor %}
/ul
In summary of above:
ArticleUserOwnership.objects.filter(user=1) returns me an object that when I display it on myview.html, I just get 'ArticleUserOwnership object'. I'm sure this is the correct returned object but, I'd like to see returned Article.question. For example Admin owns 'test title 1' and I'd like to see this article question field displayed properly.
my_articles = ArticleUserOwnership.objects.filter(user=1)
gives you a list of ArticleUserOwnership instances. If you want of list of articles try this instead:
auo = ArticleUserOwnership.objects.get(user=1) # could raise DoesNotExist
my_articles = auo.article.all() # you should rename this field 'articles'
However, that ArticleUserOwnership model doesn't really make sense, my guess is that what you're really trying to do is this:
from django.db import models
from django.contrib.auth.models import User
class Article (models.Model):
question = models.CharField(max_length=255, unique=True, blank=False)
keywords = models.TextField(max_length=500, blank=True, null=True)
owners = models.ManyToManyField(User, related_name='owned_articles')
def __unicode__(self):
return self.question
You would then access your data like so:
my_articles = user.owned_articles.all()
See the documentation for examples of how to use ManyToManyFields.
try this:
class ArticleUserOwnership (models.Model):
article = models.ManyToManyField(Article)
user = models.ManyToManyField(User)
def __unicode__(self):
return self.article
OR
def __unicode__(self):
return self.article.question