Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Django server is not working after finished the code
I just started learning Django, trying to build my first blog, after finished the code, I tried to run the server but it's not working, please help me.here is the error -
How to save multiple object in a single POST request
I am new to DRF I am saving a user details and his pets details . Here is the model class Users(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) job = models.CharField(max_length=255, blank=True) age = models.CharField(max_length=255, blank=True) class PetDetails(models.Model): user = models.ForeignKey( Users, on_delete=models.CASCADE, blank=True, null=True) pet_name = models.CharField(max_length=255, blank=True) pet_color = models.CharField(max_length=255, blank=True) pet_category = models.CharField(max_length=255, blank=True) In this I need to save both user and his pets in a single Post request. So I created a serializer like this class UserCreateSerializer(ModelSerializer): class Meta: model = Users fields = ['first_name','last_name','job','age'] class PetDetailCreateSerializer(ModelSerializer): user = UserCreateSerializer() class Meta: model = PetDetails fields = ['user','pet_name','pet_color','pet_category'] def create(self, validated_data): user_data = validated_data.pop('user') user_obj = Users.objects.create(**audit_data) Pet_details = AuditPlanDetail.objects.create(user=user_obj, **validated_data) return Pet_details The issue I am facing is if a single person can have multiple pets. For Example John is a user and he having two Pets. So in this cases two users object will creating .How to resolve this OR is there any other methods for handling this -
How do I fix my docker-compose.yml , error in installing Mayan-EDMS with django
I am trying to install the Mayan-EDMS image with the Django app and Postgres database using docker-compose but each time, I try to build docker-compose using docker-compose up it gives an error. ERROR: yaml.parser.ParserError: while parsing a block mapping in "./docker-compose.yml", line 8, column 3 expected <block end>, but found '<block mapping start>' in "./docker-compose.yml", line 29, column 4 here is my docker-compose.yml docker-compose contain postgres:11.4-alpine,redis:5.0-alpine and mayanedms/mayanedms:3 version: "3" networks: bridge: driver: bridge services: app: container_name: django restart: always build: context: . ports: - "8000:8000" volumes: - ./app:/app environment: - DB_NAME=app - DB_USER=insights - DB_HOST=db - DB_PORT=5432 depends_on: - db command: > sh -c "mkdir -p logs media && python manage.py wait_for_db && python manage.py runserver 0.0.0.0:8000" db: image: postgres:11.4-alpine container_name: postgres volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=insights - POSTGRES_DB=app redis: command: - redis-server - --appendonly - "no" - --databases - "2" - --maxmemory - "100mb" - --maxclients - "500" - --maxmemory-policy - "allkeys-lru" - --save - "" - --tcp-backlog - "256" - --requirepass - "${MAYAN_REDIS_PASSWORD:-mayanredispassword}" image: redis:5.0-alpine networks: - bridge restart: unless-stopped volumes: - redis_data:/data mayanedms: image: mayanedms/mayanedms:3 container_name: mayanedms restart: unless-stopped ports: - "80:8000" depends_on: - db - redis volumes: - mayanedms_data:/var/lib/mayan environment: &mayan_env MAYAN_CELERY_BROKER_URL: redis://:${MAYAN_REDIS_PASSWORD:-mayanredispassword}@redis:6379/0 MAYAN_CELERY_RESULT_BACKEND: … -
How to add the absolute URL field to related post in Django models
I was wondering if there's a way to add absolute URL field to related post inside the Django model. I tried using slug field but that didn't work. -
Create a seperate model with other fields for users with staff user status?
I want to create another model only for the staff and not for the admin or normal users. The model will have some other data that will also be visible for the other users but the other users will not require any if this data. Also, the staff members will have another separate app for themselves. How do I link another model to each user that has a staff permission? class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Not sure how i'm supposed to link only the staff members. -
how to create custom admin panel for django
Hi there I'm learning to django and I want to create custom admin for my django project so I can deliver my project to clients with beautiful admin panel. Please suggest me some ideas for doing this. can it be possible with react? Please share your thoughts thanks -
How to create search field lookup like Yahoo Finance symbol field
Guys i want to create search in one field where when a user types code it can see drop down suggestions ( from only db not internet) like the one from https://finance.yahoo.com/quote/AAPL. When i type AAPL ticker in yahoo finance search field -it gives autocomplete or suggestions like Apple Inc and Equity-NMS. I am not sure how it is called as i am new to django but i would like to learn what technology , package is used to create such dynamic form. I want create form my own DB rather than from internet so i assume it should be easier to implement ? What type of method do they use so i can do my reserach and explore more about it. I looked to autocomplete light but i feel like it is not what i am looking for. Would appreciate any advice and suggestions. -
How can I add an object to a group when it is created?
I need to save an object to a group at the time of creation. I have Porumbei and Grupuri models. Each Porumbei must belong to a Grupuri. I have 4 different Grupuri and depending on form fields value, it must be added to the right Grupuri. Is there a 'best practice'? Below are may models. Grupuri class Grupuri(models.Model): """ Definire model pentru salvarea porumbeilor in grupuri""" nume_grup = models.CharField(max_length=50, unique=True) porumbei = models.ManyToManyField(Porumbei, related_name="grup_porumbei") Porumbei class(models.Model): id_porumbel = models.AutoField(primary_key=True) serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True, help_text="Seria de pe inel. Ex: RO 123456") is_active = models.BooleanField(default=True) status = models.ForeignKey(StatusPorumbei, on_delete=models.PROTECT) ... My view def porumbelnou(request): if request.method == "POST": # crescator=request.user - folosit pentru a filtra porumbeii crescatorului logat form = AdaugaPorumbel(request.POST, request.FILES, crescator=request.user) if form.is_valid(): obj = form.save(commit=False) obj.crescator = request.user obj.save() return redirect('porumbei') else: # crescator=request.user - folosit pentru a filtra porumbeii crescatorului logat form = AdaugaPorumbel(crescator=request.user) context = { 'form': form, } template = loader.get_template("adaugare-porumbel.html") return HttpResponse(template.render(context, request)) What I try but it got me MultiValueDictKeyError on 'id_porumbel' if form.data['is_active']: toti = Grupuri.objects.get(nume_grup__exact="Toti porumbeii") toti.porumbei.add(form.data['id_porumbel']) -
How to run an entire external python file on click of a button in html
I want to run a python file from an html page. I want to run the entire script and not a single function. Returning a value to the page is not required -
Override requiered field in validator django DRF
I have simple EmployeeSkill and Skill models: class EmployeeSkill(models.Model): # this is required employee = models.ForeignKey( Employee, on_delete=models.CASCADE ) # this is required skill = models.ForeignKey( Skill, on_delete=models.CASCADE ) def skill_name(self): return self.skill.name class Skill(models.Model): # this is required name = models.CharField(max_length=255, unique=True) I want to keep the skill attribute of EmployeeSkill required in the model, but I want to enable passing only a skill name in the serializer, which would get or create the appropriate Skill. Here is my serializer: class EmployeeSkillSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "employee", "skill", "skill_name", ) model = EmployeeSkill extra_kwargs = { "skill": {"required": False}, } def validate_skill(self, value): """ custom validator for skill. skill can be empty if skill_name is valid """ if value is None: skill_name = getattr(self, "skill_name", None) if not (skill_name and type(skill_name) is str): raise serializers.ValidationError( "if no skill is provided, skill_name should be a valid string" ) elif not type(value) is Skill: raise serializers.ValidationError("skill must be of type Skill or None") return value def create(self, validated_data): if (not self.skill) and self.skill_name: validated_data["skill"] = Skill.objects.get_or_create(skill_name=self.skill_name)[0] super().create(validated_data) The problem is, I still get an error: { "skill": [ "This field may not be null." ], } Any idea on … -
Unable to pass arguments in python3 class
Firstly, I created a class that has init() on it in models.py, as you can see below. And when I import it in my views.py, the vscode intellisense also shows that my class takes 4 arguments. But when I try to run the program, it shows me an error saying that the class doesn't take any arguments. Any help would be appreciated, ty. // models.py --------------- from django.db import models class destination: def __init__(self, name, desc, price, img): self.name = name self.desc = desc self.price = price self.img = img // views.py -------------- from django.shortcuts import render from .models import destination dest1 = destination('Bali', 'Nice place to visit', 1000, 'destination_1.jpg') dest2 = destination('Mumbai', 'The city that never sleeps', 500, 'destination_2.jpg') dest3 = destination('Sylhet', 'The city of tea', 100, 'destination_3.jpg') dests = [dest1, dest2, dest3] def travello(req): return render(req, 'index.html', {'dests': dests}) // when I run python3 manage.py runserver ------------------------------------------ Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/base.py", … -
Django Ajax like button not changing when user likes a post in a post list
I am trying to build a like button like social media apps where user likes the button on a post and then the button changes, however, my button does not change but, the like count does change. I am using ajax. in my post list template i ave this that includes the like form: <div id="like-section"> {% include 'home/posts/likes.html' with post=post %} </div> my likes.html: {% if request.user.is_authenticated %} <form action="{% url 'home:post-like' post.id %}" method="POST"> {% csrf_token %} {% if post.is_liked %} <button type="submit" id="likeBtn" data-url="{% url 'home:post-like' post.id %}" data-token="{{ csrf_token }}" name="post_id" value="{{ post.id }}" class="btn btn-sm"> <span class="text-primary"> <i class="fas fa-thumbs-down"></i> {{ post.likes.count }} </span> </button> {% else %} <button type="submit" id="likeBtn" data-url="{% url 'home:post-like' post.id %}" data-token="{{ csrf_token }}" name="post_id" value="{{ post.id }}" class="btn btn-sm"> <span class="text-primary"> <i class="fas fa-thumbs-up"></i> {{ post.likes.count }} </span> </button> {% endif %} </form> {% endif %} my view: @login_required def post_like(request,id): data = dict() post = get_object_or_404(Post, id=id) user = request.user if post.likes.filter(id=user.id).exists(): post.likes.remove(user) else: post.likes.add(user) data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['html'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) return JsonResponse(data) my javascript code: $(document).ready(function (e) { $(document).on("click", "#likeBtn", function (e) { e.preventDefault(); var pk = $(this).attr("value"); var tk = … -
How do I access the original data from object in python. Here I've used group by to group data. Can someone please help me with this issue?
I am trying to group data based on the following data fields I have, and when I am not able to access the original data in the fields Printing the filtered_data is giving something like "object at 0x10dd1abf0>", so I need to access the original human-readable value in the objects. data_objects = ['*', '*', '*', ......] // This is list of data items filterd_data_objects = groupby( data_objects, lambda data: (data.x, data.y, data.z) and data.p ) for filterd_data_object, _ in filterd_data_objects: x = data_object[0] // this is not working I've tried this to access the original data y = data_object[1] z = data_object[2] p = data_object[3] -
self.form_valid(form) returns "TypeError: 'NoneType' object is not callable"
Getting 'TypeError: 'NoneType' object is not callable', when self.form_valid(form) is called. I got a lot of solution from stackoverflow for this kind of error, I tried everyone of them but till now the error is there. Before going to error, I want to describe my view, form and html input form. view.py class CancelView(FormView): template_name = 'cancel.html' form_class = CancelForm def post(self, request): form = self.form_class(request.POST) if form.is_valid(): if form.cleaned_data.get('canceled'): try: print(form) except Exception: return self.form_invalid(form) return self.form_valid(form) else: return redirect(reverse_lazy('MyPage')) return self.form_valid(form) Here form.is_valid() and form.cleaned_data.get('canceled') are working fine. If I print the form here it returns: <input type="hidden" name="canceled" value="True" id="id_canceled"> form.py class CancelForm(forms.Form): use_required_attribute = False canceled = forms.BooleanField( initial=False, widget=forms.HiddenInput(), required=False, ) HTML Template <form action="." method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}"> <p class="text-center link__btn--block"><input value="Decline Cancellation." class="w50" type="submit"></p> <input id="id_canceled" name="canceled" type="hidden" value="False"> </form> Error Log Traceback (most recent call last): File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/Users/mahbubcseju/Desktop/projects/works/bidding-demo/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, … -
Pandas Read CSV in django view not working
What I'm trying to do is, when user uploaded the CSV file. I'm trying to do functionalities in pandas. Django template <form action="{% url 'upload-timeslot' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> My view def bulk_timeslot_upload(request): if request.FILES: import pandas as pd csv = request.FILES['fileToUpload'] data = pd.read_csv(csv) print(data) return render(request, 'bulk-timeslot.html') when i tried to read csv, running server getting exited. If I import pandas globally, server not even running. -
Django User model : how to make it with image and username?
I'm trying to make a user model in Django. My User fields are id(auto increment, PK), userImage(unique), username(not unique). I need to make a web application that registers & logs in only with userImage and username. I don't want to use password for the model but it seems that Django user model asks for password as a default (even when using AbstractUser). Also tried custom backend but when I try testing in admin, it still requires password. Is there a way to customize my user model? -
How to make sure that my django project is using virtual environment that i created for it?
I know that there is already a question similar to this,but i think the answer i wanted is not there. I am new to django.i have created an virtual environment with virtualenv and a django project,but how can we know that my project is using the packages of virtual environment rather than using global packages??please give me some detailed answer.THANKS in advance. -
Customizing each row of the model in admin page
I am customizing django admin template. I can successfully remove button like (+add model) or some filter by changing overriding change_list_results.html and change_list.html but now I want to customize each rows of the model to off the link.(I don't want to let the user go each rows editing page.) I am checking change_list_result.html {% load i18n static %} {% if result_hidden_fields %} <div class="hiddenfields">{# DIV for HTML validation #} {% for item in result_hidden_fields %}{{ item }}{% endfor %} </div> {% endif %} {% if results %} <div class="results"> <table id="result_list"> <thead> <tr> {% for header in result_headers %} <th scope="col" {{ header.class_attrib }}> {% if header.sortable %} {% if header.sort_priority > 0 %} <div class="sortoptions"> <a class="sortremove" href="{{ header.url_remove }}" title="{% trans "Remove from sorting" %}"></a> {% if num_sorted_fields > 1 %}<span class="sortpriority" title="{% blocktrans with priority_number=header.sort_priority %}Sorting priority: {{ priority_number }}{% endblocktrans %}">{{ header.sort_priority }}</span>{% endif %} <a href="{{ header.url_toggle }}" class="toggle {% if header.ascending %}ascending{% else %}descending{% endif %}" title="{% trans "Toggle sorting" %}"></a> </div> {% endif %} {% endif %} <div class="text">{% if header.sortable %}<a href="{{ header.url_primary }}">{{ header.text|capfirst }}</a>{% else %}<span>{{ header.text|capfirst }}</span>{% endif %}</div> <div class="clear"></div> </th>{% endfor %} </tr> </thead> <tbody> {% for … -
when i run python manage.py runserver i got this error
Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python38-32\Lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\user\appdata\local\programs\python\python38-32\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "E:\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "E:\venv\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "E:\venv\lib\site-packages\django\core\management\base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "E:\venv\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "E:\venv\lib\site-packages\django\db\migrations\loader.py", line 49, in init self.build_graph() File "E:\venv\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "E:\venv\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "E:\venv\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "E:\venv\lib\site-packages\django\db\migrations\graph.py", line 195, in [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "E:\venv\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0004_auto_20200315_2142 dependencies reference nonexistent parent node ('users', '0001_initial') -
Django extending not functioning within other templates when run through Github Pages
I have a base.html file, when run locally on vs code, works to extend bootstrap and css page layout to other template pages. When run through github pages, django functionality is no longer working. Here is the TimeSheet.html where I extend style from the base.html {% extends "base.html" %} {% block content %} Here is my base.html <head> <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <link> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> When I load the TimeSheet.html page on github pages, it is not properly extending the base, and just echos the code as a literal string. {% extends "base.html" %} {% block content %} -
I am getting a IntegrityError UNIQUE constraint failed for django
I am getting an integrity error for creating a customer here. When the first customer tries to create an account this code works. But when new customer comes and tries to create a account it give the UNIQUE constraint failed. Where as When a seller tries to create an account it creates it, it works for every new seller. But this codes doesn't seem to work for the customer. This was the first error. And I got another error as FieldError at /accounts/customer/register/ Cannot resolve keyword 'user' into field. Choices are: active, address, customer, customer_id, email, id, order, timestamp, update when I try to save the email of that Customer it gives this error. Since I have a billing model set up and its given in the bottom below. And this one doesn't work even for the first customer who comes and tries to create an account. I used a custom user model accounts models.py class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) … -
pipenv set path of virtual environment in vs code
I'm using visual studio code on windows 10, using python and django. The problem I have is that whenever I create a new virtual environment it takes place on its default folder, I'd like to change it to take place in the address I specify. How can I specify the folder that virtual environment takes place in? So far, I've tried different ways to solve this problem, but none of work for me, this could be because of the system and tools I'm using, I've tried setting the path variables using set command, like: set Path="~/.ven" I also looked for changing the variables of pip and pipenv but I couldn't make it work. I also searched the similar questions on stackoverflow, I couldn't find a proper answer. Also in the documentation of pipenv, I couldn't find the solution. Thanks for reading and your time. -
ModuleNotFoundError:No module named 'users.urls'
I'm using Django3, and I want to make app to add users login. and here is my code in users/urls.py.I'm stuck here for amount of time.What's the problem? enter image description here -
Add hyperlink to columns in DataTables
Im newbie in using DataTables, I created a webpage that uses client-side processing to load the data. I want to add Hyperlink in my columns using "columns.render" to view the details in entire row where the value of ID/pk corresponds to the hyperlinked text, so that if a user click the Id/hyperlink in ID columns they would be rerouted to a separate page, "VM/Details/(id/pk)". How I fixed this? JS $(document).ready(function() { var table = $('#vmtable').DataTable({ "serverSide": false, "scrollX": true, "deferRender": true, "ajax": { "url": "/api/vm/?format=datatables", "type": "POST" }, "columns": [ {"data":"id", "render": function(data, type, row, meta){ if(type === 'display'){ data = '<a href="VM/Details/' + data.id + '">' + data + '</a>'; } return data; } }, {"data": "Activity_Id"}, {"data":"NO"}, {"data":"First_name"}, {"data":"Last_name"} ] }); html <table id="vmtable" class="table table-striped table-bordered" style="width:100%" data-server-side="false" data-ajax="/api/vm/?format=datatables"> <thead> <tr> <th>Id</th> <th>Activity No</th> <th>NO</th> <th>First Name</th> <th>Last Name</th> </tr> </thead> </table> Path that I want to rerouted after click the hyperlink path('VM/Details/<int:pk>', vmDetails.as_view(), name='vm_details'), But I got an error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/VM/Details/undefined -
Incorrect Server Response in Ckeditor Django
I want a non-admin user to be able to send an image on ckeditor's post. The problem happens that I can send the image in the post if the user is admin but if it is a simple user I cannot because it shows Incorrect Server Response in Ckeditor Django. my settings below: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'l$+3%scpx$n(ne!ky6b#!1p6q7pw-cnvl2*35v9_4akia0hswn' DEBUG = False ALLOWED_HOSTS = ['devcapivara.com.br', 'www.devcapivara.com.br'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #My Apps 'accounts', 'core', 'post', #third 'ckeditor', 'ckeditor_uploader', 'widget_tweaks', 'easy_thumbnails', ] CKEDITOR_UPLOAD_PATH = 'uploads/' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'capivara_blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'capivara_blog.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # auth LOGIN_URL = 'accounts:login' LOGIN_REDIRECT_URL = 'core:dashboard' LOGOUT_REDIRECT_URL = 'accounts:login' LOGOUT_URL = 'accounts:logout' # Usando o módulo USER da nossa aplicação ACCOUNTS AUTH_USER_MODEL = 'accounts.User' # Autenticação por email/username AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.ModelBackend', …