Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trending system
I'd like to know if it is possible to implement some kind of trending system to my Django project. Suppose that we have a Django website, like Instagram, and we need to show an user the most followed users in that platform, how would that be possible if we had a lot of people using the website? Should I use something like Elasticsearch for making big queries faster or should I keep going with only Django itself? I am using Postgresql and I'm really new to Django, anyway, thank you for any answers -
How to showcase quantity with a ManyToMany field django?
Created a recipe app which showcased the list of ingredients and instructions for a recipe, however with Django current form of displaying manytomany relationships, how do I say: 1kg of tomato, 1 oz of water, etc my models: class IngredientList(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class RecipeList(models.Model): name = models.CharField(max_length=100) ingredients = models.ManyToManyField('IngredientList') instructions = models.TextField(max_length=400) amount = models.IntegerField() my views: from django.shortcuts import render from .models import IngredientList, RecipeList def index(request): ing = RecipeList.objects.all() context = {'ing': ing} return render(request, 'myrecipes/home.html', context) -
Customer with multiple addresses, can have only one primary address
I created an app 'customerbin' inside my Django install. I need to create/edit/delete customers who can have multiple addresses where only one address can be primary. If a customer is deleted, all the addresses that belong to that customer need to be deleted as well. If a new customer is created we can't pick an address from another customer. models.py: from django.db import models class Address(models.Model): street = models.CharField(max_length=100) number = models.IntegerField(null=True) postal = models.IntegerField(null=True) city = models.CharField(max_length=100) country = models.CharField(max_length=100) is_primary = models.BooleanField(null=False) geo_lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) geo_lon = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Customer(models.Model): name = models.CharField(max_length=100) email = models.EmailField(unique=True) vat = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) address = models.ForeignKey(Address, on_delete=models.CASCADE) admin.py: from django.contrib import admin from . import models # Register your models here. admin.site.register(models.Customer) admin.site.register(models.Address) How can I make it so that: An address is exclusively linked to one customer? All addresses are deleted when I delete a customer? Only one address is primary for a customer? -
Display ManytoMany Django
trying to display all the ingredients that are associated to a recipe, however: my models: class IngredientList(models.Model): name = models.CharField(max_length=100) class RecipeList(models.Model): name = models.CharField(max_length=100) ingredients = models.ManyToManyField('IngredientList') instructions = models.TextField(max_length=400) amount = models.IntegerField() my views: from django.shortcuts import render from .models import IngredientList, RecipeList def index(request): ing = RecipeList.objects.all() context = {'ing': ing} return render(request, 'myrecipes/home.html', context) my template: <div class="card-body"> <h4>{{ details.name}} <span class="badge badge-info">{{details.cuisine}}</span></h4> <p class="card-text">Ingredients: {{details.ingredients}}</p> <p class="card-text">Instructions: {{details.instructions}}</p> <p class="card-text">This makes {{ details.amount}} meals</p> </div> my output is "myrecipes.IngredientList.None" -
Is it possible to fill in ready-made data through inputs to the JsonField() at Django?
Good afternoon dear friends! Can you tell us more about JsonField() at Django? There is an idea, and it seems that it can be created with the help of json. I would like to create ready-made keys, for example, url_file_1, url_file_2 and more, and also for them size_file_1, size_file_2 in the form of simple inputs, and upon completion of the writing of the article, display them separately according to the keys to the template. Does anyone have an example of solving such a problem? -
'CategoryDetailView' object has no attribute 'get_object'
I am setting up my CategoryDetailView for my CRM. Then this error occurred: 'CategoryDetailView' object has no attribute 'get_object' here's my code sectrion from views.py: class CategoryDetailView(LoginRequiredMixin, generic.ListView): template_name = "clients/category/category_detail.html" context_object_name = "category" def get_context_data(self, **kwargs): context = super(CategoryDetailView, self).get_context_data(**kwargs) clients = self.get_object().client_set.all() context.update({ "clients": clients }) return context Here's my models.py class Client(models.Model): first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) organization = models.ForeignKey(UserProfile, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) class Category(models.Model): name = models.CharField(max_length=30) # New, Tapped, Active, Closed organization = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.name Thanks in advance! -
Not able to make a GET request to the django REST API backend for the id=1 article, from axios in reactjs
I have a frontend application built using reactjs and django rest framework is used to serve this frontend using APIs. The django rest APIs are working fine, I have checked via Postman. When I make a GET request to http://127.0.0.1:8000/articles/, I get the list of articles, and when I click on one of them, it is supposed to take me to the article detail page for that specific id of the article. This is done by making a GET request to http://127.0.0.1:8000/articles/id. The problem is, when I make GET request for id=2,3,4,5,... , it works fine. But when the request is made for id=1, it fails with the error Access to XMLHttpRequest at 'http://127.0.0.1:8000/articles/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Please note that there is no such error for articles/2 or articles/3 and so on. I have allowed the relevant host in django settings.py file. This is the code I have for the article detail page. function ArticlePage(props) { const [MainArticle, setMainArticle] = useState({}); const {id} = useParams() const url = 'http://127.0.0.1:8000/articles/'+id; useEffect(() => { console.log("hello world"); axios.get(url) .then((response) => { setMainArticle(response.data); console.log(response.data); }) .catch((error)=>console.log(error)) }, [url]); return … -
How to make SVG auto scale to the div container - vertical scaling not working
I wrote a SVG that I want to scale to width and height of the parent container. This is scaling horizontally, but not scaling vertically. How to make it work? Do I need to modify the SVG or the CSS? SVG made using svgwrite: import svgwrite def test(request): dwg = svgwrite.Drawing('test.svg', profile='tiny', size=('100%', '100%')) dwg.viewbox(minx=0, miny=0, width=500, height=300) # dwg.stretch() # dwg.fit(horiz='center', vert='middle', scale='slice') dwg.add(dwg.line((0, 0), (0, 500),stroke=svgwrite.rgb(153, 153, 153, 'RGB'), fill='none')) dwg.add(dwg.line((0, 0), (500, 0),stroke=svgwrite.rgb(153, 153, 153, 'RGB'), fill='none')) dwg.add(dwg.line((500, 300), (0, 300),stroke=svgwrite.rgb(153, 153, 153, 'RGB'), fill='none')) dwg.add(dwg.line((500, 300), (500, 0),stroke=svgwrite.rgb(153, 153, 153, 'RGB'), fill='none')) dwg.save() return render(request, 'test.html', context={'svg': dwg }) .resizeme { resize: both; margin: 10px; padding: 0; height: 300px; width: 500px; background-color: #fffdf9; border: hsl(0, 0%, 67%); overflow: hidden; box-shadow: 0 2px 8px rgba(60,65,70,0.1); border-radius: 3px; } <div class="resizeme"> <img src="data:image/svg+xml,<svg baseProfile=&quot;tiny&quot; height=&quot;100%&quot; version=&quot;1.2&quot; viewBox=&quot;0,0,500,300&quot; width=&quot;100%&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:ev=&quot;http://www.w3.org/2001/xml-events&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;><defs /> <line fill=&quot;none&quot; stroke=&quot;rgb(153,153,153)&quot; x1=&quot;0&quot; x2=&quot;0&quot; y1=&quot;0&quot; y2=&quot;500&quot; /> <line fill=&quot;none&quot; stroke=&quot;rgb(153,153,153)&quot; x1=&quot;0&quot; x2=&quot;500&quot; y1=&quot;0&quot; y2=&quot;0&quot; /> <line fill=&quot;none&quot; stroke=&quot;rgb(153,153,153)&quot; x1=&quot;500&quot; x2=&quot;0&quot; y1=&quot;300&quot; y2=&quot;300&quot; /> <line fill=&quot;none&quot; stroke=&quot;rgb(153,153,153)&quot; x1=&quot;500&quot; x2=&quot;500&quot; y1=&quot;300&quot; y2=&quot;0&quot; /></svg>"> </div> -
Django - how to return JSON responses instead of HTML during authentication?
I'm in the process of building a Vue SPA that will use the standard Django Session Authentication, since the Django app and the Vue app will be on the same server and same domain. I've always used django-allauth for everything authentication related, but the problem in this case is that authentication is not handled by Django templates, but i use AJAX to send POST requests to Django to register, sign in and everything else. Is there any way to make Django-Allauth or Django send JSON responses instead of standard HTML and redirects? Here is an example POST request from my code that i use to login: bodyFormData.append('csrfmiddlewaretoken', this.csrf_token) bodyFormData.append('login', 'root'); bodyFormData.append('password', 'Stest'); axios({ method: "post", url: "http://127.0.0.1:8000/accounts/login/", data: bodyFormData, withCredentials: true, headers: {"Content-Type": "application/json"}, }) .then(function (response) { //handle success }) .catch(function (response) { //handle error }); This seems to work fine, it logs me in but the response is HTML and from the network tabs i can see that django tries to redirect me to another page (because that's what it does when authentication is handled by Django templates). Is there any way i can make it send only JSON responses? Do i have to override some view or … -
How do I return my plot graph after return another result in flask python
I need some help, the situation is I m able to return the new CSV file but unable to return the plot graph to another page, and I did separate the return under different scenarios. Does anyone can point out what should I do to my code? or perhaps give me some tips, Thanks in advance! app.py @app.route('/transform', methods=["POST"]) def transform_view(): if request.method == 'POST': if request.files['data_file']: f = request.files['data_file'] if not f: return "No file" stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None) csv_input = csv.reader(stream) stream.seek(0) result = stream.read() df = pd.read_csv(StringIO(result), usecols=[1]) #extract month value df2 = pd.read_csv(StringIO(result)) matrix2 = df2[df2.columns[0]].to_numpy() list1 = matrix2.tolist() # load the model from disk model = load_model('model.h5') dataset = df.values dataset = dataset.astype('float32') scaler = MinMaxScaler(feature_range=(0, 1)) dataset = scaler.fit_transform(dataset) look_back = 1 dataset_look = create_dataset(dataset, look_back) dataset_look = np.reshape(dataset_look, (dataset_look.shape[0], 1, dataset_look.shape[1])) predict = model.predict(dataset_look) transform = scaler.inverse_transform(predict) X_FUTURE = 12 transform = np.array([]) last = dataset[-1] for i in range(X_FUTURE): curr_prediction = model.predict(np.array([last]).reshape(1, look_back, 1)) last = np.concatenate([last[1:], curr_prediction.reshape(-1)]) transform = np.concatenate([transform, curr_prediction[0]]) transform = scaler.inverse_transform([transform])[0] dicts = [] curr_date = pd.to_datetime(list1[-1]) for i in range(X_FUTURE): curr_date = curr_date + relativedelta(months=+1) dicts.append({'Predictions': transform[i], "Month": curr_date}) new_data = pd.DataFrame(dicts).set_index("Month") ##df_predict = pd.DataFrame(transform, columns=["predicted value"]) … -
How to run coroutine function when use sync_to_async in django?
I have a class method that calls _post method as async using sync_to_async in django. but when I test the method inside of Django shell, it does not even run my async _post function and return coroutine object instead. Here is my method: @classmethod def add_event(cls, data): async_post_request = sync_to_async( cls._post, thread_sensitive=True ) response = async_post_request( url=cls.ADD_EVENT, data=data, headers=cls.get_headers(), json_response=False, ) return response Screen of Django shell: -
Django filter id with another model
I Have two model then filtering with another model witout foreignkey like this in the views.py file model1 = apps.get_model('home', 'DataSiswa') model2 = apps.get_model('home', 'DataSekolah') datasiswa1 = model1.objects.filter(statussiswa="Aktif") ids = datasiswa1.values_list('id', flat=True) datasiswa2 = model2.objects.filter(id__in=ids) but object in model datasiswa2 just returning same datasiswa1 data, with only last datasiswa1__id repeated How to iterate that? Or any possible way to queryset multi model then get all the data (both model are one to one relationship with ID) -
Implementing live search using JavaScript and Django
I am trying to make a livesearch feature similar to when you conduct a google search. The search queries cafes in my database by name. I have gotten the functionality to the point where if the whole search value matches a cafe's name in the database it shows up for the user but would like to make it so the search value is checked letter by letter (assuming this is the best way to do a live search). Here is what I have: $("#search-box").keyup(function() { search() }); function search(){ let searchTerm = document.getElementById("search-box").value; $.ajax({ type: 'GET', url: '/electra/search/', data: { 'search_term':searchTerm }, success: function (data) { console.log(searchTerm); //refer to below function for the running of this loop $("#search-results").text(data); } }); }; views.py: def search(request): template_name = 'testingland/write_image.html' search_term = request.GET.get('search_term', None) print(search_term) qs = mapCafes.objects.filter(cafe_name = search_term) return JsonResponse([ [cafe.cafe_name, cafe.cafe_address] for cafe in qs ], safe=False) I have been playing around with the qs filter but can't figure out the best way to approach this. -
Crop/Mask WMS geoTIFF using Polygon
I am building a geospatial webapp with Django. If I have a polygon of class django.contrib.gis.geos.polygon.Polygon, how can I crop/mask a rectangular geoTIFF (gathered via a WMS request; dataset) to the shape of polygon? I've gone down the route of using rasterio to load the TIFF into memory (based on answers to this question), but being new to GIS within Python, I'm not sure this is the best approach to take for my crop/mask requirement. I'm happy to consider any and all solutions to this question. My call to the Corine landcover service, which returns a rectangular tiff: from owslib.wms import WebMapService from rasterio import MemoryFile wms = WebMapService('https://copernicus.discomap.eea.europa.eu/arcgis/services/Corine/CLC2018_WM/MapServer/WMSServer?request=GetCapabilities&service=WMS',version='1.1.1') bbox = (0.823974609375, 52.1081920974632, 1.1700439453125, 52.3202320760973) img = wms.getmap(layers=['12'], srs='EPSG:4326', size=(600, 500), bbox=bbox, format='image/geotiff') with MemoryFile(img) as memfile: with memfile.open() as dataset: print(dataset.profile) And a polygon used to crop/mask dataset: polygon = "SRID=4326;POLYGON ((0.9063720703125029 52.32023207609735, 0.8239746093749998 52.10819209746323, 1.170043945312496 52.14191683166823, 1.170043945312496 52.31351619974807, 0.9063720703125029 52.32023207609735)" Interestingly--and I'm not sure if this will cause cropping issues--when I call dataset.profile I see that there is no CRS information, despite defining srs in getmap and returning a geoTIFF: {'driver': 'PNG', 'dtype': 'uint8', 'nodata': None, 'width': 600, 'height': 500, 'count': 3, 'crs': None, 'transform': Affine(1.0, 0.0, 0.0, … -
On off toggle switch in django BooleanField
I am building a BlogApp and I am stuck on a Problem. What i am trying to do I am trying to change BooleanField into On and Off Toggle Switch. But Failed many times. models.py class Using(models.Model): user = models.ManyToManyField(User,default='') choice = models.BooleanField(default=True,blank=True) template.html <style> .switch { width: 50px; height: 17px; position: relative; display: inline-block; } .switch input { display: none; } .switch .slider { position: absolute; top: 0; bottom: 0; right: 0; left: 0; cursor: pointer; background-color: #e7ecf1; border-radius: 30px !important; border: 0; padding: 0; display: block; margin: 12px 10px; min-height: 11px; } .switch .slider:before { position: absolute; background-color: #aaa; height: 15px; width: 15px; content: ""; left: 0px; bottom: -2px; border-radius: 50%; transition: ease-in-out .5s; } .switch .slider:after { content: ""; color: white; display: block; position: absolute; transform: translate(-50%,-50%); top: 50%; left: 70%; transition: all .5s; font-size: 10px; font-family: Verdana,sans-serif; } .switch input:checked + .slider:after { transition: all .5s; left: 30%; content: ""; } .switch input:checked + .slider { background-color: #d3d6d9; } .switch input:checked + .slider:before { transform: translateX(15px); background-color: #26a2ac; } </style> <label class="switch"> <input type="checkbox" name="choice" id="id_choice" /> <div class="slider"></div> </label> What have i tried :- I tried many CSS and HTML methods BUT nothing worked for … -
One search module to search all models or seach from diiferent apps using Django REST Framework search filter.How to build it?
How to create a custom search filter module for different classes or serializers? I have the 1st Restuatant app with serializer and models and have another app called Books. Now I want a third app called search app to search all the fields from both the apps. Using Django Search filter - https://www.django-rest-framework.org/api-guide/filtering/ -
How to redirect to page where request came from in Django
I currently work on a project an i want to redirect to page where request is came form, when request method is GET. this is my views.py file Views.py def delete_patient(request): if request.method == 'POST': patient_id = request.POST['patient_id'] rem = Patient.objects.get(pk=patient_id) rem2 = CustomUser.objects.get(aid=patient_id, role=4) rem.delete() rem2.delete() return JsonResponse({'delete': 1}) else: // // so please tell me what I want to write in else part of view. -
Django M2M relationship retrieve dynamically using Search
I have implemented a form with M2M relationship and I was following this link. But the issue is that it loads all M2M relationship when the form renders (the M2M records are 150+). Can I have a search input, through which I can load only that M2M record which matches the search input. I am using Django 2.2. Any help would be much appreciated. -
How to find tags inside a class with Beautiful soup
I tried finding all the p tags inside the class content-inner and I don't want all the the p tags that talks about copyright(the last p tags outside the container class) to appears when filtering the p tags and my images shows an empty list or nothing comes out at all and therefore no image is been saved. main = requests.get('https://url_on_html.com/') beautify = BeautifulSoup(main.content,'html5lib') news = beautify.find_all('div', {'class','jeg_block_container'}) arti = [] for each in news: title = each.find('h3', {'class','jeg_post_title'}).text lnk = each.a.get('href') r = requests.get(lnk) soup = BeautifulSoup(r.text,'html5lib') content = [i.text.strip() for i in soup.find_all('p')] content = ' '.join(content) images = [i['src'] for i in soup.find_all('img')] arti.append({ 'Headline': title, 'Link': lnk, 'image': images, 'content': content }) this website have an html page like this <html><head><title>The simple's story</title></head> <body> <div class="content-inner "><div class="addtoany_share_save_cont"><p>He added: “The President king administration has embarked on railway construction</p> <p>Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <script></script> <p> we will not once in Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <p>the emergency of our matter is Once … -
DJANGO DEBUG=FALSE CUSTOM ERROR PAGE (ConnectionAbortedError)
Am trying to create a custom error handling page for production, when am working with local project I noticed am getting error 500 for most of the pages, except few page. ERROR I get is Exception occurred during processing of request from ('127.0.0.1', 52141) Traceback (most recent call last): File "E:\Dev\Python\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "E:\Dev\Python\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "E:\Dev\Python\lib\socketserver.py", line 720, in __init__ self.handle() File "e:\Dev\REPOS\2021 PROJECTS\cognizance_cms\.env\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "e:\Dev\REPOS\2021 PROJECTS\cognizance_cms\.env\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "E:\Dev\Python\lib\socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine I have followed all the steps properly and my custom 500 page loads, but the pages such as login which used to work gets error 500. If more input his needed let me know I'll add them. I have referred most of the issues raised, nothing seems to be conclusive. I tried: # settings.py DEBUG = False ALLOWED_HOSTS = ['*'] as a hotfix. I know it should not be done, still it didn't work -
I want a list of responses from the Chatterbot?
I am making a contextually based chatbot using ChatterBot library of Python and I have trained the chatbot using a ListTrainer where I passed the question and answer in the Trainer. The response is working fine, but now I need a response list of only questions which was can shown next to the user based on previous question asked by the user. I am using a JSON file which contains all the questions and the Answers. I am using Django as a backend for this project. I need to know do I need to create a logic adapter that can give me a list of questions based on the previous question or is there any other way. Like creating a second chatbot for the same. import json from django.views.generic.base import TemplateView from django.views.generic import View from django.shortcuts import render,redirect from django.http import JsonResponse from chatterbot import ChatBot from chatterbot.ext.django_chatterbot import settings from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer import requests class ChatterBotAppView(TemplateView): template_name = 'chatbot/chatbot.html' class ChatterBotApiView(View): """ Provide an API endpoint to interact with ChatterBot. """ """ Training Only Once """ chatterbot = ChatBot(**settings.CHATTERBOT) # # train(chatterbot) # trainer = ChatterBotCorpusTrainer(chatterbot) # trainer.train("chatterbot.corpus.english") # trainer.train("chatterbot.corpus.english.greetings") # trainer … -
NoReverseMatch Error trying to render from html to pdf
I am a newbie on Django and I am currently working on this result management project, I actually downloaded the whole project from a website but while trying to explore its functionalities especially while trying to render the result to show me a pdf file. I encountered an error reading NoReverseMatch at /dashboard/find-result/4/result/ Reverse for 'pdf' not found. 'pdf' is not a valid view function or pattern name. I actually intended to later tweak the models to conform with my own specifications to build the Result Management System but as seen I can not proceed. I need some help. Below are the codes. Views.py from django.http.response import Http404 from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse, HttpResponseServerError from io import BytesIO from django.shortcuts import redirect, render, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.views import PasswordChangeView from django.contrib.auth import update_session_auth_hash from django.contrib.auth import authenticate, login from django.views.generic import TemplateView, View from django.contrib.auth.models import User from results.models import DeclareResult from django.http import JsonResponse from django.urls import reverse_lazy from django.core import serializers import json from student_classes.models import StudentClass from results.models import DeclareResult from subjects.models import Subject from students.models import Student def index(request): if request.method == … -
Django send email reminder based on date how to?
I'm using a Windows OS and have a model where users selects a date. Based on the date I want to send an email to the user at an interval of 10, 25, 35, 50 days. I checked celery but now celery isn't supported on windows....can someone please help me with it..how to setup this functionality? -
Migrations files not created in dockerized Django
I've made changes to a model in a Django app and need to apply migrations to the database. I'm new to Docker, so this is giving me problems. I've been able to makemigrations and migrate, but migration files aren't being created, so I can't push my code to production because of the missing migration files. I think this is because I'm running makemigrations while connected to the Docker container. If I try to makemigrations without being connected to a running container, I get the following error: Traceback (most recent call last): File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 228, in ensure_connection self.connect() File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 205, in connect self.connection = self.get_new_connection(conn_params) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 172, in get_new_connection connection = Database.connect(**conn_params) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 393, in execute_from_command_line utility.execute() File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 387, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/base.py", line 336, in run_from_argv self.execute(*args, **cmd_options) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/base.py", line 377, in execute output = self.handle(*args, **options) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/base.py", line 87, … -
DJANGO: TYPE ERROR: an integer is required
Please help! I am new to DJANGO and have little experience coding. I am working through a tutorial that involves building a shopping cart. When the user navigates to localhost/cart/cart the code should create a cart. I had a previous error which I fixed but the fix appears to have unmasked a different problem. ALthough the cart loads, no cart is created in admin portal. When attempting to create the cart from the DJANGO admin UI manually on clicking add the following error appears: Traceback error Internal Server Error: /admin/cart/cart/add/ Traceback (most recent call last): File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", …