Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filtering too slow
I have a lot of data in my mongoDB and I'm trying to filter these data on my Django page in search form. User send parameters to views.py which conditions want to search and views.py search that data in DB and send result back in CONTEXT dictionary like this return redirect(f"/terema/kensaku/?q={url_data}&page={page_number}", self.CONTEXT) I'm searching data using this style all_searched_data = self.model.objects.filter(address__icontains=full_adress) where model is DB collection, full_address is a variable containing data from users. This work nice, when my users are very specific about searching, but when they try to search like typing only name of city to the full_address there is a too much matches in DB and user get Gateway Timeout. I want to say that django's filter + __icontains is too slow when I have a lot of matches. Is there a way to avoid this? Plus it brings my server cpu on 100% for like 20 minutes -
DJANGO BLOG POST PERMISSION
I need to create a django blog as follows, the administrator creates the content in django-admin, and directs the content to a specific user, this post can only be viewed by that user chosen by the admin -
Reverse for 'movie_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['movie/(?P<slug>[-a-zA-Z0-9_]+)$']
I'm creating a Movie app in Django. Created slider in movie app trying getting last 3 value but it is not working, when I try to get last 3 value it shows error. I.m trying to retrieve values from the object in Django. I tried lots of things, none worked. I posted all my project files below. you can have a look. I would be glad if you guys help me. My code goes here : slider.py from .models import Movie def sider_movies(request): movie = Movie.objects.all().order_by('-id')[:3] return {'slider_movie':movie} urls.py from django.urls import path from .views import MovieList,MovieDetail,MovieCategory,MovieLanguage,MovieSearch,MovieYear app_name = 'movie' urlpatterns = [ path('',MovieList.as_view(), name = 'movie_list'), path('category/<str:category>',MovieCategory.as_view(), name = 'movie_category'), path('language/<str:language>',MovieLanguage.as_view(), name = 'movie_language'), path('search/',MovieSearch.as_view(), name = 'movie_search'), path('<slug:slug>',MovieDetail.as_view(), name = 'movie_detail'), path('year/<int:year>',MovieYear.as_view(), name = 'movie_year'), base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Movies</title> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"> <!-- Link Swiper's CSS --> <link rel="stylesheet" href="{% static 'css/swiper.min.css' %}"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/script.js' %}"></script> <!-- Demo styles --> <style> </style> </head> <body> <div class="wrapper"> <header class="header"> <figure class="logo"> <a href="/"><img src="{% static 'img/logo.png' %}" alt="Logo"></figure> </a> <nav class="menu"> <ul> <li><a href="/">Home</a></li> … -
How can I unuse some middlewares in some view?
For some reasons. I want to mark some middlewares as unused in some special view to improve its performance. Is there any functions or decorators in django I can use to do this? -
How to override Django AuthenticationForm inactive message
I am trying to display a custom error message when an account exists but is inactive. To do this I am overrriding the AuthenticationForm's error_messages. forms.py: class AuthForm(AuthenticationForm): error_messages = { 'invalid_login': ( "This custom message works" ), 'inactive': ( "This custom message does not." ), } urls.py: path('login/', auth_views.LoginView.as_view( template_name='employees/login.html', authentication_form=AuthForm), name='login'), As you can see the inactive message does not work. Thoughts on why? -
How to combine 2 queryset into one?
I have 3 models. Module, Task, and Lesson. Lesson is related to Module through an FK. Task is connected to Lesson through FK. I am trying to get all the lessons and tasks in a single queryset of a particular module. class Module(models.Model): name = models.CharField(max_length=255) class Lesson(models.Model): name = models.CharField(max_length=255) module = models.ForeignKey('module', on_delete=models.CASCADE) class Task(models.Model): name = models.CharField(max_length=255) lesson = models.ForeignKey('lesson', on_delete=models.CASCADE) I want to get all the related Lessons to a module and the tasks related to it in a single queryset. This is what I have tried module = Module.objects.get(id=57) lessons = Lesson.objects.filter(module=module) tasks = Task.objects.filter(lesson__id__in=[lesson.id for lesson in lessons]) -
heroku requirements.txt bug
Is there a bug that prevents this file from updating the correct python version for heroku to run ?. I have tried everything to get heroku to build python 3.7.7. I have deleted my heroku app and rebuilt it with same problems. (ERROR: Could not find a version that satisfies the requirement decouple==0.0.7) <-- this is because heroku is running a older version of python. I personally have nothing but problems getting heroku and django set up and working. I am setting up a simple web page. I'm surprised all the problems im encountering. -
How to fix Parsing error: Unexpected token?
I am trying to change my text color but I keep on getting Parsing error: Unexpected token as an error but don't know why can someone point out where my error is and how I would be able to fix that? Code is below import React from 'react'; import react, { Component } from 'react' import { Plateform, StyleSheet, view,text } from 'react-native'; **Here is where I am trying to change the text color everything seems to be in place but I keep on getting that unexpected token error?** function Header() { return ( <View style={style}> <Text style={[styles.setFontSize.setColorRed]} React Native Font example </Text> <header className="header"> <div className="col1"> </div> <div className="col2"> <div className="menu"> <h3>About</h3> <h3>Cars</h3> <h3>Contact</h3> <h3>Search</h3> </div> </div> </header> ); } export default Header extends Component; This is the error I get? ./src/components/header.js Line 10:78: Parsing error: Unexpected token return ( <View style={style}> <Text style={[styles.setFontSize.setColorRed]} React Native Font example </Text> ^ <header className="header"> <div className="col1"> </div -
Python 3: access resource folders in sub-modules
I have a Django app that is composed of a bunch of optional modules. In settings.py, I dynamically add the configured modules to INSTALLED_APPS and that's great. However, I would like to dispatch the translation files to their own sub-modules. For now, I have a simple: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) On my dev machine, I could add [f"../{module}/locale" for module in loaded_modules] but implementers/production will use pip install <module> and won't be in the same location. I have seen that the way of doing that changed in Python 3.7 (OK) and would be to use a ResourceReader or get_resource_reader() method with a resource_path probably but I can't figure out how to implement that. I've seen a few examples with files where you directly open a file for reading but I'm looking to give the Django translations module a folder in which to search for translations. Anyone knows how I can do this ? (Leaving a Django tag because there might be a Django (translation) specific way of doing this) -
How to do filter(in=...) using a different list for every object I do filter on in Django?
I've written an implementation that explains what I mean. Is there a better way to do what I did? class Rstq(models.Model): pass class Baz(models.Model): rstq_set = models.ManyToManyField(Rstq, blank=True) class Foo(models.Model): # bar_set points to Bar because of many-to-many relationship def get_bars(self): bars = [] for bar in self.bar_set: if bar.rstq in bar.baz.rstq_set: bars.append(bar) return bars class Bar(models.Model): baz = models.ForeignKey(Baz, on_delete=models.CASCADE) rstq = models.OneToOneField(Rstq, on_delete=models.CASCADE) foo_set = models.ManyToManyField(Foo) -
displaye parent model form in chiled model in Django admin app
i want to create days using planing administration interface this what i tried but it seemes that it works for the opposite case models.py class Day(models.Model): SAMEDI = 1 DIMANCHE = 2 LUNDI = 3 MARDI = 4 MERCREDI = 5 JEUDI = 6 VENDREDI = 7 DAY_OF_WEEK = ((SAMEDI, 'Samedi'), (DIMANCHE, 'Dimanche'), (LUNDI, 'Lundi'), (MARDI, 'Mardi'), (MERCREDI, 'Mercredi'), (JEUDI, 'Jeudi'), (VENDREDI, 'Vendredi')) jds = models.PositiveSmallIntegerField( choices=DAY_OF_WEEK, blank=True, null=True) he1 = models.TimeField(auto_now=False, auto_now_add=False) hs1 = models.TimeField(auto_now=False, auto_now_add=False) he2 = models.TimeField(auto_now=False, auto_now_add=False) hs2 = models.TimeField(auto_now=False, auto_now_add=False) class Planing (models.Model): titre = models.CharField( max_length=150, unique=True, blank=False, null=False) description = models.CharField(max_length=400, blank=True, null=True) samedi = models.ForeignKey( 'Day', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') diamanche = models.ForeignKey( 'Day', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') lundi = models.ForeignKey( 'Day', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') mardi = models.ForeignKey( 'Day', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') mercredi = models.ForeignKey( 'Day', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') jeudi = models.ForeignKey( 'Day', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') vendredi = models.ForeignKey( 'Day', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') admin.py class DayInline(admin.StackedInline): model = Day class PlaningAdmin(admin.ModelAdmin): list_display = ('titre', 'description',) inlines = [Dayinline] -
How do I Mock a method that makes multiple POST and GET request all requiring different response data?
I have looked at How to mock REST API and I have read the answers but I still can't seem to get my head around how I would go about dealing with a method that executes multiple GET and POST requests. Here is some of my code below. I have a class, UserAliasGroups(). Its __init__() method executes requests.post() to login into the external REST API. I have in my unit test this code to handling the mocking of the login and it works as expected. @mock.patch('aliases.user_alias_groups.requests.get') @mock.patch('aliases.user_alias_groups.requests.post') def test_user_alias_groups_class(self, mock_post, mock_get): init_response = { 'HID-SessionData': 'token==', 'errmsg': '', 'success': True } mock_response = Mock() mock_response.json.return_value = init_response mock_response.status_code = status.HTTP_201_CREATED mock_post.return_value = mock_response uag = UserAliasGroups(auth_user='TEST_USER.gen', auth_pass='FakePass', groups_api_url='https://example.com') self.assertEqual(uag.headers, {'HID-SessionData': 'token=='}) I also have defined several methods like obtain_request_id(), has_group_been_deleted(), does_group_already_exists() and others. I also define a method called create_user_alias_group() that calls obtain_request_id(), has_group_been_deleted(), does_group_already_exists() and others. I also have code in my unit test to mock a GET request to the REST API to test my has_group_been_deleted() method that looks like this: has_group_been_deleted_response = { 'error_code': 404, 'error_message': 'A group with this ID does not exist' } mock_response = Mock() mock_response.json.return_value = has_group_been_deleted_response mock_response.status_code = status.HTTP_404_NOT_FOUND mock_get.return_value = mock_response … -
django admin - subquery inside list_filter
Given are the following models class Report(models.Model): id = models.CharField(max_length=256, unique=True) name = models.CharField(max_length=256) confidential = models.BooleanField(default=False) class Owner(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE) and the following admin.py from django class OwnerAdmin(admin.ModelAdmin): . . . list_filter = ('report__name',) As expected I get the option to filter based on the name of the report. Yet I would like to only get displayed to filter if the report is confidential, means that the confidential field of the given report is true. How can i achieve this? -
not giving value when i use inside for loop {{product.i.product_name}} but works fine when {{product.0.product_name}}
here is my model class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=200) description = models.CharField(max_length=600) pub_date = models.DateField() image = models.ImageField(upload_to="home/images") the views.py def home(request): products = Product.objects.all() n = len(products) params = {'product': products, 'range': range(n)} return render(request,'home/home.html',params) and the HTML for loop part is {% for i in range %} <div class="col-md-6 col-lg-4 text-center mt-4 "> <div class="card" style="width: 18rem;"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{product.i.product_name}}</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% endfor %} the problem is when I am typing {{product.i.product_name}} it is not giving the product name but it is working when I am giving value instead of I like {{product.0.product_name}} I am not understanding what is the problem -
Django attribute reference error on models attribute: AttributeError: module 'classes.models' has no attribute 'Classes'
Not exactly sure why I am unable to reference a Class as a foreign key for my test results model. Is there something obvious that I am missing here? I was able to reference a user and test id without error, but can't seem to wrap my head around why class is not able to pull back Classes model. Any guidance will be helpful. I have posted my error message and models below. Error Message: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/opt/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/opt/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/opt/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/opt/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/opt/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/opt/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/venv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/opt/venv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/opt/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in … -
Product order/purchase model in Django
I have a product model with name, description, currency, price, vendor and image fields, and I'm trying to implement ordering items, and I'm having a bit of trouble doing that. Basically, what I want is to be able to access an Orders model in the admin and add an order number, customer name (I have already implemented these two), and some products with each product having a quantity. # models.py from django.db import models class Vendor(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Product(models.Model): currencies = [ ('$', "US Dollars ($)"), ] name = models.CharField(max_length=40) description = models.TextField() currency = models.CharField(max_length=5, choices=currencies, default="$") price = models.DecimalField(max_digits=10, decimal_places=2) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) image = models.ImageField(default="not_found.jpg") def __str__(self): return self.name class Customer(models.Model): name = models.CharField(max_length=30) date_of_birth = models.DateField() def __str__(self): return self.name class Order(models.Model): order_number = models.CharField(max_length=20) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) My attempts/solutions: Adding ManyToManyField to Product (No Quantity) Creating ProductInstance class with fk to product and order (Quantity added but You have to visit 2 different pages in the admin, and you can't see the items in orders page of admin) Are there any other ways I can implement this or am I stuck with the second solution? It wouldn't … -
Django Admin - Overriding the "groups" selector widget
Django seems to use the FilteredSelectMultiple widget in its admin for groups and permissions. Since I have only two groups, I would like to replace the filtered widget with checkboxes. I tried using the CheckboxSelectMultiple widget, but I'm not sure what the problem is. The Django docs have this example: class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': RichTextEditorWidget}, } I'm using custom user and group models, and this is part of my code: from django.contrib.admin.widgets import FilteredSelectMultiple from django.forms import CheckboxSelectMultiple @admin.register(UserAccount) class MyUserAdmin(UserAdmin): formfield_overrides = {FilteredSelectMultiple: { 'widget': CheckboxSelectMultiple}, } fields = ("email", "password", "first_name", "last_name", "is_active", "is_staff", "is_superuser", "groups", ) It isn't working and I'm not getting any error messages either. Could someone please help me figure out what's wrong, or suggest a way to get checkboxes instead of the existing widget. -
Updating a Django Model from DetailView
I have a Django model that is receiving most of it's variable values from a form created by User 1 using CreateView. User 1 creates an object and selects most field values. Once the object is created it is posted to a wall, another user (User 2) can access the object and add information for the final unfilled field. My question is, how do I allow for this functionality in the DetailView html form? In the code below, "basketball.salary2" is the previously empty field User 2 will be inputting and posting in the DetailView. All other values are already filled in and displaying in the HTML. basketball_detail.html: {% extends "base.html" %} {% block title %}By: {{ basketball.creator }}{% endblock %} {% block content %} <h2>{{ basketball.creator }} has placed an opinion:</h2> <p>{{ basketball.creator }} says that {{ basketball.player }} deserves {{ basketball.salary1 }} <p> Do you agree with {{ basketball.creator }}? </p> <p>I believe {{ basketball.player }} deserves {{ basketball.salary2 }} <p> {% endblock content %} views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Basketball class BasketballListView(LoginRequiredMixin, ListView): model = Basketball class BasketballDetailView(DetailView): model = Basketball class BasketballCreateView(LoginRequiredMixin, CreateView): model … -
What is the best language to make this site [closed]
I want to create site with connection to SQL, login through networks, live chat and a web-game. Here is an example: cs.fail . Please, what framework should I take up(except PHP), just one name and that’s all. It will change my life and this is really important to me;) -
i have created school record system but when i m creating button for delete it is showing error
****views.py file from django.shortcuts import render from django.urls import reverse_lazy from django.http import HttpResponse from django.views.generic import (View,TemplateView, ListView,DetailView, CreateView,DeleteView, UpdateView) from . import models # Create your views here. # Original Function View: # # def index(request): # return render(request,'index.html') # # # Pretty simple right? class IndexView(TemplateView): # Just set this Class Object Attribute to the template page. # template_name = 'app_name/site.html' template_name = 'index.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['injectme'] = "Basic Injection!" return context class SchoolListView(ListView): # If you don't pass in this attribute, # Django will auto create a context name # for you with object_list! # Default would be 'school_list' # Example of making your own: # context_object_name = 'schools' model = models.School class SchoolDetailView(DetailView): context_object_name = 'school_details' model = models.School template_name = 'basic_app/school_detail.html' class SchoolCreateView(CreateView): fields = ("name","principal","location") model = models.School class SchoolUpdateView(UpdateView): fields = ("name","principal") model = models.School class SchoolDeleteView(DeleteView): model = models.School success_url = reverse_lazy("basic_app:list") def delete(pk): class CBView(View): def get(self,request): return HttpResponse('Class Based Views are Cool!') models.py from django.db import models from django.urls import reverse class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse("basic_app:detail",kwargs={'pk':self.pk}) class Student(models.Model): name = models.CharField(max_length=256) age … -
Should sign in with Microsoft be done on frontend or backend?
I plan to write a Django REST backend and React SPA frontend. I want to authenticate exclusively with Microsoft. I setup the application in azure active directory. Do I want use the frontend or backend to authenticate? Do I want to use react-microsoft-login or django_microsoft_auth? -
Django: How to read question mark (?) in the django URL
I am developing a Django app that stores the user input in the database. Now the problem is that when the user writes the ? in the input field, Django treats it as the part of querystring so it doesn't save it. I am using the following JavaScript code: $("#submit").on("click",function(){ text = $("#input").val(); $.get('/add/'+text); } And here is my urls.py file: urlpatterns = [ path('add/<str:text>',views.add, name='add'), .............. ] And in views.py, I have: def add(request,text): field = Text(text=text) field.save() return HttpResponse('') -
pagination of a specific context in multiple context in ListView not working in django?
in django, i am trying to list some queries of several objects like user lists, categoies and Post list. the homepage will be contained couple of blocks or boxes. each box will have different query list like Post list, User List, category list. But only one context will have pagination and other won't and ofcourse the pagination will be working on Post list. here is the views.py: class BlogappListView(ListView): model = Category,CustomUser template_name = 'home.html' context_object_name='category_list' queryset=Category.objects.all() paginate_by = 2 def get_context_data(self, **kwargs): context = super(BlogappListView, self).get_context_data(**kwargs) context['user_list']= CustomUser.objects.all() context['post_list']=Post.objects.all() activities=context['post_list'] return context def get_related_activities(self,activities): queryset=self.objects.activity_rel.all() paginator=Paginator(queryset,2) page=self.request.GET.get('page') activities=paginator.get_page(page) return(activities) in urls.py: urlpatterns = [ path('',BlogappListView.as_view(),name='home'), ] in base.html, the paginate portion code: <ul class="pagination justify-content-center mb-4"> {% if is_paginated %} {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">First</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a> </li> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <li class="page-item"> <a class="page-link" href="?page={{ num }}">{{ num }}</a> </li> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <li class="page-item"> <a class="page-link" href="?page={{ num }}">{{ num }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.next_page_number … -
How return image url and prepopulate a form at the same time? Error in image url inside the template
I am having a problem to prepopulate a form and also return the image url of the account: My view: class DadosProfissionaisViewUpdate(LoginRequiredMixin, FormView): template_name = 'accounts/udadosprofissionais.html' form_class = DadosProfissionaisForm model = DadosProfissionais def get_initial(self): obj = DadosProfissionais.objects.get(user = self.request.user) initial = super(DadosProfissionaisViewUpdate, self).get_initial() initial = model_to_dict(obj) return initial def form_valid(self, form): obj = DadosProfissionais.objects.get(user = self.request.user) obj.user = self.request.user obj.nome_publico = form.cleaned_data['nome_publico'] obj.nome_consult = form.cleaned_data['nome_consult'] obj.cep_atend = form.cleaned_data['cep_atend'] obj.endereco_atend = form.cleaned_data['endereco_atend'] obj.bairro_atend = form.cleaned_data['bairro_atend'] obj.save() messages.success(self.request, _('Seus dados foram atualizados com sucesso.')) return redirect('home') My template: {% block content %} <div class="text-center"> <img src="{{ profile_pic.url }}" class="rounded" alt="img"> </div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-primary">Enviar</button> </form> {% endblock %} My urls - added MEDIA_URL: urlpatterns = [ path('admin/', admin.site.urls), ........ path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), path('accounts/', include('accounts.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My form: class DadosProfissionaisForm(forms.ModelForm): nome_publico = forms.CharField(label='Nome Público') nome_consult = forms.CharField(label='Nome do Consultório') cep_atend = forms.CharField(label='CEP') endereco_atend = forms.CharField(label='Rua') bairro_atend = forms.CharField(label='Bairro') profile_pic = forms.ImageField(label='Foto') class Meta: model = DadosProfissionais fields = ['nome_publico', 'nome_consult', 'cep_atend', 'endereco_satend', 'bairro_atend', 'profile_pic'] I do not know how the correct way to prepolute the form and also load this image profile url in this template. … -
Connecting Django and Postgres: FATAL authentication error
I'm trying to use PostgreSQL in my Django project. When I run sudo su - postgres I received the following output: (venv) jacquelinewong@Jacquelines-MBP spiderdjango % sudo su - postgres Password: /etc/zshrc:source:76: no such file or directory: /Library/PostgreSQL/12/.bash_profile postgres@Jacquelines-MBP ~ % psql Password for user postgres: psql (12.3) Type "help" for help. I'm on Mac. So it seems the psqlshell does work, but there's an issue with .bash_profile. And when I exit the shell and type in python manage.py makemirgations, here's what I got (venv) jacquelinewong@Jacquelines-MBP spiderdjango % python manage.py makemigrations Traceback (most recent call last): File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "spiders" The above exception was the direct cause of the following exception: 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 "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute …