Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
redirect to landing page How i can do that?
The problem is the logged in user who, after logging in, is on the main page of the application and after pressing the back button of the browser, I return to the login page, where the entire navbar is, there is a possibility that after clicking back the user will be redirected to the home page or checking some condition if the user is logged in, it is not possible to enter the login page -
How to return just the id number from queryset for a counter?
I'm really just a beginner in python and django... I'm looking for a way on how to get just the id of the last item in the queryset as a counter of posts for my project. I know about the ModelName.objects.last or .latest() however if I use last i still get the "Topic object (id)" I need just the id without the preceding text. Could anyone help me? -
Erro Python Django
Eu coloquei mais uma tabela no models dos usários, onde eu crio um modelo personalizado para um usuário. Eu criei uma tabela pra capturar algumas informações de onde ele. quando eu dou migrate ocorre o seguinte erro: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user' E todas as outras partes que eu uso a chave estrangeira apontando para o usuário ele dá esse problema -
Rename content_type and object_id in ContentTypeFramework
I want to create specific relation in my Django app. For doing this, I've chosen ContentTypeFramework and GenericForeignKey. In the django documentation there are not so much info about it. Here is it: There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. The usual name for this field is “content_type”. Give your model a field that can store primary key values from the models you’ll be relating to. For most models, this means a PositiveIntegerField. The usual name for this field is “object_id”. Give your model a GenericForeignKey, and pass it the names of the two fields described above. If these fields are named “content_type” and “object_id”, you can omit this – those are the default field names GenericForeignKey will look for. And it works great if I left fields with default names: content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.UUIDField(null=True, blank=True) item = GenericForeignKey('content_type', 'object_id') But if I change their names, for something more specific (just custom field names) e.g: item_ct = models.ForeignKey(ContentType, on_delete=models.CASCADE) item_id = models.UUIDField(null=True, blank=True) item = GenericForeignKey('item_ct', 'item_id') My Application tests fails with traceback: .................. File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1021, in add_annotation annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None, File "/usr/local/lib/python3.8/site-packages/django/db/models/expressions.py", line … -
how to take input from form submission and use it to display an entry using django
I'm trying to take the input from a form in Django and to then search storage and display any matches here is the code I have so far. views.py def search(request): input = request.GET.get('q') return render(request, "encyclopedia/search.html", { "entry": util.get_entry(input) == None, "display": util.get_entry(input) }) search.html {% extends "encyclopedia/layout.html" %} {% block title %} {% endblock %} {% block body %} {% if entry %} <div>No entry found</div> {% else %} <div>{{ display }}</div> {% endif %} {% endblock %} layout.html <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> <input type="submit"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> urls.py urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.entry, name="entry"), path("search", views.search, name="search") ] utils.py def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None It works with taking you to the search page but always displays no entry found even if the entry does exist. This is my first project using Django so its pretty new, I'm assuming there is an issue with how I'm feeding in the … -
Profile() got an unexpected keyword argument 'user'
Hi i working with Django . I'm trying to turn my user into a profile with signals When registering the user through a form I get the following error : TypeError at /Registro/ Profile() got an unexpected keyword argument 'user' and the user is created in 'AUTHENTICATION AND AUTHORIZATION' (ADMIN), but not in profiles. Models.py from django.db import models class Profile(models.Model): id = models.AutoField(primary_key=True) nombreUsuario = models.CharField('Nombre usuario : ', max_length=15, null = False, blank=False, unique=True) email = models.EmailField('Email', null=False, blank=False, unique=True) password = models.CharField('Contraseña', max_length=25, null=False, blank=False, default='') #Unique sirve para validar si el usuario existe y sea unico el email y nombre de usuario. nombres = models.CharField('Nombres', max_length=255, null= True, blank=True) apellidos = models.CharField('Apellidos', max_length=255, null=True, blank=True) imagen = models.ImageField(upload_to='img_perfil/',default='batman.png',null=True, blank=True) fecha_union = models.DateField('Fecha de alta', auto_now = False, auto_now_add = True) facebook = models.URLField('Facebook', null=True, blank=True) instagram = models.URLField('Instagram', null=True, blank=True) def __str__(self): return f'Perfil de {self.nombreUsuario}' class Meta: verbose_name = "Perfil" verbose_name_plural = "Perfiles" views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.views.generic.edit import FormView from .models import Profile from .forms import RegistrationForm from django.contrib import messages from django.contrib.auth.models import Group from django.utils.decorators import method_decorator def iniciarSesion(request): return render(request,'social/inicio.html') def registro(request): if request.method … -
Failing to display images
I am writing this Django program which is a clone of Craigslist but displaying images of the searched products. The issue is I failing to display the actual image on the card, I am only getting the image icon at the top left corner of the card import requests from bs4 import BeautifulSoup from django.shortcuts import render from urllib.parse import quote_plus from . import models BASE_CRAIGSLIST_URL = 'https://losangeles.craigslist.org/d/services/search/bbb?query={}' BASE_IMAGE_URL = 'https://images.craigslist.org/{}_300x300.jpg' # Create your views here. def home(request): return render(request, 'base.html') def new_search(request): search = request.POST.get('search') models.Search.objects.create(search=search) final_url = BASE_CRAIGSLIST_URL.format(quote_plus(search)) response = requests.get(final_url) data = response.text soup = BeautifulSoup(data, features='html.parser') post_listings = soup.find_all('li', {'class': 'result-row'}) final_postings = [] for post in post_listings: post_title = post.find(class_='result-title').text post_url = post.find('a').get('href') if post.find(class_='result-price'): post_price = post.find(class_='result-price').text else: post_price = 'N/A' if post.find(class_='result-image').get('data-ids'): post_image_id = post.find(class_='result-image').get('data-ids').split(',')[0].split(':') post_image_url = BASE_IMAGE_URL.format(post_image_id) print(post_image_url) else: post_image_url = 'https://craigslist.org/images/peace.jpg' final_postings.append((post_title, post_url, post_price, post_image_url)) stuff_for_frontend = { 'search': search, 'final_postings': final_postings, } return render(request, 'my_app/new_search.html', stuff_for_frontend) -
How to get Django to reference the name instead of the id/pk
I am currently working on a tutoring API using Python and Django. I want the Tutor Model to show all the tutees (yes, that is a word) and the tutee to show the tutor. Right now, it works correctly but it references the id/pk of the model so I really don't know who or what it refers to. GET a tutee : { "id": 1 "full_name": "First Last", "email": "email@emailprovidercom", "tutor": 1, "subjects": "SubjectX" } As you can see, the tutor is a number instead of a name. GET a tutor: { "id": 1, "full_name": "First Last", "email": "name.name@emailprovider.com", "notes": "XXXXX XX XX X X X X X X XXXXXX XX X X X X ", "tutees": [ 1 ] } The same thing happens here. I am using Django Rest Framework. My models class Tutor(models.Model): full_name = models.CharField(max_length=40) email = models.EmailField() notes = models.TextField() def __str__(self): return self.full_name class Tutee(models.Model): full_name = models.CharField(max_length=40) email = models.EmailField() tutor = models.ForeignKey(Tutor, on_delete=models.CASCADE, related_name="tutees") subjects = models.CharField(max_length=13) def __str__(self): return self.full_name My Serializers class TutorSerializer(serializers.ModelSerializer): class Meta: model = Tutor fields = ['id', 'full_name', 'email', 'notes', 'tutees'] class TuteeSerializer(serializers.ModelSerializer): class Meta: model = Tutee fields = ['id', 'full_name', 'email', "tutor", "subjects"] My … -
Can ImportExportModelAdmin update with django?
I'm still new to Django and found this cool plugin for django called ImportExportModelAdmin that allows me to upload excel files into my DB. However I can't find anything on it updating. Does anybody know if you can update with this plugin or no? -
How to get all objects from many to many relation?
So i have 2 models: class Artist(models.Model): """Artist model.""" name = models.CharField('Artist name', max_length=255) genre = models.CharField('Music genre', max_length=255) class Event(models.Model): """Event model.""" name = models.CharField('Event name', max_length=255) description = models.TextField('Description') localization_name = models.CharField('Localization name', max_length=255) longitude = models.FloatField('Longitude', default=0.0) latitude = models.FloatField('Latitude', default=0.0) artists = models.ManyToManyField(Artist, verbose_name='Artists') date = models.DateTimeField('Event date') And i need to get for one artist, every other artist that was with him on events. I made this on Artist model: @property def get_participate_artists(self): return list(self.event_set.all().values_list('artists__event__artists__name', 'artists__event__artists__genre', named=True).distinct()) but i wanna get queryset or list of Artist objects. -
Stack objects in columns in HTML
I have a list of words that I want to stack in columns in order to save and use the left place in an html file for a Django project: I tried to use the <div class="col-lg-4 col-md-6"> tag but without success ... so how do you stack objects in columns in HTML? {% extends "todo/base.html" %} {% block content %} <!-- Header --> <header class="intro-header"> <div class="container"> <div class="col-lg-5 mr-auto order-lg-2"> <h3><br>Tell me something about you... </h3> </div> </div> </header> <!-- Page Content --> <section class="content-section-a"> <div class="container"> <dt> <span>Pick the keywords you want to express when wearing perfume</span> </dt> <div class="row"> <div class="col-lg-5 mr-auto order-lg-2"> <div class="recommendations"> <form action = "/getmatch" method="POST"> {% for keyword in keywords %} <div class="col-lg-4 col-md-6"> <h3>{{ keyword.title }}</h3> </div> {% endfor %} {% csrf_token %} <button type="submit">Envoyer</button> </form> </div> </div> <!-- /.container --> </div> </div> </section> <!-- Bootstrap core JavaScript --> <script src="static/vendor/jquery/jquery.min.js"></script> <script src="static/vendor/popper/popper.min.js"></script> <script src="static/vendor/bootstrap/js/bootstrap.min.js"></script> {% endblock %} I am aiming at making a multiselection based on buttons or images that would be these words. -
How to send data present in html table rows to back end
Im trying to make a simple library management app using django . I don't know how to send data present in html table rows to backend for storing into database I know I can use json but I think there is more sofesticated way ... This is the code please help I appreciate that... {% extends 'home.html' %} {% block b %} <div class="container"> <table class="table"> <thead> <tr> <th scope="col">book_name</th> <th scope="col">writer_name</th> <th scope="col">category</th> <th scope="col">Sub_category</th> <th scope="col">price</th> <th scope="col">quntity</th> </tr> </thead> <tbody id="table"> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> <td>123</td> <td>1w3</td> </tr> </tbody> </table> <input type="button" class="btn btn-primary" value="store"/> </div> <hr /> <div class="container"> {{ form}} <input type="button" class="btn btn-primary" value="orderd" id="orderd" /> </div> -
Why won't the urls.py file in my Django project let me import this file?
I'm trying to import a function from a file in another directory into my urls.py file. I have included the directory in the settings.py file, ran the ./manage.py makemigrations & the ./manage.py migrate Django commands, and imported the function and the file into the urls.py file. Here is my current code: urls.py: from django.contrib import admin from django.urls import path from apps.accounts.urls import account_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += accounts_urlpatterns settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'rest_framework', 'rest_framework.authtoken', 'djoser', # 'apps.accounts' ] apps/accounts/urls.py: from django.conf.urls import url, include accounts_urlpatterns = [ url(r'^api/v1/', include('djoser.urls')), url(r'^api/v1/', include('djoser.urls.authtoken')), ] the error message: ImportError: cannot import name 'account_urlpatterns' from 'apps.accounts.urls' (/Users/{name}/programming/dj/backend/server/apps/accounts/urls.py) and the project structure: . └── server ├── apps │ └── accounts │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py └── server ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py I appreciate any advice - thank you in advance! -
how to change list to order by username instead of random in Django [duplicate]
I'm having a problem with django views.py , How can i change the "my_users" variable to an ordered list instead of a random list. I'd like to order it by username. This may be simple but i'm still new to Django, thanks. @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) sent_to = [] friends = [] for user in users: friend = user.friends.all() for f in friend: if f in friends: friend = friend.exclude(user=f.user) friends+=friend my_friends = request.user.profile.friends.all() for i in my_friends: if i in friends: friends.remove(i) if request.user.profile in friends: friends.remove(request.user.profile) **my_users = random.sample(list(users), min(len(list(users)), 10))** for r in my_users: if r in friends: my_users.remove(r) friends+=my_users for i in my_friends: if i in friends: friends.remove(i) for se in sent_friend_requests: sent_to.append(se.to_user) context = { 'users': friends, 'sent': sent_to } return render(request, "users/users_list.html", context) -
using cpanel for django apps
Sorry if this question is off-topic, but I need to know if cPanel is really a good choice for hosting Django apps. Currently, my Django app has various packages and some of them need to be compiled, but I don't have superuser privileges to enable or install compilers. Should I still use cPanel or look for other Django friendly alternatives. -
How to create chart in HTML using pychartjs
I am new to web development and I wanted to create a chart on HTML page. In my search I found https://github.com/IridiumIO/pyChart.js repository where I can create charts in python. I followed instructions in readme file but I am missing something. Any leads could help me. I am not sure where am I doing it wrong. Please note that I am not a web developer : Installed pycharm and created a python project installed pyChartjs using pip created a home.html file with following script: <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script> </head> <body> <canvas id="myChart"></canvas> <script> var data = {{ chartJSON | safe }} var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, data); </script> </body> </html> created a python file plot.py with following script: class MyBarGraph(BaseChart): type = ChartType.Bar class data: label = "Numbers" data = [12, 19, 3, 17, 10] backgroundColor = Color.Green def homepage(request): NewChart = MyBarGraph() NewChart.data.label = "My Favourite Numbers" # can change data after creation ChartJSON = NewChart.get() return render(request=request, template_name='home.html', context={"chartJSON": ChartJSON}) -
Can a django url contain a fixed path at the beginning?
I have a server running a django application. This version is stable. For testing purposes I want to host a testing version of the same application on the server. Normally you could do this with subdomains, so the stable version runs at myserver.de and the testing version at test.myserver.de. This is not possible for me, I have only one available domain (myserver.de). So I can only use paths. Let's say I host the stable version at myserver.de/[apps urls] and the test version at myserver.de/test/[apps urls]. To achieve this, i could edit all urls in the testing version. But that would defeat the purpose of testing, because to then make a testing version stable, i would have to re-edit all urls. So I would love to simply edit settings.py and put ALLOWED_HOSTS = ["mysite.de/test"] for the testing version. I tested this locally with ALLOWED_HOSTS = ["127.0.0.1:8000/test", "127.0.0.1/test"], but that unsurprisingly didn't work (I read the docs ^^) Is there a way to run two applications on a django server where the urls of one app always start with /test/<rest> without editing all urls? Could I do this with apache2 instead? (My guess was no, because django builds all links in the … -
Django redirection to react front end causing issue after OAuth2 authentication
I'm trying to implement OAuth2 authentication for the React and Django project. In the development environment (local machine) react will be running on localhost:3000 and Django/DRF will be running on localhost:8000 This is how my flow looks, Kindly excuse if the flow is not easy to grasp. But I will try to explain better below I have 4-5 Django apps all of them have their own functionalities. The user app will have a custom user model and user info related logic. OAuth2 app will have authentication related logics. So this is how my flow works. Step 1: User will access react app by navigating to localhost:3000 or domain name. On the component mount, react will try to get the user information by calling an API endpoint i.e. to the user app API endpoint. Step 2: Since the user is accessing the app for the first time and the user is not logged in, the django user app will send back 403 unauthorized access error to the react app. Step 3: Now react will catch that 403 error and tries to login the user. It makes an API call to the Django OAuth app endpoint and gets the OAuth (Azure AD) … -
Updating a django view with values from a js addin: How to trigger a change event and pass the values back to the view
I've got a form that has a dropdown for selecting the reporting period with the finish always being the current day and start determined by the dropdown selection of week, month, quarter or year. When the period form updates, it has an on change event that submits the form, the page recalculates with the new start date and refreshes. I want to replace this with something more precise and I've got xdsoft's period picker http://xdsoft.net/jqplugins/periodpicker/ partly working but not actually doing anything except logging the change in the console! The period picker is picking up the start and end values on loading and when I update the period dropdown form, displaying those dates as correctly, but when I want to refine that selection by editing the range in the periodpicker, I don't know how to trigger an on change event to recalculate the view similarly to the period form which uses a fieldwrapper onchange to do it. Once this is working, I'll eliminate the period form dropdown as it won't be required but at the moment, it's the only way I could get the values in there so I can pull some data for different periods. Simply put, I need … -
Comment Reply button is not clicking in Django, Json
I am making a Blog app and I built a Comment and Comment Reply Feature BUT that is not working. views.py def create_reply(request,pk): comment = get_object_or_404(Comment,pk=pk) reply = Reply(description=request.GET.get('description'),comment=comment,user=request.user) reply.save() return JsonResponse({'reply':model_to_dict(reply)}) models.py class Reply(models.Model): description = models.TextField() date = models.DateTimeField(auto_now_add=True) comment = models.ForeignKey(Comment,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f'[User] {self.user} [Comment] {self.comment.comment_body[:30]}' detail.html {% for comment in comments %} <div class="comment"> <p class="info"> {{ comment.created_at|naturaltime }} {{ topic.post_owner }} </p> {{ comment.comment_body|linebreaks }} <a class="btn btn-info btn-circle" href="#" id="addReply{{comment.id}}"><span class="glyphicon glyphicon-share-alt"></span> Reply</a> <a class="btn btn-warning btn-circle" data-toggle="collapse" href="#replyOne" id="showReplies{{comment.id}}"><span class="glyphicon glyphicon-comment"></span>{{comment.reply_set.count}} Replies</a> <script> document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { $('#showReplies{{comment.id}}').click(function (event) { event.preventDefault(); $('#replyList{{comment.id}}').slideToggle() }) $('#replyForm{{comment.id}}').slideToggle() $('#addReply{{comment.id}}').click(function (event) { event.preventDefault(); $('#replyForm{{comment.id}}').slideToggle() $('#showReplies{{comment.id}}').click() }) $('#cancelCommentReply{{comment.id}}').click(function (event) { event.preventDefault; $('#replyForm{{comment.id}}').toggle(); $('#commentReplyInput{{comment.id}}').val('') }) $('#replyForm{{comment.id}}').submit(function (event) { event.preventDefault(); $.ajax({ url: "{% url 'create_reply' comment.id %}", data: { 'description': $( '#commentReplyInput{{comment.id}}' ) .val(), }, dataType: 'json', success: function (response) { $.ajax({ url: "{% url 'get_user_by_id' %}", data: { 'pk': response .reply .user, }, method: 'get', dataType: 'json', async: false, success: function ( userResponse ) { let user = userResponse .user $('#replyList{{comment.id}}') .prepend(` <li class="media media-replied"> <a href="/people/${user.id}"> <img src="${user.avatar}" alt="User Image" width="64" height="64"> </a> <div class="media-body"> <div class="well well-lg"> <h4 class="media-heading … -
Why Python pytz package has both Asia/Kolkata and Asia/Calcutta timezones?
I was working on a dropdown with list of all timezones and I took the list of timezones from Python pytz package. I noticed that Asia/Kolkata and Asia/Calcutta both appear in the list where as Asia/Calcutta has been renamed to Asia/Kolkata. Is there a reason pytz is not removing the older timezone? -
Django - caching queryset result
For each of my 12 views I have a few commun querysets currently duplicated in each view. I'm wondering If there is a way to cache the result to avoid recalculating everytime (querysets are differents for each user but once it's set it's barely never change) Company_user = Company.objects.get(User = request.user) User_info = User_info.objects.get(User = request.user) Groups_user = request.user.groups.values_list('name',flat = True) Sales_company = Sales.objects.filter(Company = Company_user) I have also few forms repeted in each views (bootstrap modal open by clicking in a navbar button) Change Password Change personal infos Change sales target Change personnal informations Change target Is there a way to optimize this ? -
Communicating between two Django applications
I have two DjangoREST applications, ServiceA and ServiceB running on different servers. I am using RabbitMQ as my broker and want the two services to commnicate, I assume the producer ServiceA is sending the message. but following the code in the rabbitmq documention it keeps the connection open and it interacts with my Django server on ServiceB. Here is what i have ServiceA def partial_update(self, request, pk=None, *args, **kwargs): email = request.auth.get('email') user = am.AppUser.objects.get(user=email) serializer = aps.AppUserSerializer(user, data=request.data, partial=True) data = { "email": request.auth.get('email') } if serializer.is_valid(): serializer.save() data.update(request.data) message = json.dumps(data) connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='rpc_queue') channel.basic_publish(exchange='', routing_key='test_key', body=message) connection.close() return Response(serializer.data, status=status.HTTP_206_PARTIAL_CONTENT) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ServiceB class RpcClient(object): connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='rpc_queue') def get_user_data(ch, method, props, body): body = body.decode("utf-8") try: x = json.loads(body) queryset = am.AppUser.objects.filter(user=x.get('email')) serializer = aps.AppUserSerializer(queryset, data=x, partial=True) if serializer.is_valid(): serializer.save() ch.basic_publish(exchange='', routing_key="rpc_queue", properties=pika.BasicProperties(correlation_id=props.correlation_id), body=json.dumps(body)) ch.basic_ack(delivery_tag=method.delivery_tag) except Exception as e: print(str(e)) channel.basic_qos(prefetch_count=4) channel.basic_consume(queue='rpc_queue', on_message_callback=get_user_data) print("[x] Awaiting RPC requests") channel.start_consuming() What am I getting wrong? -
SQL Alchemy connection refused when trying to connect db and web containers
I am having problem when running docker-compose up with my django/postgres app(using sqlalchemy). Everything is fine when just running it localy but when i try to contenerise it(with Docker) I am having an error sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused. Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? For some reason app is not connecting to db. My docker-compose.yml: version: "3.9" services: db: image: postgres:9.6 environment: - POSTGRES_DB=my database - POSTGRES_USER=my user - POSTGRES_PASSWORD=my password web: build: . command: python3 manage.py runserver 127.0.0.1:8080 volumes: - .:/code ports: - "8080:8080" depends_on: - db My Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip3 install --trusted-host pypi.python.org -r requirements.txt COPY . /code/ My engine: engine = create_engine("postgresql://mu user:my password@127.0.0.1:5432/my database") Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my database', 'USER': 'my user', 'PASSWORD': 'my password', 'HOST': '127.0.0.1', 'PORT': 5432, } } Can anyone advice where am I making mistake? -
getting error in graphene-django during running tests [ GraphqlTestCase class ]
i write some tests using GraphQlTestCase for my graphene-django api : from graphene_django.utils.testing import GraphQLTestCase class ProductsQueryTestCase(GraphQLTestCase): GRAPHQL_URL = "/graphql" def test_product_by_name_query(self): """ the productByName query given a required arguments named 'name' and return the product with given name """ response = self.query( ''' query productByName($input: String!) { productByName(name: $input) { id name } } ''', op_name="productByName", # Related to the data entered in the database [this is product with id=1] variables={"input": "Marble Floors"} ) self.assertResponseNoErrors(response) but unfortunately i receive an error : { "errors": [ {"message":"Product matching query does not exist."} ] } anybody can help me in this issue or anything about writing tests for graphene-django apis ?