Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to point Django .html to S3 media file?
I can upload files to the S3 bucket from my django app using the models admin view and later watch the videos on my S3 bucket account. But I am not able to serve them in my .html file My settings.py (which I believe where the mistake is) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') AWS_ACCESS_KEY_ID = 'x' AWS_SECRET_ACCESS_KEY = 'x' AWS_STORAGE_BUCKET_NAME = 'django-draft-project-1' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' The link to the S3 bucket where the video uploaded https://s3.eu-central-1.amazonaws.com/django-draft-project-1/data/videos/SampleVideo.mp4 My .html file <video controls> <source src=https://s3.eu-central-1.amazonaws.com/django-draft-project-1/{{ video_details.videofile }}> </video> -
How can I refresh a page automatically after a button has been clicked?
I'm working on a housing project with a listing model. Listing has a ManyToManyField called favorites, which is supposed to hold all the usernames of users that clicked the favorite button on the detail page for the listing. Right now the favorite button adds the username to the listing's favorites, but then 404s because I'm not correctly redirecting to the listing detail page. I've been trying to follow this tutorial (https://www.youtube.com/watch?v=VoWw1Y5qqt8) and though I think I have followed correctly, my page 404s while in the tutorial, it refreshes (around 6:30). Here is models.py: class Listing(models.Model): favorites = models.ManyToManyField(User, related_name='favorites', blank=True) ... listing_detail.html: ... <form action="{% url 'favorite_listing' %}" method="listing"> <button type="submit" name="listing_id" value="{{ listing.id }}" class="btn btn-primary">Favorite</button> </form> urls.py: ... urlpatterns = [ ... url(r'^favorite/$', views.favorite_listing, name="favorite_listing"), ] views.py: ... def favorite_listing(request): listing = get_object_or_404(Listing, id=request.POST.get('listing_id')) listing.favorites.add(request.user) return HttpResponseRedirect(listing.get_absolute_url()) ... As of now I'm getting: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/favorite/?listing_id=48 Raised by: reviews.views.favorite_listing Any and all help is greatly appreciated! -
Why is my URL modified with http but not https
I'm having a more aesthetic problem with a deployed django app (it is still in debug mode). The application has a domain at example.net. Django apps on it are accessed via example.net/path, which works (for example, example.net/resume or example.net/blog). I can access it via: (1) example.net/path (2) www.example.net/path (3) http://example.net/path (4) https://example.net/path When accessing each of these, the domain in (1), (2), and (3) changes unexpectedly, and not in a way i'd like a user to see. (4) is what I want to see. So, when a user types this in, this occurs: Entered URL --> Displayed URL --------------------------------------------------------------------------------------- (1) example.net/path --> example.net/home/username/appname/path (2) www.example.net/path --> www.example.net/home/username/appname/path (3) http://example.net/path --> http://www.example.net/home/username/appname/path (4) https://example.net/path --> https://www.example.net/path While this is not a major problem, i'm curious as to why this happens. I don't know what is actually causing the redirect - whether I have a setting configured improperly, or if I need to use my own redirects to rectify the issue. I also currently do not have a home page referring to example.net, but that should not be relevant. For reference, this is my urls.py in the main project: from django.contrib import admin from django.urls import path from django.contrib import admin from … -
Using a field from a URL for filtering in ListAPIView in Django Rest Framework
Iam using a generic ListApiView of Django Restframework, the serializer iam using consist of many other serializer(nested serializers). I need to know how I can use the keyword from URL and pass it to the serializer in order for me to filter the result using the keyword in the URL. For example I have a api view as this class GetList(Generics.ListApiView): serializer Class = ABCSerializer I want to pass a value from a URL, to filter some parts of results produced by the serializer. This ABCSerializer is composed of many other nested serializers. I want to filter the result using the Value from URL not like primary key. -
Fiscal year in Django forms initial
I have a model with Fiscal Year and I am trying to get the initial value as the current year. However, the fiscal year is different than the calendar year. The fiscal year starts in July and continues till next year June. At this moment, the initial value is the current year and I would like to get fiscal year instead. Any suggestion? class BudgetTreemapForm(forms.Form): today = date.today() fiscal_year = forms.ModelChoiceField(queryset=FiscalYear.objects.all(), widget=forms.Select( attrs={ 'class': 'form-control' } ), initial=today.year, label="Fiscal Year") -
Error when registering a custom user in Django
When I want to register a new user in Django, I get the following warning: UNIQUE constraint failed: polls_usuario.matriculaUsuario When I edit the registry, both by admin and in the main view, this error does not occur. This error only occurs when creating a new user. When I create a user by the view register, the user is created, with the default enrollment. When I try to create by admin, the user is not even created. What could be happening? views.py def registrar(request): if request.method == 'POST': form = SignUpForm(request.POST) usuario_form = UsuarioForm(request.POST) if form.is_valid() and usuario_form.is_valid(): user = form.save(commit=False) user.refresh_from_db() # load the profile instance created by the signal user.usuario.matriculaUsuario = form.cleaned_data.get('matriculaUsuario') usuario_form.save() user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request,user) return render(request, 'polls/index.html', user) #return HttpResponseRedirect(reverse('/')) #return redirect('/') else: form = SignUpForm() usuario_form = UsuarioForm() return render(request, 'polls/registrar.html', {'form': form , 'usuario_form':usuario_form}) forms.py class UsuarioForm(forms.ModelForm): class Meta: model = Usuario fields = ('matriculaUsuario',) class SignUpForm(UserCreationForm): first_name = forms.CharField(label='Primeiro Nome',max_length=30, required=False, help_text='Opcional.') last_name = forms.CharField(label='Último Nome',max_length=30, required=False, help_text='Opcional.') email = forms.EmailField(label='E-mail',max_length=254, help_text='Informe o seu e-mail (Requerido)') username = forms.CharField(label='Nome de usuário', min_length=4, max_length=150) password1 = forms.CharField(label='Senha', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirmação da senha', widget=forms.PasswordInput) matriculaUsuario = forms.CharField(label='Matrícula',max_length=12,validators=[ validators.RegexValidator(re.compile('^[0-9]{12}$'), _('Digite … -
Django dynamic url parameter names
Basically trying to do {% url dynamic_url_name dynamic_parameter_name=dynamic_parameter_value %} Tried the simplest approach of <a href="{% url belongs_to belongs_to_url_arg=entry|getattribute:belongs_to_url_arg_value %}">{{entry}}</a> {% include 'mainsite/children/title_template.html' with the_title=title_text is_title_page=True entries_of="title" belongs_to="profile" belongs_to_url_arg="user" belongs_to_url_arg_value="author" %} But unfortunately this resulted in utter failure of From this I can tell that parameters can't be context variables, so what I can try to do next is to simply unpack a dictionary as I would do inside python with something like {% url **{dynamic_parameter_name:dynamic_parameter_value} %} But I have no idea if it is possible inside django templates, and if possible how? -
Multiple context using ListView in Django 2.0
What is the best way to create extra context while using ListView? Based on the code below: class PostListView(LoginRequiredMixin, ListView): model = Post context_object_name = 'posts' template_name = 'posts/posts-list.html' def get_context_data(self, request, *args, **kwargs): context = super(PostListView, self).get_context_data(*args, **kwargs) context['users'] = User.objects.exclude(id=self.request.user.id) return context I have tried to add extra context below: context['users'] = User.objects.exclude(id=self.request.user.id) context['friend'] = Friend.objects.get(current_user=request.user) context['friends'] = Friend.objects.all() return context Apparently it is not the right way to do it. Any help would be much appreciated. (I am still new to Class based views) -
Django - trying to clean email field is throwing ''dict' object has no attribute 'strip'"
Halfway through my project I realized that I am able to create an account using the same email address. This will definitely create some problems later (recovering account, etc). So I came up with the idea to clean the email field by testing to see if an account is already registered in the database by searching for the email. class UserRegistrationForm(forms.ModelForm): ... email = forms.CharField(label='Email', widget=forms.EmailInput(attrs={'class':'form-control form-control-sm'})) ... class Meta: model = User fields = {'username', 'first_name', 'last_name', 'email'} def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email is already registered") return self.cleaned_data This should be able to solve the problem, but it is throwing the 'dict' object has no attribute 'strip' I also made sure to set the cleaned email in the function. Here is my register method: def register(request): if request.user.is_authenticated: return redirect('somewhere') else: if request.method == "POST": user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # begin google reCaptcha validation recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) # end of reCaptcha validation if result['success']: # create a new user but avoid saving it yet new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.set_email(user_form.cleaned_data['email']) new_user.save() … -
Django - How to add update and delete comment
I'm just new to django. I'm having a hard time how can i add an update and delete functions in my comment section. here's my forms.py for comment. class CommentForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Type your comment', 'id': 'usercomment', 'rows': '4' })) class Meta: model = Comment fields = ('content', ) and here's my views.py for comment. it's attach to my bookdetail. def BookDetail(request, slug): most_recent = Book.objects.order_by('-timestamp')[0:3] book= get_object_or_404(Book, slug=slug) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = book form.save() return redirect(reverse("book-detail", kwargs={'slug': slug})) if request.user.is_anonymous: user_membership = None else: try: user_membership = Customer.objects.get(user=request.user) except Customer.DoesNotExist: user_membership = None context = { 'user_membership': user_membership, 'form': form, 'book': book, 'most_recent': most_recent, } return render(request, 'catalog/book_detail.html', context) I hope someone can help me. thanks. -
I want to add data validator in my signup from dynamically
i want display error in input field separately in signup from. but after submitting with invalid inputs page redirect to same page but no errors are displayed in the input. i have written my code like: in Singup from forms={} if form.errors: for key,value in form.errors.items(): forms[key]=value return render(request, 'signup.html',{'forms':forms}) in template <script> {% for key,value in forms.items %} $(document).ready(function(){ $('input[name={{key}}]').parent().addClass("alert-validate"); $('input[name={{key}}]').parent().attr("data-validate", "{{value | safe}}"); }); {% endfor %} </script> -
passing choices by list
I'm using choices to save to database and when saved it appears ['option1', 'option2'] and I need only the correct name to appear. and I need my model to continue as models.CharField models.py PETN_CHOICES = ( ('Cachorro','Cachorro'), ('Gato','Gato'), ('Pássaros', 'Pássaros'), ('Peixes','Peixes'), ('Reptéis','Reptéis'), ('Roedores','Roedores') ) class Negocio(models.Model): pet_aceitos = models.CharField(max_length=255, choices=PETN_CHOICES) forms.py PETN_CHOICES = ( ('Cachorro','Cachorro'), ('Gato','Gato'), ('Pássaros', 'Pássaros'), ('Peixes','Peixes'), ('Reptéis','Reptéis'), ('Roedores','Roedores') ) class NegocioForm(UserCreationForm): pet_aceitos = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=PETN_CHOICES, ) -
django-environ: how to separate INSTALLED_APPS for dev and prod
I am using djano-environ for my settings In django development i am planning to install django-extensions app which i need only in development. So what is the recommended way to use django-environ for prod and dev w.r.t INSTALLED_APPS I have to add it to the INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party apps 'django_extensions', ] Now how to use django-envion's .env file which will pass INSTALLED_APPS because i will have a different .env files for dev and prod -
Restrict access to Website/IP to specific OpenVPN client
I have a digitalocean droplet running Ubuntu 18.04.2 and nginx, and an API built with the Django Rest Framework on it. The specs of the project I'm working on require a VPN to be set up, so I've set up OpenVPN on the droplet. I've also generated a config file to send to the client that will be connecting to my API. My API is currently still accessible by anyone who has the IP address and the username/password combination I've created. My question is: how can I configure my server/OpenVPN to allow access only to the client that I am going to give the configuration file to? -
Serializers: Customising nested relationships
I have the following data structure which is similar to what is shown in the serializer nested relationships example. Models: class Entities(models.Model): name = models.CharField(max_length=100, help_text="name of the object") description = models.CharField(max_length=100, help_text="description of the object") class EntitiesAVP(models.Model): entity = models.ForeignKey(Entities, related_name='attributes', on_delete=models.CASCADE) attribute = models.CharField(max_length=64, blank=False, null=True, help_text="name of the attribute") value = models.CharField(max_length=255, blank=False, null=True, help_text="value of the attribute") As per the example, I am exposing this data in my API using the following serializers: class EntitiesAVPSerializer(serializers.ModelSerializer): class Meta: model = EntitiesAVP fields = ('attribute', 'value') class EntitiesSerializer(serializers.ModelSerializer): attributes = EntitiesAVPSerializer(many=True, read_only=True) class Meta: model = Entities fields = ('name', 'description', 'attributes') This exposes my example data in the following JSON structure: [ { "name": "Test Entity", "description": "Description of test entity", "attributes": [ { "attribute": "attribute 1", "value": "value 1" }, { "attribute": "attribute 2", "value": "value 2" }, { "attribute": "attribute 3", "value": "value 3" } ] } ] What I would like, is to present my attributes in the following format: [ { "name": "Test Entity", "description": "Description of test entity", "attributes": { "attribute 1": "value 1" "attribute 2": "value 2" "attribute 3": "value 3" }, ] } ] To try and achieve this, I … -
Why parent validation isn't working while directly called using CreateView/ModelForm?
I'm trying to set a simple form, for user to input IP subnet into my django app. I want to validate that IP + Mask is a subnet address. I'm using CreateView with IpRangeForm. However, I've noticed a problem, that when I override ModelForm clean method, my model validation doesn't work. Model: class IpSubnet(models.Model): ip = models.GenericIPAddressField(verbose_name="IP", protocol='IPv4') mask = models.IntegerField(verbose_name="Mask") View: class IpSubnetCreateView(SuccessMessageMixin, CreateView): form_class = IpSubnetForm model = IpSubnet success_url = '/front/' success_message = "%(ip)s/%(mask)s added" ModelForm: class IpSubnetForm(forms.ModelForm): class Meta: model= IpSubnet fields = ( 'ip','mask') def clean(self): cleaned_data = super(IpSubnetForm, self).clean() ip = cleaned_data.get('ip') mask = cleaned_data.get('mask') subnet = ipcalc.Network(ip + "/" + str(mask)) if ip != subnet.network(): raise ValidationError( _('%(ip)s/%(mask)s is not a network address (network address: %(network)s/%(mask)s)'), params={'ip':str(ip), 'mask' : str(mask), 'network':str(subnet.network())}, ) return cleaned_data If I delete my clean method, model validation works fine. With my clean method, only the subnet validation works, so user can input i.e. chars into IP field. I don't see any difference if I add or delete call to parent: super(IpSubnetForm, self).clean() Therefore it looks like in my case I should use some other way? How can I fix it, what mistake am I making? -
Django Migrations wont change the models after setting the primary key
I have imported db tables from sql to SQLite and I cant do the migrations after setting the primary key I have run the python manage.py makemigrations command and the python manage.py migrate command but cant seem to force the migrations to take place Looks like this is a bug in python I am stuck for like more than an hour now -
django_filters using multiple choices does not return results
I have a system and I am using django_filters to do the filtering, it is working, in the state that is a models.CharField field with choices = STATE_CHOICES more in the field pet_aceitos that is a MultiSelectField, it does not return any value, even though have these values registered. It appears right with the widget to be able to choose one or more fields, but even though I choose apanas one that I'm sure is registered, and click on the search it does not return this search as success. I will briefly outline my code so you can help me. thanks any help I'm using google translator, I'm Brazilian, summarizing the question, when I search the field with multiple choices it always appears as no results found models.py class Negocio(models.Model): pet_aceitos = MultiSelectField(max_length=255, choices=PETN_CHOICES) views.py def search(request): negocio_list = Negocio.objects.all() negocio_filter = NegocioFilter(request.GET, queryset=negocio_list) return render(request, 'search/negocio_list.html', {'filter': negocio_filter}) urls.py url(r'^search/$', views.search, name='search'), filters.py import django_filters from django import forms from django.forms.widgets import CheckboxSelectMultiple from .models import ( Negocio, Usuario ) PETN_CHOICES = ( ('Cachorro Pequeno Porte','Cachorro Pequeno Porte'), ('Cachorro Médio Porte','Cachorro Médio Porte'), ('Cachorro Grande Porte','Cachorro Grande Porte'),('Gato','Gato'), ('Pássaros', 'Pássaros'), ('Peixes','Peixes'), ('Reptéis','Reptéis'), ('Roedores','Roedores') ) class NegocioFilter(django_filters.FilterSet): pet_aceitos = django_filters.MultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, … -
Django - how to render all pages of pdf files at once
I am trying to make a pdf viewer in html template using pdf.js in Django framework. I had used a code that I got from a Youtube channel Traversy Media on how to create a custom PDF Viewer With JavaScript. It is working but i want to know if its possible to render all pages at once. here's the link of the pdf.js full code in github... https://github.com/bradtraversy/pdf_viewer/blob/master/js/main.js or there's alternative way rather than sticking to this code? -
Static variable and method in Django models file and how to add a decimal field for a static variable in Django admin interface
I'm making a web page by using Django that counts coin collected. Each coin has its coin_type and coin_count. I also want to have a static total variable "total" that calculates the total amount of coins. I want to make a function that can calculate the sum of all instances' coin_count and assign that value to total. However, when I declare "total" inside the class, its value is different for every instances. Moreover, I don't know how to have a decimal field for a static variable in Django admin interface. In the code below, I create a global variable "total" so that its value doesn't change for every class instances. However, every time I change the code or restart the server, its value is reset to 0. This is my models.py file # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. total = 0 class Coin(models.Model): coin_type = models.CharField(max_length=100) coin_count = models.DecimalField(max_digits=3,decimal_places=0) def __str__(self): return self.coin_type def count(self): return self.coin_count def increase(self): self.coin_count += 1 @staticmethod def find_total(): global total return total I want to have a static variable "total" that has the same value for all instances and a static … -
How to save images that I get in a POST request using ajax?
I am new to Django. I create a form for identification with two fields for upload images - main_photo, profile_photo I have a Django form that upload images. With the help of ajax FormData() (I'm working with her wrong maybe), I send them to a function via POST request. But I can not store them. Help me. template <input type="hidden" name="csrfmiddlewaretoken" value="9S6oPbkHujBnxaKHSxzU5W4mdkEs6Lbbf3g0OIJAk3lBfaMV8bafzpz8QudIuofJ"> 9S6oPbkHujBnxaKHSxzU5W4mdkEs6Lbbf3g0OIJAk3lBfaMV8bafzpz8QudIuofJ <div class="field inline"> <div class="subhead"></div> <input type="file" name="main_photo" required="" id="id_main_photo"> <label for="foto1" class="id_foto"> <div class="addPhoto"> <div class="button"></div> </div> </label> </div> <div class="field inline"> <div class="subhead"></div> <input type="file" name="profile_photo" required="" id="id_profile_photo"> <label for="foto2" class="id_foto"> <div class="addPhoto"> <div class="button"></div> </div> </label> </div> <div class="center"> <button class="submit mgln" type="button"></button> </div> jquery var token = '{{csrf_token}}'; $('.mgln').on('click', function(){ photo = new FormData(); photo.append('file1', $('input[name=main_photo]').prop('files')[0]) photo.append('file2', $('input[name=profile_photo]').prop('files')[0]) photo1 = photo.getAll('file1') photo2 = photo.getAll('file1') data = { photo1: photo1, photo2: photo2, } console.log(data) $.ajax({ headers: { "X-CSRFToken": token }, type: "POST", url: "{% url 'identification_view' %}", data: data, processData: false, contentType: false, success: function(result) { alert('Ok.'); }, error: function(result) { alert('Error.'); } }) }) views def identification_view(request): if request.method == 'POST': form = IdentificationForm(request.POST, request.FILES) if request.is_ajax(): print(request.POST.values()) #[] print(request.FILES.values()) #[] return HttpResponse('image upload success') else: form = IdentificationForm() identifications = RequestUser.objects.filter(user = … -
export PS1='sameerjagtap:~#' command works perfectly from Command line but fails from pexpect
Using command export PS1='sameerjagtap:~#' to set prompt to "sameerjagtap:~#" on Ubuntu always fails from pexpect but works from Command line. -
Django model function to save ImageField if none image given = execption
i have a Django models function to save an image correctly. Currently it seems that Django-SmartFields is buggy at that point, see: https://github.com/lehins/django-smartfields/issues/17 and sorl is not working properly, no idea why. So i quickly have written down this: models.py def save(self, *args, **kwargs): imageTemproary = Image.open(self.postcover) outputIoStream = BytesIO() imageTemproaryResized = imageTemproary.resize((700, 525)) imageTemproaryResized.save(outputIoStream, format='JPEG', quality=85) outputIoStream.seek(0) self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.jpeg" % self.postcover.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None) super(Post, self).save(*args, **kwargs) this is the field at my actual modely.py postcover = fields.ImageField( verbose_name="Cover", blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[default_image_size, default_image_file_extension] ) But if i now want to clear the Picture trough my form i get the following error: The 'postcover' attribute has no file associated with it. Does smb. has a quick workaround on that behaviour? Thx in advance -
Import SQLite to MySQL, DecimalField rounded off
I tried to migrate my database to MySQL from SQLite, but I couldn’t figure out how to keep the parameters set for Decimal type so that the Precision and Scale (specified as max_digits and decimal_places parameters in Django) remain the same after importing to MySQL. I got my SQLite dump script from here http://www.techtrek.io/migrate-from-sqlite3-to-mysql/. After running the dump script via MySQL Workbench 8.0, I don’t know why the Precisions are not as I specified in Django and are all over the place. Similarly the Scales are all set to zero after running the script (see pic). Even after changing the precision and scale for individual columns with an “ALTER TABLE table MODIFY COLUMN column decimal(#,#)” command, I couldn’t get the remaining digits back, and they were all reset to zero. Do I need to modify the dump script or change something in the MySQL Workbench? -
Add Rich Text outside admin panel
I need to add a Rich Text outside the admin panel, so that the system user can put text and images. I installed ckeditor, made changes to settings and models, but it does not look like any changes. Settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # apps 'blog', # packages 'ckeditor', 'ckeditor_uploader', ] # Development only + url static MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # CKEditor SETTINGS CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'none', 'extraPlugins': ','.join( ['codesnippet', 'uploadimage', 'uploadwidget', 'widget', 'dialog', ]), 'allowedContent': True, }, } #Configuracoes ckeditor CKEDITOR_ALLOW_NONIMAGE_FILES = False CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' Models: from django.db import models from django.contrib.auth.models import User from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=200) body = RichTextUploadingField() def __str__(self): return self.title Views: from django.views.generic import (CreateView) from forms import PostForm from models import Post class HomeView(CreateView): model = Post form_class = PostForm template_name = 'blog/home.html' url: from django.conf.urls import url from django.conf.urls import include from django.conf import settings from django.contrib import admin from django.conf.urls.static import static from blog import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='index'), url(r'^admin/', admin.site.urls), url(r'^ckeditor/', include('ckeditor_uploader.urls')), ] What would be wrong? …