Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Favorite view
Estou tentando criar um botão favoritar os posts de um aplicativo, mas não consigo descobrir como criar um porque ele contém um número inteiro. Quando o usuário clica no botão favoritar. O botão aumentará em 1 e será exibido perto da imagem. Este é o meu model do Post. class Post(models.Model): title = models.CharField(max_length=100) slug = AutoSlugField(unique=True, always_update=False, populate_from="title") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=1050) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) image = models.ImageField(null=True, blank=True, upload_to=upload_perfil_user) category = models.ForeignKey( Category, related_name="posts", on_delete=models.CASCADE, null=True ) class Meta: ordering = ("-created",) def __str__(self): return self.title def get_absolute_url(self): return reverse("blog:detail", kwargs={"slug": self.slug}) def comment_number(self): return len(self.comment_set.all()) E esse é o modelo do Favorite : class Favorite(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) Mas estou tendo extrema dificuldade em criar a view do sistema : class Favorite(CreateView): model = Favorite def form_valid(self): form.instance.author=request.user #id do usuario #id do post #se o usuario ja favoritou, então não faça nada #se o usuario não favoriou então suba a info pro banco (id_user, id_post) #retorne o mesmo url talvez... Não tive ideia pro retorno da função Alguém pode me ajudar a criar o básico de um botão favoritar ? Tenho o … -
django join two tables based on values
I have django models like this: class A(): attr_a class B(): attr_b attr_fa = models.ForeignKey(A, to_field='attr_a') class C(): attr_c attr_fa = models.ForeignKey(A, to_field='attr_a') Is it possible to join table B and C based on B.attr_b = C.attr_c and B.attr_fa = C.attr_fa? the raw sql would be select * from B, C where B.attr_b = C.attr_c and B.attr_fa = C.attr_fa is it possible to use Django queryset to achieve this? -
How to truncate Django Measurement object to 2 decimal points
I have a distance queryset annotation in Django. Its precision is overly exaggerated and unnecessary, I want to limit the precision to 2 or 3 decimal points. I have tried to format it with string formatting but didn't work. How can I truncate distance measurement objects in django to 2-3 decimal places? -
How toallow users to select multiple fields(which are objects of model A) and save it in another modelB.model A and B are ManytoMany related in django
This is my modelA class TrashCan(models.Model): DBlon = models.FloatField() DBlat = models.FloatField() DBlevel = models.PositiveIntegerField(blank=True, null=True) This is modelB class Route(models.Model): DBbins = models.ManyToManyField(TrashCan, blank=True, max_length=100) this is my template which displays the trashcans model <form method = "POST"> {% csrf_token %} <tbody id="myTable"> {% for can in cans %} <tr> <th scope="row"> {{ can.id }} </th> <td class="text-white bg-primary"><strong> {{ can.DBlevel }} </strong></td> <td> <input type="checkbox" class="" id="selected_bin"> </td> </tr> {% endfor %} <button type="submit" class="" name="bins">Create Route</button> </form> here is my attempted view def CreateRoute(request): cans = TrashCan.objects.all() if request.method == 'POST': if request.POST.get('bins'): selected_bins = Route() selected_bins.DBbins = request.POST.get('bins') selected_bins.save() return redirect('CreateRoute') context = { 'cans': cans, } return render(request, 'pages/CreateRoute.html', context) so i what i want is to permit the user to select the bins, then to save the selected bins in the model create route in a way that the bins can be processed (it should not be saved in a char field for most solutions i saw online proposes to store them in a char field seperating them with a ',' which sorts of limit how enough you an process it). in this way, i can now get the fill levels of the bins … -
How can I add another form in signup form django
this is my code: views.py class SignUpView(generic.CreateView): form_class = SignUpForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True, help_text='Required.') last_name = forms.CharField(max_length=30, required=True, help_text='Required.') email = forms.EmailField(max_length=254, required=True , help_text='Required.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) class ProfileForm(forms.ModelForm): location = forms.CharField(max_length=200, required=True, help_text='Required.') phone = forms.CharField(max_length=10, required=True, help_text='Required.') class Meta: model = Profile fields = ('location','phone') i don't know how to extend signupform with profileform, i want user to submit together since signup -
How do I set csrf token to form
I am running Django and React concurrently, each time I try to hit my login endpoint on Django it logs "Cookie not set" (403). I am also using django rest framework, I have tried using the decorator @method_decorator(csrf_exempt, name='dispatch') on the class but it doesn't work. Login.js const handleLogin = () => { const config = { headers: { 'X-CSRFToken': Cookies.get('csrftoken') }, }; const userCredentials = { email: email.toLowerCase(), password }; axios .post('/rest-auth/login/', userCredentials, config) .then(({ data: { user, token } }) => { Cookies.set(TOKEN_KEY, token); if (user.should_reset_pass) { history.push(`/reset-password/${user.id}`); return; } history.push('/'); }) .catch((error) => { //TODO: remove later! console.log(error); }); }; <div className="auth-card"> <div className="auth-logo-wrapper"> <img className="auth-logo" src={logo} /> </div> <h3>Welcome to NAPIMS</h3> <form className="auth-form"> <div className="auth-group"> <label htmlFor="email">USERNAME OR EMAIL</label> <input type="email" id="email" onChange={({ target: { value } }) => setEmail(value)} value={email} /> </div> <div className="auth-group"> <label htmlFor="password">Password</label> <input type="password" id="password" onChange={({ target: { value } }) => setPassword(value)} value={password} /> </div> </form> <button onClick={handleLogin}>Login</button> </div> views.py class AuthUser(APIView): .... def login(self, request): username = request.data.get('username', None) password = request.data.get('password', None) if self.simple_email_check(username) is not True: found_user = User.objects.filter(username=username) if len(found_user) > 0: username = found_user[0].email user = authenticate(username=username, password=password) if user is not None: if user.is_active: … -
Set ForeignKey in Django view.py
def clientinfo(request): clientForm = ClientInfoForm(prefix="client") criminalForm = OCCForm(prefix="criminal") if request.method == 'POST': clientForm = ClientInfoForm(request.POST,prefix="client") criminalForm = OCCForm(request.POST,prefix="criminal") criminalForm['cust_id_id'] = clientForm['id'] if clientForm.is_valid() or criminalForm.is_valid(): clientForm.save() criminalForm.save() print("SUCCESSFUL SUBMISSION") return render(request, 'submitted.html') return render(request, 'clientinfo.html', {'form': clientForm, 'occform': OCCForm}) My criminalForm has a ForeignKey field cust_id and i need to set it to the auto-generated Primary key of clientForm I can't figure out the correct way to do this? They both have an associated model ClientInfo and OCC if I need to use them somehow to accomplish this? -
Django referencing a specific object in a many-to-one relationship
Let's say I have the following models: from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, related_name="articles", on_delete=models.CASCADE) I'd like to add a favorite_article field to my Reporter model that will reference a specific Article from reporter.articles. How can I do this? -
Django HTTPS Elastic Beanstalk
I am having trouble routing HTTPS with my django app. I saw this following post: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/https-singleinstance-python.html I have set my listner on port 443 for HTTPS with a certificate that is validated, but when I go to ACM in AWS I cannot download the information to put in the block that looks like: /etc/pki/tls/certs/server.crt: mode: "000400" owner: root group: root content: | -----BEGIN CERTIFICATE----- certificate file contents -----END CERTIFICATE----- I am running into a similar issue with the RSA Private key in the block: /etc/pki/tls/certs/server.key: mode: "000400" owner: root group: root content: | -----BEGIN RSA PRIVATE KEY----- private key contents # See note below. -----END RSA PRIVATE KEY----- Has anyone else run into this before? -
Django on Heroku gives me error 500 when trying to log in
so as you may know by now, when I try to log in into my Django app deployed on Heroku with debug=False, it raises me an error 500. My settings.py important part (i guess) looks like this: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [''] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', #authentication 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'perfil', 'posts' ] Also guys, here is the log if this could help: 2021-04-15T16:26:03.149934+00:00 app[web.1]: 10.12.37.145 - - [15/Apr/2021:16:26:03 +0000] "GET /static/main.f95279ea3102.js HTTP/1.1" 200 0 "https://codelize-pap.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36" 2021-04-15T16:26:24.457519+00:00 app[web.1]: [2021-04-15 16:26:24 +0000] [10] [DEBUG] POST /accounts/login/ 2021-04-15T16:26:24.614106+00:00 app[web.1]: 10.10.193.143 - - [15/Apr/2021:16:26:24 +0000] "POST /accounts/login/ HTTP/1.1" 500 145 "https://codelize-pap.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36" 2021-04-15T16:26:24.614597+00:00 heroku[router]: at=info method=POST path="/accounts/login/" host=codelize-pap.herokuapp.com request_id=065b83c7-e345-4134-9962-9e0b9ea9fc1f fwd="94.62.138.241" dyno=web.1 connect=1ms service=158ms status=500 bytes=410 protocol=https 2021-04-15T16:26:31.512235+00:00 app[web.1]: [2021-04-15 16:26:31 +0000] [9] [DEBUG] GET / 2021-04-15T16:26:31.515625+00:00 app[web.1]: 10.35.168.144 - - [15/Apr/2021:16:26:31 +0000] "GET / HTTP/1.1" 200 3041 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36" 2021-04-15T16:26:31.517029+00:00 heroku[router]: at=info method=GET path="/" host=codelize-pap.herokuapp.com request_id=4d95ad03-83b5-40ce-ba98-8b73ed021e5a fwd="94.62.138.241" dyno=web.1 connect=1ms service=4ms status=200 … -
Web - Subscription
Sorry for the vague title, open to suggestions. I would like to add a subscription option to a small and ongoing media project. I'd like to set up for email. I have code to prepare and send updates, but I don't know of a safe way to collect the user's email address and transfer it to my server and keep it in the database. Could anybody point me towards some useful information on the subject? Thanks! I'm using vanilla javascript at the moment, but may switch to using django or flask soon. Responses don't need to be detailed. Just an overview/indication of a general standard procedure for this sort of thing. -
django serializer is_valid() return false but serializer error is empty
Model Class: class Movie(models.Model): movie_id = models.IntegerField(primary_key=True) movie_title = models.CharField(max_length=150) image_url = models.CharField(max_length=250, null=True) description = models.CharField(max_length=1000, null=True) class Meta: db_table = 'Movie' Serializer Class: class DisplayMovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('movie_id', 'movie_title') My view: if request.method == 'POST': movies = JSONParser().parse(request) movie_serializer = DisplayMovieSerializer(data=movies, many=True) try: if movie_serializer.is_valid(): movie_serializer.save() return JsonResponse(movie_serializer.data, status=status.HTTP_201_CREATED, safe=False) print("BAD") return JsonResponse(movie_serializer.errors, status=status.HTTP_400_BAD_REQUEST, safe=False) except Exception as e: return JsonResponse({'error': e.args[0]}, status=status.HTTP_400_BAD_REQUEST) The view method return BAD + , so serializer is invalid. Where did I go wrong? -
How to handle multiple search inputs in django
I have three different search inputs(by the text, by date and a checkbox) is it possible at all to Handle three post requests?E.g. I at first want to find a lesson by text search,then after I found it, I want to search the results by the date. Will something like that work or no? def my_view(request): if request.method == "POST": if request.POST['value_one']: # Do stuff here elif request.POST['value_two']: # Do stuff here elif request.POST['value_three']: # Do stuff here else: # Do something else -
djangos self.client.force_login doesn't work
I am using django 3.2 and self.client.force_login in test package doesn't log in. this is the setUp method: def setUp(self) -> None: self.user = User.objects.create_user( email='asdf@gmail.com', password='hiwa_asdf', name='smile as we go ahead' ) self.client.force_login(self.user) and here the test method: def test_update_uer_profile(self): """testing if update user profile works""" data = { 'name': 'Angry as hell', 'password': 'hi there john' } response = self.client.patch(me_url, data) print(response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) self.user.refresh_from_db() self.assertEqual(self.user.name, data['name']) self.assertTrue(self.user.check_password(data['password'])) -
Why does this block of code throws a syntax error?
def __str__(self): return f'{self.title}' The picture below shows the code. -
How to edit a formset
I have a formset which i want the user to be able to edit their answers. The formset is a quiz, which is separated in 5 parts. Each part takes a few questions related to that part. Every question answered in the formset is related to a quiz_id. I figured I'd be able to edit by requesting the answers related to that quiz_id. I'm really new to django and i can´t quite figure out how to get this edit function working. Here is some of the coding: The models: class Questionario(models.Model): nome_emp = models.CharField(max_length=100) num_func = models.CharField(max_length=4) setor = models.CharField(max_length=50) faturamento = models.CharField(max_length=20) nome_func = models.CharField(max_length=50) cargo = models.CharField(max_length=50) data = models.CharField(max_length=50) id_user = models.ForeignKey(User, on_delete=models.CASCADE) class Pergunta(models.Model): question=models.CharField(max_length=200) tema=models.ForeignKey(Tema, on_delete=models.CASCADE) is_active=models.BooleanField(default=True) class Resposta(models.Model): RESPOSTAS=( (1,'Discordo totalmente'), (2,'Discordo'), (3,'Nem discordo nem concordo'), (4,'Concocordo'), (5,'Concordo totalmente') ) id_questionario=models.ForeignKey(Questionario, on_delete=models.CASCADE) id_pergunta=models.ForeignKey(Pergunta, on_delete=models.CASCADE) resposta=models.IntegerField(choices=RESPOSTAS,default=0) Here is the view function for 1 of the 5 parts of the quiz. The other 4 parts are copies of this one: def quest_perg1(request,quest_id): questionario= Questionario.objects.get(pk=quest_id) perguntas= Pergunta.objects.all() numperg = Pergunta.objects.filter(tema=1).count() perg = Pergunta.objects.filter(tema=1) register = template.Library() @register.filter def list_item(lst, i): try: return lst[i] except: return None RespostaFormset = modelformset_factory(Resposta,form=RespostaForm, extra=numperg) if request.method == 'POST': formset = RespostaFormset(request.POST, … -
Make Django to compile modules out of regular Django project modules
I have a Django project and I want to encapsulate some items, so I created a python file inside a Django application directory: The problem is that Django engine is not compiling this file, so syntax errors are not reported. Django is basically ignoring the file and do not react to changes in it, like it reacts to changes in models.py, that causes Django engine to restart. What do I need to do for Django to consider this file? -
how to get query from Django three class models
I have created 3 class models. I created a School class model in School App, a Studnet class model in Attribute App, and an Attribute class model. And I created a table to list all Schools (School.objects.all()) I want to output the number of students by school that satisfies each condition by applying conditions to the Attribute class model. I know why {{ school.condition }} is not displayed. This is because from_date and to_date cannot be loaded using request in models.py. Please let me know if there is a way. I'm sad that I haven't been able to solve it for several days. [School App - models.py] class School(models.Model): name = models.charField() principal = models.charField() count_student = models.IntegerField() def condition(self, request): from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') student= Student.objects.filter(school_id=self.id) return Attribute.objects.filter( entrance_date__range=[from_date, to_date], student_id__in=student).values('entry_date').distinct().count() [School App - views.py] def school_list(request): school_list = School.objects.all() return render(request, 'school_list.html', {'school_list': school_list} [Attribute App - models.py] class Student(models.Model): name = models.charField() grade = models.charField() sex = models.charField() school = models.ForeignKey(School, on_delete=models.CASCADE) class Attribute(models.Model): hair = models.charField() entrance_date = models.DateField() student= models.ForeignKey(Student, on_delete=models.CASCADE) <Table I want to display on the template> <tr> {% for school in school_list %} <td>{{ school.name }}</td> <td>{{ school.condition }}</td> ---------- … -
Having trouble grouping with django query
I have this query, but it returns individual results for each Fruit. How do I get grouped results? Fruit.objects.\ annotate(quantity=Count('fruit_box')).\ annotate(remaining=Count('pk', filter=~Q(fruit_status='eaten'))).\ annotate(eaten=Subquery(ShipmentContent.objects.filter( object_id=OuterRef('pk'),\ fruits__fruit_box=OuterRef('fruit_box'),\ shipment=self.request.query_params.get('shipment_id'),\ fruits__fruit_status='eaten',\ content_type=fruit_content_type).\ values('object_id').\ annotate(count=Count('object_id')).\ values('count')\ )\ ).\ annotate(location=F('fruit_box__location__description')).\ values('fruit_box__label', 'fruit_box', 'harvest_date', 'seeded').\ order_by('fruit_box__label') -
Flutter chat app with django channels backend keeps reloading
I am using flutter chat app and using Django Rest Framework + channels as the backend. In the chat page, I am using the following code to display messages - Scaffold( backgroundColor: backColor, appBar: AppBar(), body: GestureDetector( onTap: () => FocusScope.of(context).unfocus(), child: StreamBuilder( stream: channel.stream, builder: (context, snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>( Theme.of(context).primaryColor, ), ), ); }else{ var mymessages = jsonDecode(snapshot.data); if(mymessages['command']=='messages'){ // setState(() { messages = ChatMessagesList.fromJson(mymessages["messages"]).messages; // }); }else{ ChatMessage msg = ChatMessage.fromJson(mymessages["message"]); if(!messages.contains(msg)) // setState(() { messages.add(msg); // }); } return Column( children: <Widget>[ Expanded( child: Container( decoration: BoxDecoration( color: backColor, borderRadius: BorderRadius.only( topLeft: Radius.circular(30.0), topRight: Radius.circular(30.0), ), ), child: ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(30.0), topRight: Radius.circular(30.0), ), child: ListView.builder( reverse: true, padding: EdgeInsets.only(top: 15.0), itemCount: messages.length, itemBuilder: ( context, index) { final ChatMessage message = messages[index]; final bool isMe = message.sender.username == linUser.username; return _buildMessage(message, isMe); }, ), ), ), ), _buildMessageComposer(), ], ); } } ) , ), ) Here channel is IOWebSocketChannel that connect to django websocket url, and it is closed in dispose(). messages is a List<ChatMessage> declared outside build. Depending on what is sent via channel.sink either list of ChatMessage is received or just a single, … -
DRF serialize post request with foreign key
My problem is that when trying to run is_valid() on a big chunk of data in a POST-request, where the model has a foreign key, it will fetch the foreign key table for each incoming item it needs to validate. This thread describes this as well but ended up finding no answer: Django REST Framework Serialization POST is slow This is what the debug toolbar shows: My question is therefore, is there any way to run some kind of select_related on the validation? I've tried turning off validation but the toolbar still tells me that queries are being made. These are my models: class ActiveApartment(models.Model): adress = models.CharField(default="", max_length=2000, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) class Company(models.Model): name = models.CharField(blank=True, null=True, max_length=150) These are my serializers: I have tried not using the explicit PrimaryKeyRelatedField as well class ActiveApartmentSerializer(serializers.ModelSerializer): company = serializers.PrimaryKeyRelatedField(queryset=Company.objects.all()) class Meta: model = ActiveApartment list_serializer_class = ActiveApartmentListSerializer fields = '__all__' extra_kwargs = { 'company': {'validators': []}, } class ActiveApartmentListSerializer(serializers.ListSerializer): def create(self, validated_data): data = [ActiveApartment(**item) for item in validated_data] # Ignore conflcits is the only "original" part of this create method return ActiveApartment.objects.bulk_create(data, ignore_conflicts=True) def update(self, instance, validated_data): pass This is my view: def post(self, request, format=None): # Example … -
How to see full Heroku stacktrace in logs?
When i deploy my django app to Heroku, in the console (heroku logs --tail -a george-paintings) i see an error 2021-04-15T15:14:42.109272+00:00 app[web.1]: Error: No application module specified. 2021-04-15T15:14:42.161597+00:00 heroku[web.1]: Process exited with status 1 2021-04-15T15:14:42.290903+00:00 heroku[web.1]: State changed from starting to crashed But i can't figure out what particular went wrong. My Procfile looks like this web: gunicorn --pythonpath application.george_paintings.george_paintings.wsgi --log-file - --log-level debug Where can i find more info about my error ? -
Django: how to get the related set of a related set of an object
Let's say I have the following three interconnected models setup: class Organisation(): .... class Job(): organisation = models.ForeignKey('Organisation', null=True, blank=True, related_name="jobs", on_delete=models.CASCADE) class Candidate(): job = models.ForeignKey('Job', related_name='candidates', on_delete=models.CASCADE) That is, each Organisation has many jobs, and in turn each Job has many candidates. From this, I know how to get all ofthe jobs (the "job set") related to an organisation with organisation.jobs.all(). Q. So putting all of this together - how could I get all of the candidates related to an Organisation? My mind is just drawing a blank...and I can't seem to find any use cases online ... would anyone know the ORM shorthand for such a chained relationship? -
Trigger Notifications on log in, django
Hi Guys I am working on a django project, I have my notifications Model : class Notification(models.Model): site = models.ForeignKey(Site, on_delete=models.CASCADE) kpi = models.CharField(max_length=20, blank=True) value = models.IntegerField(blank=True, null=True) site_name = models.CharField(max_length=20, blank=True) for the moment I have it set up in the action of adding KPIs and it works fine, I would like to change it that it checks for kpi values in my database table : SiteKPIS : class SiteKPIs(models.Model): site = models.ForeignKey(Site, on_delete=models.CASCADE) date = models.CharField(max_length=200, blank=True) staff = models.IntegerField(blank=True, null=True) dl = models.IntegerField(blank=True, null=True) idl = models.IntegerField(blank=True, null=True) total_hc = models.IntegerField(blank=True, null=True) total_in = models.IntegerField(blank=True, null=True) total_out = models.IntegerField(blank=True, null=True) staff_rate = models.IntegerField(blank=True, null=True) dl_rate = models.IntegerField(blank=True, null=True) idl_rate = models.IntegerField(blank=True, null=True) turn_over = models.FloatField(blank=True, null=True) And for example if there is a site that has turn_over<1 it adds a notification. Can someone guide me through that ? much appreciated -
Relation not exists Heroku, Django Project
In my django Project I configured my Database in the settings as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myname', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'database_url', 'PORT': '3306', } } The database details that i have entered is a hosted MySQL database on clever-cloud.com, and it's working perfectly fine on my local. I can run raw sql queries, using: with connection.cursor() as cursor: query = "select * from anyTable" cursor.execute(query) But after deploying this project on heroku, it always throws an error at this cursor.execute line. error: relation "anyTable" does not exist LINE 3: select * from anyTable Everything works perfectly on local, so it seems heroku has not configured my database details as the original db for the project.