Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use django post_save signal
I have two models, client and contact model with foreign key relation, I using Django signals to create contact while the creation of the client, but I getting an error from the database : ( 1048, "Column 'client_id' cannot be null") when I check the database I found the contact and the client rows, so how to get rid of this error? models.py class Client_Data(models.Model): RC = models.CharField(max_length=50) Raison_social = models.CharField(max_length=254) NIF = models.CharField(max_length=50,unique=True) AI = models.CharField(max_length=50,unique=True) NIS = models.CharField(max_length=50,unique=True) Banque = models.CharField(max_length=50,unique=True) CB = models.CharField(max_length=50) adresse = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) active = models.BooleanField(default=True) class Contact(models.Model): client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE) Nom = models.CharField(max_length=50) post = models.CharField(max_length=50) Tel = models.CharField(max_length=50) email = models.EmailField(max_length=255,unique=True) contact_type = models.CharField(default='Client_contact',max_length=50) @receiver(post_save, sender=Client_Data) def create_contact(sender, **kwargs): if kwargs['created']: conatact = Contact.objects.create(client=kwargs['instance']) post_save.connect(create_contact, sender=Client_Data) views.py def save_client_form(request, form,Contact_form, template_name): data = dict() if request.method == 'POST': if form.is_valid() and Contact_form.is_valid(): form.save() Contact_form.save() data['form_is_valid'] = True books = Client_Data.objects.all() data['html_book_list'] = render_to_string('Client_Section/partial_client_c.html', { 'client': books }) else: print(form.errors) print(Contact_form.errors) data['form_is_valid'] = False context = {'form': form,'contact_form':Contact_form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def client_create(request): if request.method == 'POST': form = ClientForm(request.POST) contact_form = Contact_Form(request.POST) else: form = ClientForm() contact_form = Contact_Form() return save_client_form(request, form,contact_form, 'Client_Section/partial_client.html') forms.py … -
Pass a single database entry from django to html template
Good Evening, hope you all are healthy during this critical times! I want to use the time to again work on my django web app. This time in addition to showing all my customers on the page I want to return the information for a single customer, that I selected on the website. I get the information about all the customers in the databse to show up on the website and when I use print in my views.py I see all the information from the single object. However, it will not show up in my template :( Here is my code (first the model): class PrivateCustomer (models.Model): WEIBLICH = 'W' MANNLICH = 'M' DIVERS = 'D' KEINEANGABE = 'K' GENDER =( (WEIBLICH, 'Weiblich'), (MANNLICH, 'Maennlich'), (DIVERS, 'Divers'), (KEINEANGABE, 'Keine Angabe') ) kundennummer = models.CharField(max_length=5, null=False, primary_key=True) vorname = models.CharField(max_length=30, null=False) nachname = models.CharField(max_length=30, null=False) adresse = models.CharField(max_length=50, null=False) postleitzahl = models.CharField(max_length=5, null=False) stadt = models.CharField(max_length=30, null=False) geschlecht = models.CharField(max_length=3, null=False, choices=GENDER) geburtstag = models.DateField(null=True) telefon = models.CharField(max_length=30, null=True) mobil = models.CharField(max_length=30, null=True) email = models.CharField(max_length=80, null=True) datum = models.DateField(null=False) # def __str__(self): # return self.nachname Then the function in the views.py: def showCustomer(request): if request.method == 'POST': kd = request.POST['kundennummer'] … -
Do a default save rather than override
I have a model that looks like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=160, null=True) avatar = models.ImageField(storage=OverwriteStorage(), upload_to=create_user_image_path, validators=[validate_avatar], default="default/avatars/default.jpg") The model also has its default save method overridden to do some logic for the image that's uploaded. However, let's say the user signed up and has no image, so the default image is used instead. So when this happens Profile(user=22).save() I don't want to use the overridden save method because we are using the default image instead, so there's no extra logic needed. Is there a way I can save it normally in the database instead of it going through the overridden save method? -
'function' object has no attribute '_meta'
Internal Server Error: /credito/nuevo_solicitud/ Traceback (most recent call last): File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/shigab/apps/credito/views.py", line 56, in post return self.render_to_response(self.get_context_data(form1=form1, form2=form2)) # miercdero File "/Users/haroldtg/Documents/Desarrollo/shigab/shigab/apps/credito/views.py", line 23, in get_context_data contexto = super(Crear_solicitud_view, self).get_context_data(**kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/views/generic/edit.py", line 66, in get_context_data kwargs['form'] = self.get_form() File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/views/generic/edit.py", line 33, in get_form return form_class(**self.get_form_kwargs()) File "/Users/haroldtg/Documents/Desarrollo/shigab/shigab/apps/credito/forms.py", line 37, in init super().init(*args, **kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/forms/models.py", line 292, in init object_data = model_to_dict(instance, opts.fields, opts.exclude) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/forms/models.py", line 82, in model_to_dict opts = instance._meta AttributeError: 'function' object has no attribute '_meta' [02/Apr/2020 17:55:54] "POST /credito/nuevo_solicitud/ HTTP/1.1" 500 109540 -
Django ListView
It's my first time to use ListView and it doesn't work and give me error. I put get_query but they still give me same error. How can I fix the problem? And everytime when I write code in views.py I always used 'def' not 'class'. But could see many people use (and also django documents) 'class' for ListView. So for general render stuffs we use 'def' and for django.views.generic stuffs we use class right? Why they distinguished these two? This is error what I got. ImproperlyConfigured at /search/results ListView is missing a QuerySet. Define ListView.model, ListView.queryset, or override ListView.get_queryset(). urls.py from django.urls import path from django.conf import settings from django.views.generic import ListView, TemplateView from . import views app_name = 'search' urlpatterns = [ path('', TemplateView.as_view(template_name = "search/index.html")), path('results', ListView.as_view(template_name = 'search/results.html')), path('beerlist', views.beerlist, name='beerlist'), path('<int:beerinfo_id>', views.beerinfo, name='beerinfo'), ] views.py from django.shortcuts import render, get_object_or_404, redirect from django.db.models import Q from django.views.generic import ListView, TemplateView from .models import Beerinfo # Create your views here. def index(TemplateView): template_name = 'search/index.html' def results(ListView): model = Beerinfo template_name = 'search/results.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Beerinfo.objects.filter( Q(name__icontains = query) | Q(label__icontains = query) ) return obejct_list index.html <form action="{% url 'search:results' %}" … -
How to solve, dest virtualenv: error: the following arguments are required: dest error?
As the title says, I keep on having that error and I don't know how to solve it. The Error, as the title says is virtualenv: error: the following arguments are required: dest the command which I entered was virtualenv I am running this on MAC and on python -
How to properly configure Celery logging functionality with Django?
I use Django and Celery to schedule a task but I have an issue with the logger because it doesn't propagate properly. As you can see in the code below I have configured the Python logging module and the get_task_logger Celery module. import logging from celery import Celery from celery.utils.log import get_task_logger # Configure logging logging.basicConfig(filename='example.log',level=logging.DEBUG) # Create Celery application and Celery logger app = Celery('capital') logger = get_task_logger(__name__) @app.task() def candle_updated(d, f): logging.warning('This is a log') logger.info('This is another log') return d+f I use django-celery-beat extension to setup periodic task from the Django admin. This module stores the schedule in the Django database, and presents a convenient admin interface to manage periodic tasks at runtime. As recommended in the documentation I start the worker and the scheduler that way: $ celery -A capital beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler celery beat v4.4.0 (cliffs) is starting. __ - ... __ - _ LocalTime -> 2020-04-02 22:33:32 Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> django_celery_beat.schedulers.DatabaseScheduler . logfile -> [stderr]@%INFO . maxinterval -> 5.00 seconds (5s) [2020-04-02 22:33:32,630: INFO/MainProcess] beat: Starting... [2020-04-02 22:33:32,631: INFO/MainProcess] Writing entries... [2020-04-02 22:33:32,710: INFO/MainProcess] Scheduler: Sending due task Candles update (marketsdata.tasks.candle_updated) [2020-04-02 … -
Graphene says field name is invalid keyword
I'm using ModelFormMutation and Graphene says a field keyword is not valid, when itself is looking for those fields. I delete the field and error changed to another field 😬. -
DRF How to restrict (permissions) user by companies?
I mean User have a company and restrict views by companies. If user in company A he can't look on same view on company B. Any help with this? thx class Company(models.Model): name = models.CharField(max_length=255) class User(AbstractBaseUser): first_name = models.CharField(max_length=254) last_name = models.CharField(max_length=254) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) -
Django model method returning correct response when called from shell but not when called from template
models.py class player(models.Model): name = models.CharField(max_length = 100) rounds_played = models.IntegerField() rounds_missed = models.IntegerField() date_joined = models.DateTimeField(default = timezone.now) total_points = models.IntegerField() bio = models.TextField() user_ID = models.CharField(max_length = 10) user_m = models.ForeignKey(User, on_delete=models.CASCADE) is_active = models.BooleanField(), def rounds_record(self): return int(100 * self.rounds_played / (self.rounds_played + self.rounds_missed)) def player_status(self): if self.is_active: return "Yes" return "No" def average_points(self): return int(self.total_points / self.rounds_played) def __str__(self): return self.name template snippet {% for player in players %} <div class = "grid-item"> {{player.player_status}} </div> {% endfor %} I'm developing a database web app (to learn django) in which players on a team and their statistics are tracked and stored in a psql database. When calling the player_status method from the manage.py shell it returns the correct response, say, for each user, 'yes', 'no'. However when the method is called from the template the method is returning 'yes', 'yes'. After some troubleshooting I found that it indeed is returning true for each response. What can I do to fix this problem. EDIT: I should specify I currently have 2 test users, one storing True and the other storing False in the is_active BooleanField -
NameError: name 'ProductTag' is not defined
models.py from django.db import models from django.contrib.auth.models import User class ActiveManager(models.Model): def active(self): return self.filter(active=True) class Product(models.Model): name = models.CharField(max_length=32) description = models.TextField(blank=True) price = models.DecimalField(max_digits = 5, decimal_places = 2) slug = models.SlugField(max_length=48) active = models.BooleanField(default=True) in_stock = models.BooleanField(default=True) date_updated = models.DateTimeField(auto_now=True) objects = ActiveManager() tags = models.ManyToManyField(ProductTag, blank=True) def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE) image = models.ImageField(upload_to="product-images") thumbnail = models.ImageField( upload_to="product-thumbnails", null=True) class ProductTag(models.Model): name = models.CharField(max_length=40) slug = models.SlugField(max_length=48) description = models.TextField(blank=True) active = models.BooleanField(default=True) def __str__(self): return self.name def natural_key(self): return(self.slug,) The name error says ProductTag is not defined, whereas ProductTag itself a Class. I don't understand where I missed... appreciate for the help -
Getting info from django-debug-toolbar when using manage.py run_method?
Is there a way to get the information that django-debug-toolbar collects/compiles, namely the sql queries and their times, when running code via manage.py run_method? I can construct an artificial view around the code I am running, but it sure would be nice to just run my code directly. I swear I saw a SO question describing how to do this recently, but either I was mistaken or I'm unable to find it now. -
Register two models with one form
I'm looking for the best way to register two related models with one django form or model form. e.g. User and Profile models. An user has onetoone Profile. Actually django CreateView allows select the user from menu, I wanna register in one operation both. I also tried inheritance, from two model forms, but django only takes fields from first modelform. Any idea? -
Website Template and Admin panel template, work synchranously in different two apps, in one project in Django problem
I want to make process in front end and admin panel together as two apps in a project. I can easily get website content. But I cannot get admin panels interface. I get 404 error. I put static folder in main project files and set it up in main settings.py. Here is the main urls.py configuration: path('', include('home.urls')), path( 'panel/', include( 'panel.urls')), path( 'admin/', admin.site.urls ), This is panel app's url.py panel urls.py’a from .views import Panel urlpatterns = [ path(‘panel’, Panel, name=‘Panel’), ] [enter image description here][1] Identification of Static folder's in settings.py STATIC_URL = ‘/static/’ STATIC_ROOT = os.path.join(BASE_DIR, ‘static’) MEDIA_URL = ‘/img/’ MEDIA_ROOT = os.path.join(BASE_DIR,‘img/’) STATIC_DIRS = [os.path.join(BASE_DIR, “static”),] Could you please help me for solving this problem. Thanks in advance! -
How to create a dropdown navbar which is automatically updated (Django)
Hey guys how are you doing? I'm creating my portfolio and I'd like to do it using Django and now i need some help. I'm trying to create a navbar with a dropdown list that contains my projects and it is automatically update when I publish a new project. Now my project_list page already do this, and when I'm on it the navbar works as I want, but when I'm in another page it doesnt show any project. This is my model: from django.db import models from django.urls import reverse from django.contrib.auth import get_user_model from django.utils import timezone from django.contrib.auth.models import User class Publish(models.Model): user = models.ForeignKey(User,null=True, on_delete=models.CASCADE ) author = models.CharField(max_length=256, null= True) name = models.CharField(max_length=256, null = True) description = models.TextField() create_date = models.DateTimeField(default=timezone.now) def published(self): self.create_date = timezone.now() self.save() This is my views.py from django.shortcuts import render,redirect, get_object_or_404 from django.views.generic import ListView, DeleteView, CreateView, TemplateView, UpdateView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import PublishCreateForm from publish.models import Publish from django.urls import reverse, reverse_lazy from django.views.generic.detail import SingleObjectMixin from django.utils import timezone class NavItems(object): def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context.update({ 'nav_items' : Publish.objects.all(),}) return context class ResumeView(TemplateView,NavItems): template_name = 'publish/resume.html' class PublishListView(ListView): model = Publish def get_queryset(self): … -
pip can't find django 3.x
whe I run: pip install django==3.05 I get Could not find a version that satisfies the requirement django==3.05 (from versions: 1.1.3, ... 2.2.11, 2.2.12) I need to update some references somewhere, but I am not sure how. Plz Help. -
django id foreagin key
I have client model and contact model with foreign key relation, i want to know to can I create the client and hist contact in the same time, I mean that how to get the client id which is the foreign key in client model while the creating of the client?? should I use Django signals or there is another way of doing this ?? models.py class Client_Data(models.Model): RC = models.CharField(max_length=50) Raison_social = models.CharField(max_length=254) NIF = models.CharField(max_length=50,unique=True) AI = models.CharField(max_length=50,unique=True) NIS = models.CharField(max_length=50,unique=True) Banque = models.CharField(max_length=50,unique=True) CB = models.CharField(max_length=50) adresse = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) active = models.BooleanField(default=True) class Contact(models.Model): client = models.ForeignKey(Client_Data,on_delete=models.CASCADE) Nom = models.CharField(max_length=50) post = models.CharField(max_length=50) Tel = models.CharField(max_length=50) email = models.EmailField(max_length=255,unique=True) contact_type = models.CharField(default='Client_contact',max_length=50) views.py def save_client_form(request, form,Contact_form, template_name): data = dict() if request.method == 'POST': if form.is_valid() and Contact_form.is_valid(): form.save() contact = Contact_form.save(commit=False) # contact.id = Contact_form.save() data['form_is_valid'] = True books = Client_Data.objects.all() data['html_book_list'] = render_to_string('Client_Section/partial_client_c.html', { 'client': books }) else: print(form.errors) print(Contact_form.errors) data['form_is_valid'] = False context = {'form': form,'contact_form':Contact_form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def client_create(request): if request.method == 'POST': form = ClientForm(request.POST) contact_form = Contact_Form(request.POST) else: form = ClientForm() contact_form = Contact_Form() return save_client_form(request, form,contact_form, 'Client_Section/partial_client.html') forms.py class ClientForm(forms.ModelForm): class … -
Chart does not display on webpage in Django app (with Chart.js)
I am new to web development and I struggling with the frontend side of a django project. I have a dashboard template that I got from bootstrap and I want to integrate a chart that I made with chart.js. The charts works fine in another project but I cannot get it to display anything when it's a part of a dashboard. I attached my index.html as well as my plot.html and a sample of the data that I am trying to plot and the error I get in Chrome console <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>SB Admin 2 - Dashboard</title> <!-- Custom fonts for this template--> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i' %}" rel="stylesheet"> <!-- Custom styles for this template--> <link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <!-- Sidebar --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-laugh-wink"></i> </div> <div class="sidebar-brand-text mx-3"> Inventory Management <sup></sup></div> </a> <!-- Divider --> <hr class="sidebar-divider … -
django - models.ForiegnKey to the same model, to self
Peace be upon you! Currently, I'm working on my first django project, of course as all django developers, I have stumbled upon so many bugs, my current problem is that I want to set up comments system (DB, front-end, back-end), I have searched for a solution for this but no answer is found. this is my models: from django.db import models from datetime import datetime from django.contrib.auth.models import User class Comment(models.Model): # if I am a reply, so "comment" my parent comment, so each comment will have replies_set comment = models.ForeignKey('self', on_delete=models.CASCADE, default = '', related_name='replies') user = models.ForeignKey(User, on_delete=models.CASCADE, default='') value = models.CharField(max_length=100, default='') date = models.DateField(default = datetime.now()) def __str__(self): return self.value class Reaction(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, default = '') # the user that this love belong to user = models.ForeignKey(User, on_delete=models.CASCADE, default='') # type: like:0, love:1, laugh:2, cry:3, angry:4, ... TYPES = [ (0, 'like'), (1, 'love'), (2, 'laugh'), (3, 'cry'), (4, 'angry'), ] reaction_type = models.IntegerField(choices=TYPES, default=0) def __str__(self): return self.types[self.reaction_type][1] I want to make something similar to twitter comments, to reply forever not a thing such that in StackOverflow, to have a root post or question and comments with a reply for a user … -
Django Translation Internationalization and localization: forms, models, tables
I have two questions. How can I translate in forms: a) labels b) Form ValidationErrors ? forms.py from django import forms from django.db.models import Max, Min from .models import Application, FlowRate, WaterFilterSubType, Fineness, Dirt from .models import DirtProperties, Flange class InputDataWaterForm(forms.Form): '''Application''' choices = list(Application.objects.values_list('id','application')) application = forms.ChoiceField(choices = choices, initial="1", label="Specify application:") .... def clean(self): cleaned_data = super(InputDataWaterForm, self).clean() application = cleaned_data.get('application') ... '''OTHER CONDITIONS if not flowrate ...''' if not (flowrate or pressure or dirt or dirtproperties or application or fineness or temperature or flange or atex or aufstellung or ventil): raise forms.ValidationError('PLEASE ENTER THE REQUIRED INFO') How can I translate content of a table in a database? All records eg. product names in a table must be translated. models.py from django.db import models '''FILTER PROPERTIES LIKE COLOR''' class FP_sealing(models.Model): value = models.CharField('Material Sealing', max_length=10) descr = models.CharField('Description', max_length=200, default="") def __str__(self): return("Seal: " + self.value) Thank you -
Monkey Patch Django Components
Suppose we have a django component django.views.generic.base.ContextMixin I Want to replace it with my own ContextMixin without changing any imports. How to that in django ? I have tried it many ways, reassigning the class in manage.py, in project init, etc. Has anyone done it? In django where is proper place to do system wide patching? -
Template Language for Django which does not silently fail on exception?
I like django, the ORM, the admin, the community. But I don't like the handling of exception in the template language, like documented here: invalid template variables. Is there an alternative template variable where I always get an exception if something is wrong (even in production)? I prefer exceptions to "silently ignore errors". -
How can i use django groups for specific model?
does any body can help me to use Django groups for a specific model ? for example for blog app,in Entry model, can i add a field like this to have groups like sport,news and etc ? group = models.ForeignKey(groups,on_delete=models.CASCADE) (something like this) -
(.SVG, .PNG) not loading in react component
I am trying to load SVG and PNG images in my react app. I am running a back end server on Django. I always get this error when I try to load any Image. "GET /b5cde312e6d66e389b1ca2ccfc013da0.png HTTP/1.1" 404 2195 webpack.config.js { test: /\.(jpg|png|svg)$/, loader: 'url-loader', options: { limit: 25000, }, }, { test: /\.(jpg|png|svg)$/, loader: 'file-loader', options: { name: '[path][name].[hash].[ext]', }, }, My component import React from 'react'; import '../App.css'; import Nav from '../components/Nav'; import Logo from '../logo512.png'; export default class Dev extends React.Component { render(){ return ( <div className="App"> <Nav /> <header className="App-header"> <div className="container"> <img src={Logo} alt="React Logo" /> </div> </header> </div> ) } } -
Why do I get a KeyError on a Model in Django?
I am getting a KeyError: 'conversation' on the line conv = ans.conversation in the code section: answers = Answers.objects.all() for ans in answers: conv = ans.conversation ... My model 'Answers' looks like this: class Answers(models.Model): conversation = models.ForeignKey(Conversation) ... I get the error sometimes, so if I run the code, I get the correct result a few times, but eventually within the for loop, sometimes the line conv = ans.conversation fails. Why do you think an error like this could ocurr? The entire error trace is here: Traceback (most recent call last): File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 164, in _get_ rel_obj = self.field.get_cached_value(instance) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'conversation' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/webapps/municipio/municipio/reportes/views.py", line 153, in get_whats_data conv = ans.conversation File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in _get_ rel_obj = self.get_object(instance) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 145, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 402, in get num = len(clone) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 256, in _len_ self._fetch_all() File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 55, in _iter_ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql cursor.execute(sql, params) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute …