akulakov / django-mcbv Goto Github PK
View Code? Open in Web Editor NEWdjango by example; MCBV library
django by example; MCBV library
I have made APIs in Django and uploading a file from the IOS app. I'm passing file by converting it into data using multipart request. It's uploading fine from the Postman but while posting from application, i'm getting following error,
{
"userProfilePicture":["The submitted data was not a file.
Check the encoding type on the form."]
}
Can anybody help me with this out?
Code:
models.py
from __future__ import unicode_literals
from django.db import models
import datetime
def upload_location(instance, fileName):
extension = fileName.split('.')[-1]
random_string = 'IMG-' + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
filename = "images/" + UserImages._meta.app_label + "/" + random_string + "." + extension
return filename
class UserImages(models.Model):
userId = models.AutoField(primary_key=True, db_column="user_id")
userProfilePicture = models.ImageField (
"Profile Picture",
upload_to = upload_location,
db_column="user_profile_picture",
blank=True
)
serializers.py
from rest_framework import serializers
from .models import UserImages
class UserImageSerializer(serializers.ModelSerializer):
class Meta:
model = UserImages
views.py
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from .serializers import UserImageSerializer
from .models import UserImages
class UserImageUpload(ListCreateAPIView):
serializer_class = UserImageSerializer
queryset = UserImages.objects.all()
class UserImageUpdate(RetrieveUpdateDestroyAPIView):
serializer_class = UserImageSerializer
urls.py
from django.conf.urls import url
from django.contrib import admin
from .views import UserImageUpload, UserImageUpdate
urlpatterns = [
url(r'^user-create/$', UserImageUpload.as_view()),
url(r'^user-update/(?P<pk>[0-9]+)/$', UserImageUpdate.as_view()),
];
Making post/put request.
Here is the API calling code of IOS
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:@"http://192.168.0.116:8001/user-create/" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:imageData name:@"userProfilePicture"];
} error:&error];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding]);
}];
[manager.operationQueue addOperation:operation];
remember this section( image_upload_to) is in comment
field=models.ImageField(blank=True, null=True, upload_to=posts.models.image_upload_to), AttributeError: module 'posts.models' has no attribute 'image_upload_to'
how it possible this part (field=models.ImageField(blank=True, null=True, upload_to=posts.models.image_upload_to) is in comment any idea?
I'm following you tutorial on the blog(Django 1.5 version) and I'm using Django 1.6. For some reason, the Archive Months side bar is not showing the months. It seems like the list for months and years is not being created, and therfore not shown. in list.html I am using:
{% block sidebar %}
{% for ym in view.months %}
{% ifchanged ym.0 %} {{ ym.0 }} <br /> {% endifchanged %}
<a href="{% url 'archive_month' ym.0 ym.1 %}">{{ ym.2 }}</a> <br />
{% endfor %}
{% endblock %}
and in views.py the code for creating the list of archive months is:
import time
from calendar import month_name
from travelblog.models import *
from travelblog.forms import *
from masudtravels.shared.utils import *
from masudtravels.mcbv.list import ListView
from masudtravels.mcbv.list_custom import DetailListCreateView
allpost = Post
class PostView(DetailListCreateView):
"""Show post, associated comments and an 'add comment' form."""
detail_model = Post
list_model = Comment
modelform_class = CommentForm
related_name = "comments"
fk_attr = "post"
template_name = "post.html"
class Main(ListView):
list_model = Post
paginate_by = 10
template_name = "list.html"
def months(self):
"""Make a list of months to show archive links."""
if not Post.obj.count(): return list()
# set up variables
current_year, current_month = time.localtime()[:2]
first = Post.obj.order_by("created")[0]
first_year = first.created.year
first_month = first.created.month
months = list()
# loop over years and months
for year in range(current_year, first_year-1, -1):
start, end = 12, 0
if year == current_year : start = current_month
if year == first_year : end = first_month - 1
for month in range(start, end, -1):
if Post.obj.filter(created__year=year, created__month=month):
months.append((year, month, month_name[month]))
return months
class ArchiveMonth(Main):
paginate_by = None
def get_list_queryset(self):
year, month = self.args
return Post.obj.filter(created__year=year, created__month=month).order_by("created")
and in base.html i am using:
{% block sidebar %}{% endblock %}
Thank you in advance for your help!
my main url is:
url(r'^posts/', include("posts.urls", namespace="posts")),
my app url is:
url(r'^(?P<pk>\d+)/update/$', PostUpdateView.as_view(), name='update'),
i am trying to access it in my template like this:
<small> <a href='{% url 'posts:update' %}'>***</a></small>
and getting this error:
NoReverseMatch at /
Reverse for 'update' with no arguments not found. 1 pattern(s) tried: ['posts/(?P\d+)/update/$']
You seem to be using the django-registration app, but the templates for it do not exist.
when I run sudo python manage.py runserver 0.0.0.0:8000, I get the error:
.......
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
how to solve it? thanks
test issues
when i run the command python manage.py runserver getting this ERROR -
server - Error trying to receive messages: Error 10061 connecting to localhost:6379. No connection could be made because the target machine actively refused it.
now what i have to do.
When trying to import the portfolio app from this code into a new django project. There is an error that comes up of TemplateDoesNotExist where it is specifically looking for group_list.html that is mentioned in the list.html template.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.