Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to register model in Django Admin?
I am creating an eCommerce functionality in my Django admin panel, I want something like this (suppose if a product has SKU, size, 'flavour, price) then these should be in a single order (i mean in a single line) in my admin panel, and there should be add more option, if I upload product from backend then on click add more these all options will repeat again and I can fill new values in these options, please let me know how I can solve this issue. it means a product can have multiple flavours, multiple sizes, multiple price(price will be changed according to size and flavour) and multiple SKU (SKU will be changed according size and flavour) -
How to get complete list of related objects in Django-rest-Framework
I am trying to implement Nested serializer for the first time in django-rest-framework My requirement is i need the response data in below form :- { id: 0, title: "Fresh", data: [ [{ image: ".../assets/images/banana.jpeg", name: "Fruits", image_scaling: 2, API: "http://database_api" }, { image: "../assets/images/banana.jpeg", name: "Vegetables", image_scaling: 2, API: "http://database_api" }, { image: "../assets/images/banana.jpeg", name: "Exotic Vegetables", image_scaling: 2, API: "http://database_api" } ] ] } I am validating the token for the get api and listing the objects form DB. My current implementation of views.py is :- class home(APIView): def get(self,request,format=None): header_token = request.META.get('HTTP_AUTHORIZATION', None) if header_token is not None: token = header_token access_token=token.split(' ')[1] print(access_token) if(validate_token(access_token) == None): raise NotFound('user does exist') queryset=Fresh.objects.all().select_related('data') print(queryset) serializer = FreshSerializer(queryset,many=True) return Response(serializer.data) Serializer.py is :- class DataSerializer(serializers.ModelSerializer): class Meta: model=data fields = ('name','image_scaling','image') class FreshSerializer(serializers.ModelSerializer): data=DataSerializer(read_only=True, many=False) class Meta: model = Fresh fields = ('title','data') models.py is :- class data(models.Model): name=models.CharField(max_length=9,null=True) image_scaling=models.IntegerField(default=0,null=True) image=models.URLField(max_length = 200) def __str__(self): return str(self.name) class Fresh(models.Model): title=models.CharField(max_length=9) data=models.ForeignKey(data,on_delete=models.CASCADE,default=None, null=True) def __str__(self): return str(self.title)+" " +str(self.data) My current output is :- [ { "title": "vegetable", "data": { "name": "vegetable", "image_scaling": 2, "image": "https......jpg" } }, { "title": "exoticveg", "data": { "name": "exoticveg", "image_scaling": 2, "image": "https://.......jpg" } … -
Received unregistered task of type KeyError('modules.callback.tasks.check_transaction')
I'm trying to execute chains of task with celery, this is my tasks: from config import celery_app from modules.transaction.models import Transaction import logging logger = logging.getLogger('callback_log') @celery_app.task def get_transaction(transaction_id): transaction = Transaction.objects.last().__dict__ if transaction.get("_state"): transaction.pop("_state") return transaction_id, transaction @celery_app.task def check_transaction(transaction_id, transaction_dict): return transaction_dict["id"] == transaction_id: and this is my celery app import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") app = Celery("toolbox",include=["modules.callback.tasks"]) app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() and where i used tasks: from celery import chain from modules.callback.tasks import get_transaction, check_transaction @action(methods=["GET"], detail=False) def test_chain(self, request): chain(get_transaction.s(234) | check_transaction.s()).apply_async() return Response({}) after starting celery with this command: celery -A config worker -l info celery prints: -------------- celery@SUSE v4.4.6 (cliffs) --- ***** ----- -- ******* ---- Linux-5.7.7-1-default-x86_64-with-glibc2.2.5 2020-07-18 16:10:21 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: toolbox:0x7f731f2dbfa0 - ** ---------- .> transport: amqp://FAKE_USER:**@XXX.XXX.XXX.XX:XXXX// - ** ---------- .> results: amqp:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . modules.callback.tasks.check_transaction . modules.callback.tasks.get_transaction after executing chain, the first task will execute successfully but for second task it throws this exception: Received … -
How I can park heroku domain instead of pointing? My domain has no cname option
I am newbie to heroku. I have purchased a domain which only supports nameservers and not CNAME. But I can not find nameservers in heroku. So is there anyway to use that domain in heroku? It has .pk extension. Anybody guide me please. Thanks -
You cannot access body after reading from request's data stream, django
I am trying to read request body using django but, it throws an error: You cannot access body after reading from request's data stream Here is my code: @csrf_exempt def update_profile(request): """ """ if request.method == 'POST': try: # Validate payload = json.loads(request.body) # get files profile_pic = request.FILES.get('profile_pic') user_data = util.update_profile(obj_common, user_id, payload,profile_pic) return user_data I have seen many answer on the stackoverflow, They advice me to replace request.body with request.data. but when it tried i got another error {AttributeError}'WSGIRequest' object has no attribute 'data' -
Django FormView passing paramaters and context
I want to return some data based on a pk that is passed in the url, in a FormView, view, my question is, how can I pass in the paramater and define the context? -
how to build a bookmark system in django as in instagram
I wanna build this bookmarking system like in Instagram, I'm having problems writing the logic in views.py and displaying it. So what I want is to bookmark "Act" based on "act-id's" to Wishlist model if a user is authenticated and it would be better if we use Ajax for the post-call(when clicked on the bookmark icon) or open to new options really. Here's my current code... Please help me! if you need any extra bit of code just lemme know. models.py class Act(models.Model): label1 = models.CharField(max_length=50, blank=False) label2 = models.ImageField(blank=False, null=True) label3 = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) label4 = models.CharField(max_length=80) def __str__(self): return self.Name class Wishlist(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE,null=True) act_id = models.ForeignKey(Act, on_delete=models.DO_NOTHING) views.py @csrf_exempt def wishlist(request): act_id = request.POST.get('act_id') if not act_id: raise ValueError("Required act_id to set wishlist") user_id = request.user.pk try: act_id = Act.objects.get(pk=act_id) wishlist_obj = { 'user_id': user_id, 'act_id': act_id } Wishlist(**wishlist_obj).save() except ObjectDoesNotExist: return HttpResponse('Some error occured, unable to add to wishlist') return HttpResponse('Added to wishlist') urls.py urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.login_req, name='login'), path("logout/", views.logout_req, name="logout"), path('home/', views.home, name='home'), path('wishlist/', views.wishlist, name='wishlist'), ] for more context here's a conceptual pic of home.html [1]: https://i.stack.imgur.com/lX8Ro.png -
Django - DoesNotExist: option matching query does not exist
I am getting DoesNotExist Error. Tried Filter(),First(),Try-except - None working. I don't want hide error through try-catch, want to remove it. I Tried many answers here none is working. Using latest Django and Python3.6 , php7.2. Console Output - {'1': '4'} Internal Server Error: /student_verify/ Traceback (most recent call last): File "/home/student/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in innerresponse = get_response(request) File "/home/student/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_responseresponse = self.process_exception_by_middleware(e, request) File "/home/student/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_responseresponse = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/student/django/online_exam/views.py", line 999, in student_verify opt = option.objects.get(question_id = ques, option_no=j.answer) File "/home/student/.local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/student/.local/lib/python3.6/site-packages/django/db/models/query.py", line 417, in get self.model._meta.object_name online_exam.models.option.DoesNotExist: option matching query does not exist. [18/Jul/2020 10:05:49] "POST /student_verify/ HTTP/1.1" 500 16275 views.py is as follows - def student_verify(request): if(request.session.get('id', False) != False and request.session.get('account_type', False) == 1): attempted = json.loads(request.POST.get("answer", False)) registration.objects.filter(id = request.POST["registration_id"]).update(answered = 1) marks = 0 for i in attempted.keys(): attempted_answer = dict(attempted[i]) print(attempted_answer['answers']) #print(attempted_answer['question_id']) ans = dict() ques = question_bank.objects.get(pk = attempted_answer['question_id']) ques_type = ques.question_type.q_type if(ques_type == "Multiple Choice Single Answer" or ques_type == "Multiple Choice Multiple Answer"): for j in answer.objects.filter(question_id = ques).all(): opt = option.objects.get(question_id = ques, option_no=j.answer) ans[opt.option_no] = opt.option_value temp = result() temp.registration_id … -
Django: how to add csrf token when prepending a from using ajax
I am adding a comment functionality in my project. And I am using ajax to make it dynamic so that when the user clicks on the comment submit button it will be added in the comment section dynamically without refreshing the page. But the problem is when prepending a form using ajax I cant add csrf token like this {% csrf_token %} in the form because ajax wouldn't understand it and take it as text. function getids(postid){ console.log(postid) $(postformid).one('submit', function(event){ event.preventDefault(); console.log(event) console.log("form submitted!") // sanity check create_comment(posted); }); } // AJAX for posting function create_comment(postid) { console.log("create comment is working!") // sanity check console.log(postid) console.log(talkid) $.ajax({ url : "create_comment/"+postid, // the endpoint type : "POST", // http method data : { the_comment : $(cmtext).val() }, // data sent with the post request // handle a successful response success : function(json) { $(cmtext).val(''); // remove the value from the input console.log(json); // log the returned json to the console $(talkid).prepend( "<div class='col-1 p-0'><form' id=upvote' method='POST'>{%"csrf_token"%}<button class='btn btn-md btn-outline-danger btn- block p-auto' id='btnid' onclick='---' type='submit'></button></form></div>"); console.log("success"); // sanity check }, // handle a non-successful response error : function(xhr,errmsg,err) { } }); }; pretending my form here <div class="row m-0" id="talk{{post.id}}"></div> is … -
I want to make an engeneering based website
So basically I want to make a website in which the user will input some values and will get the output, but the formula which I write should be embed in backend. So which backend will be easier for me to work on this project. The formulas are a little complex and we have to take many values and input. Which languages will be easier for me. Collabs for this project are invited. And which database will be more secure for such website. -
Fetching list of entries with their field name into dictionary DJango Models
I have the list of ids id_list = [1,2,3,4] I am using for loop to fetch the result roles = [] for id in id_list: roles.append(Role.objects.filter(id = id).values('id' , 'name')) This give me the result but in this form: roles = [[{id:1, name:employee}], [{id:2, name=staff}], [{id:3,name=driver}] , [{id:4, name=staffboy}]] But I want data in dictionary so that also relatable for Json response roles = [{id:1,name:employee} , {id:2,name:staff} , {id:3,name:driver} , {id:4,name:staffboy}] Any other method of fetching the list of results in a format I want? Thanks for your help -
Create a vanilla JavaScript confirm delete modal when deleting a Django object
Most answers for this on Stack Overflow are written using Ajax and or jQuery. For an assignment I need it to be vanilla JS. This is what I have so far. Strangely I have a working delete button with a GET request method. Not a POST method as it normally would be. I'm not sure why and honestly got it working without the confirmation modal with trial and error. This is what I have so far: urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='vgHome'), # relative path to VideoGames homepage path('about/', views.about, name='vgAbout'), # relative path to VideoGames about page path('news/', views.news, name='vgNews'), # realtive path to VideoGames news page path('gallery', views.gallery, name='vgGallery'), # relative path to VideoGames gallery page path('library/', views.library, name='vgLibrary'), # relative path to VideoGames user library path('library/create', views.create_game, name='addGame'), # realative path to game create form path('library/<int:game_id>/game_info', views.game_info, name='gameInfo'), # realative path to each games info page path('library/<int:game_id>/update', views.update_game, name='updateGame'), # relative path to update selected game path('library/<int:id>/delete', views.delete_game, name='deleteGame'), # relative path to delete selected game ] views.py from django.shortcuts import render, get_object_or_404, HttpResponseRedirect, redirect from django.contrib import messages from .forms import GameForm from .models import Game # … -
Static Files Don't Work Django Elastic Beanstalk Amazon Linux 2
I have Django project on EB on Amazon Linux 2. After running the collectstatic command, I can verify that there is a staticfiles folder. But when I go to the admin, the static files return 404 Here is my config file which doesn't work: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: backend.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: backend.settings aws:elasticbeanstalk:environment:proxy:staticfiles: /static/: staticfiles/ -
OperationalError: at no such column in django
OperationalError no such column: store_customer_info.product_id add foreignkey then after give error class Product(models.Model): name = models.CharField(max_length=50) image = models.ImageField() desc = models.CharField(max_length=500) stock = models.IntegerField() price = models.IntegerField() timestamp = models.DateTimeField(auto_now=timezone.now) new = models.BooleanField(default=False) hot = models.BooleanField(default=False) off = models.BooleanField(default=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name @staticmethod def get_all_product(): return Product.objects.all() @staticmethod def get_product_category_wise(id): return Product.objects.filter(category=id) @staticmethod def get_cart_product(list): return Product.objects.filter(id__in=list) customer model class Customer_info(models.Model): fname = models.CharField(max_length=50) lname = models.CharField(max_length=50) email = models.CharField(max_length=50) phone = models.CharField(max_length=20) country = models.CharField(max_length=20) state = models.CharField(max_length=20) add1 = models.CharField(max_length=100) add2 = models.CharField(max_length=100) pin = models.CharField(max_length=10) company = models.CharField(max_length=20) product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.fname I try : Python manage.py makemigrations python manage.py migrate (Not solve Error) then I delete migrations file and also delete db.sqlite3 file and run a command Python manage.py makemigrations python manage.py migrate(Not solve Error) then Python manage.py makemigrations store (App name is store) Python manage.py migrate store Error:no such column: store_customer_info.product_id -
How to create Variations in Django?
I am developing an eCommerce website and I want to work with variations, but I don't know how to create variation structure, All variations will be connected with my product table. Please let me know how I can do it. For example, I am sharing an example, please check the second part of this link (https://laracasts.com/discuss/channels/general-discussion/custom-ecommerce-dynamic-product-variants) here is variation structure with the product but I do not know which relationship will work for this, I am a little bit confused about it, please give me the solution for this. -
I want to filter my product on the bases of rating, How can i do that?
My Models from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField() def no_of_ratings(self): ratings = Rating.objects.filter(product=self) return len(ratings) def avg_rating(self): ratings = Rating.objects.filter(product=self) sum=0 for rating in ratings: sum += rating.rating if len(ratings)>0: return sum/len(ratings) else: return None def __str__(self): return self.title class Rating(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) class Meta: unique_together = (('user', 'product'),) index_together = (('user', 'product'),) serializer.py from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from .models import Product, Rating class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields =('id', 'title', 'description', 'no_of_ratings', 'avg_rating') class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('product', 'user', 'rating') views.py from django.shortcuts import render from rest_framework import viewsets, status from rest_framework.authentication import TokenAuthentication from rest_framework.response import Response from rest_framework.decorators import action from django.contrib.auth.models import User from .models import Rating, Product from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.permissions import IsAuthenticated, AllowAny from .serializers … -
Browser Content Security Policy Issue in paypal SDK integration
I am integrating the paypal payment system in python Django environment. Now, as per the basic guidelines, the payment is created as follows, payment = Payment({ "intent": "sale", # Set payment method "payer": { "payment_method": "paypal" }, # Set redirect URLs "redirect_urls": { "return_url": "http://localhost:3000/process", "cancel_url": "http://localhost:3000/cancel" }, # Set transaction object "transactions": [{ "amount": { "total": "10.00", "currency": "USD" }, "description": "payment description" }] }) if payment.create(): for link in payment.links: if link.method == "REDIRECT": redirect_url = (link.href) return redirect_url return False else: print(payment.error) return False Now, it generates a redirect url properly. But after going into the url (payment page) I am getting a list of errors in both Google chrome and in Mozilla Firefox. Now the error is related to CSP but that is not in my hand cause the rules are mentioned in the paypal page itself. Is there any way out ? Am I mistaking some settings or code ? -
django.core.exceptions.FieldError: Cannot resolve keyword 'department_name' into field
How to use serializers.SlugRelatedField Correctly? My code is look like this but it got an error... There is the full error: django.core.exceptions.FieldError: Cannot resolve keyword 'department_name' into field. Choices are: badge, created_at, department, department_id, gender, id, name, position, position_id, updated_at Model Code: class Employee(models.Model): GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ) name = models.CharField(max_length=100) badge = models.CharField(max_length=6, unique=True) gender = models.CharField(max_length=20, choices=GENDER_CHOICES) department = models.ForeignKey( Department, on_delete=models.CASCADE, null=True) position = models.ForeignKey( Position, on_delete=models.CASCADE, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name} - {self.badge}' Serializer Code from rest_framework import serializers from .models import Employee class EmployeeSerializer(serializers.ModelSerializer): department = serializers.SlugRelatedField( slug_field='department_name', queryset=Employee.objects.all()) # position = serializers.SlugRelatedField( # slug_field='position_name', queryset=Employee.objects.all() class Meta: model = Employee fields = '__all__' -
How to update database value in django on a button click
I have a template that contains one search button (this is for filtering the details based on option choose in the select) and a Next button (this is to move to next tab). When the template loads for then i will search for projects from the select list and the result will be displayed in a table - which is working for me. After the result is displayed in the table, i will select a row (through radio button) from that table and click on Next button to move to next tab. Here when i click the Next button i want to update some values in the django database but not able to achieve this. Can some one help me? My View: def form(request): projects = CreateProjects.objects.filter(Status=True) if request.method == 'POST': selectproject = request.POST.get('selectproject') searchprojlist = ListProjDetails.objects.filter(Project=selectproject) return render(request,'form.html',{'projects':projects,'lists': searchprojlist}) elif request.POST.get('tab1btn','') == 'nxttab': selval = ListProjDetails.objects.get(id=1) selval.Selected = True selval.LockedUser = request.user selval.save() else: lists = ListProjDetails.objects.all() return render(request,'form.html',{'projects':projects}) First If POST is working correctly, trouble is with the 2nd IF (2nd button). I have swapped the 2nd IF to be called fresh after the else statement but not working either. I have passed id=1 for testing purpose only -
What is best library for computer Management in python?
i wanna make a Management system in python .. Idont know , Management use library -
How to save PDF file generated in Django to a specified directory in my project?
I need my pdf files that is generated by using xhtml2pdf library be saved/stored in some specified directory in my project folder, for example in the folder "generate_pdf/media/" NOTE: I am using django framework for my project. And here is the structure of project. generate_pdf/ -----generate_pdf/ -----generate_pdf_app/ --admin.py ---models.py ---views.py -----media/ This is my current view.py from django.shortcuts import render from io import BytesIO from django.http import HttpResponse from django.views import View from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): # this function renders html template to a PDF. template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None context = { "first_name": "Jhon", "last_name": "Doe", "city": "London", "phone": "1234567890", "email": "jhon@mail.com", } def render_html(self, *args, **kwargs): # here i'm passing the template into this function, which get triggered on click of button pdf = render_to_pdf('pdf_template.html', context) return HttpResponse(pdf, content_type='application/pdf') def download_pdf(self, *args, **kwargs): # I want this function to get triggered that will save the generated PDF in media directory. On click of button event. pdf = render_to_pdf('app/pdf_template.html', context) Thanks in advance!! -
Ddjango: can't store JSON to DB in 1:n model
I'm trying to store 'some user's request's detail_requests' when client sends "post" to server. I classified user's id by token, and stored requests. I've tried to store detail_requests, but I checked that DetailRequestModel is empty. please help me to store DetailRequestModel... This is JSON which I wanna store {"detail_requests" : [ { "person": “me”, "making_type" : "making_type", "age" : 18, "season" : "season", "detailImage" : "detailImage", "fabric" : "fabric", "memo" : "memomemomemomemomemomemomemomemomemo" }, { "person": “grandma", "making_type" : "making_type", "age" : 78, "season" : "season", "detailImage" : "detailImage", "fabric" : "fabric", "memo" : "memomemomemomemomemomemomemomemomemo" } ], "end_date" : "123" } here's my models.py class SignUpModel(AbstractBaseUser, PermissionsMixin): user_id = models.CharField(max_length=50, default='', unique=True, verbose_name=('user_id')) nickname = models.CharField(max_length=4, default='') phone_num = models.CharField(max_length=15, default=None, null=False) objects = UserManager() class RequestModel(models.Model): requested_user = models.ForeignKey(SignUpModel, on_delete=models.CASCADE, null=True) end_date = models.CharField(max_length=20) objects = models.Manager() class DetailRequestModel(models.Model): request = models.ForeignKey(RequestModel, on_delete=models.CASCADE) person = models.CharField(max_length=10) making_type = models.CharField(max_length=10) age = models.CharField(max_length=7) # CharField? season = models.CharField(max_length=10) fabric = models.CharField(max_length=10) memo = models.CharField(max_length=100) objects = models.Manager() and here's my views.py, and I'm guessing 'for' sentence didn't work. class hanbokRequestView(View): @login_decorator def post(self, request, *args, **kwargs): data = json.loads(request.body) access_token = request.headers.get('Authorization', None) payload = jwt.decode(access_token, SECRET_KEY, algorithm='HS256') user = SignUpModel.objects.get(id=payload['id']) … -
Django Forms how to access current request user in ModelForm?
I am working on a hard django project and I am stuck again. In my implementation of ModelForm, I have this form. So I wanna filter the queryset in the assign field so if I do this assign.objects.filter(user_id=1) it is gonna show every user this queryset but I wanna put the request user in this queryset. How can I access the current request user? class SomeModelForm(forms.ModelForm): assign = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Assign.objects.all(), ) class Meta: model = SomeModel fields = '__all__' -
connecting django devserver from android studio fails
I am trying to connect to django rest framework server from android studio on my local machine using volley . I tried running server with 0.0.0.0:8000 on command line and have added ALLOWED_HOST=[*] in settings.py. Error message in android studio com.android.volley.NoConnectionError: java.net.ConnectException: Failed to connect to /0.0.0.0:8000 Below is the android client code P.S:- All the import libraries are included. String URL= "http://0.0.0.0:8000/api/userdata/"; RequestQueue requestQueue = Volley.newRequestQueue(this); JsonObjectRequest objectRequest = new JsonObjectRequest( Request.Method.GET, URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.e("Response:",response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Response:",error.toString()); } } ); -
Built Docker image cannot reach postgreSQL
I am using Django and PostgreSQL as different containers for a project. When I run the containers using docker-compose up, my Django application can connect to the PostgreSQL, but the same, when I build the docker image with docker build . --file Dockerfile --tag rengine:$(date +%s), the image successfully builds, but on the entrypoint.sh, it is unable to find host as db. My docker-compose file is version: '3' services: db: restart: always image: "postgres:12.3-alpine" environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_PORT=5432 ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data/ networks: - rengine_network web: restart: always build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - db networks: - rengine_network networks: rengine_network: volumes: postgres_data: Entrypoint #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z db 5432; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py migrate # Load default engine types python manage.py loaddata fixtures/default_scan_engines.json --app scanEngine.EngineType exec "$@" and Dockerfile # Base image FROM python:3-alpine # Labels and Credits LABEL \ name="reNgine" \ author="Yogesh Ojha <yogesh.ojha11@gmail.com>" \ description="reNgine is a automated pipeline of recon process, useful for information gathering during web application penetration testing." ENV PYTHONDONTWRITEBYTECODE 1 …