Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting bad request 400: Unable to submit formset with DRF
I have two models, one is Voucher and another one is Journal. I created a formset with django forms to create a voucher for a set of journals. Each voucher must contain at least two transactions of journal. Here's my model below: class Voucher(models.Model): transactions_date = models.DateField(default=now) voucher_type = models.CharField(max_length=2) voucher = models.CharField(max_length=50, blank=True, null=True) narration = models.CharField(max_length=100) debit = models.DecimalField(max_digits=10, decimal_places=2, default=0) credit = models.DecimalField(max_digits=10, decimal_places=2, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name="+", blank=True, null=True, on_delete=models.SET_NULL) updated_by = models.ForeignKey(User, related_name="+", blank=True, null=True, on_delete=models.SET_NULL) is_deleted = models.BooleanField(default=False) def __str__(self): return str(self.voucher) class Meta: verbose_name = 'Voucher' verbose_name_plural = 'Vouchers' default_related_name = 'voucher' def get_voucher(self): return self.voucher_type + now().strftime('%Y-%m-%d-' + str(int(self.id))) def get_debit(self): transactions = Journal.objects.filter(voucher=self) total = 0 for item in transactions: total += item.debit return total def get_credit(self): transactions = Journal.objects.filter(voucher=self) total = 0 for item in transactions: total += item.credit return total def save(self, *args, **kwargs): self.voucher = self.get_voucher() self.debit = self.get_debit() self.credit = self.get_credit() super(Voucher, self).save(*args, **kwargs) class Journal(models.Model): account = models.ForeignKey('Account', blank=True, null=True, on_delete=models.SET_NULL) voucher = models.ForeignKey('Voucher', blank=True, null=True, on_delete=models.CASCADE) debit = models.DecimalField(max_digits=10, decimal_places=2, default=0) credit = models.DecimalField(max_digits=10, decimal_places=2, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name="+", blank=True, null=True, … -
Error running WSGI application, no module named django
I have some problem while deploying my website to Pythonanywhere.com i've done all things step by step like it was in a guide-line and at the end i catch an error: error log 2022-03-27 20:07:23,699: Error running WSGI application 2022-03-27 20:07:23,700: ModuleNotFoundError: No module named 'django' 2022-03-27 20:07:23,700: File "/var/www/usitingshit_pythonanywhere_com_wsgi.py", line 88, in <module> 2022-03-27 20:07:23,700: from django.core.wsgi import get_wsgi_application 2022-03-27 20:07:23,700: i've tried to change wsgi.py file import os import sys path = '/home/usitingshit/deploy_course_work/' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] ='/home/usitingshit/deploy_course_work/vodprojectstroy_site/wsgi.py' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() structure of my project: has anybody had the same problem? how can i fix that? sorry if this question is silly, coz i am a beginner in django -
django login without password
I'm looking for a way how to login without password. During create new user I noticed that, password field has default value empty, but not null. How can I do login with empty password? Because not all user needed to have password set. models.py class user(AbstractUser): database: | username | password | | -------- | -------------- | | A | | | B | 123 | views.py user = authenticate(request, salary_number='A', password='') if user is not None: login(request, user) return redirect('index') -
Vercel CLI Pyhon version issue when deploying Django project
When running the vercel command in Ubuntu terminal: Error! Command failed: python3.6 /tmp/2de7da56/get-pip.py --user ERROR: This script does not work on Python 3.6 The minimum supported Python version is 3.7. Please > use https://bootstrap.pypa.io/pip/3.6/get-pip.py instead. python --version returns 3.8.10. pip --version returns 22.0.4. vercel --version returns 24.0.1 requirements.txt just has Django == 4.0.3 What I tried: Ran the script linked in the error message and added its installation directory to PATH. Updated pip in default directory to 22.0.4. Even aliased python3.6 to python at one point. Tried on both Windows and Ubuntu. -
django export data to excel template
I installed django-import-export and it's working fine with export to excel file. But I would like to insert data into prepared excel file because of some macro. It's possible to do like that? And how can I achieve it? -
Let user add user but not change the user in Django admin, is that possible, and if so how?
In my Django 4.0 it's impossible to let staff user "add User" but not "change user" in the Admin interface. Is that possible to let staff user to not change user in the admin interface but still be able to add user? -
user accessible in template without passing to context
i have the following code. @login_required(login_url='login') def ListDeleteNoteView(request, pk): query_note = Note.objects.filter(id=pk).get() if request.method == 'POST': query_note.delete() return redirect('dashboard') context = { 'note': query_note } return render(request, 'notes/note.html', context) in the template,am able to access {{user}}. i dont understand why am able to do soo. i never passed it to context.why is this soo guys??. It also didnt come from the inherited base.html -
How to pass arguments to reverse so it is accessible in a django view
I'm trying to understand how reverse works with arguments and my goal here is to pass the body of a post request from one view (callerView) to another (demoView) through a function. In other words, I want demoVIew to return the body of the json request that was sent to callerView (I intend to do some manipulation of the data in demoView later on). Urls - "api/v2/ada/demo", views.demoView.as_view(), name="ada-demo", ), path( "api/v2/ada/caller", views.callerView.as_view(), name="ada-caller", ), ] Function - ada_response = reverse("ada-demo", args=payload) return ada_response Views - permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): body = request.data response = demo(body) return Response(response, status=status.HTTP_200_OK) class demoView(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): body = request.data return Response(body, status=status.HTTP_200_OK) Tests- def test_caller( self ): rp_payload = { "contact_uuid": "49548747-48888043", "choices": 3, "message": ( "What is the issue?\n\nAbdominal pain" "\nHeadache\nNone of these\n\n" "Choose the option that matches your answer. " "Eg, 1 for Abdominal pain\n\nEnter *back* to go to " "the previous question or *abort* to " "end the assessment" ), "step": 6, "value": 2, "optionId": 0, "path": "/assessments/assessment-id/dialog/next", "cardType": "CHOICE", "title": "SYMPTOM" } user = get_user_model().objects.create_user("test") self.client.force_authenticate(user) response = self.client.post( reverse("ada-caller"), rp_payload, ) print(response) self.assertEqual(response.status_code, 400, response)``` Error: ```django.urls.exceptions.NoReverseMatch: Reverse … -
Is it safe to delete all .pyc files from the django root directory?
Is it safe to delete all .pyc files from the Django root directory? I ran the command below in my Django root directory: find . -name "*.pyc" -exec git rm -f "{}" \; to delete .pyc files that I saw in my git check-in but the process went for quite some time and deleted hundred of .pyc files within every directory. I am a beginner in Python, Git and I am a bit concerned if this will have an impact on my Django code? -
persist indiviual data between views
I am playing with Django. I have a view where i repr 1 object, below them there is 4 cards with options related to that object. I want the user to click in one of the cards, then rear first obj, clicked option and 4 new options related to clicked option. I am not really sure about how to dev that. I was thinking about use forms or session (?). Because I really don't want to use urls kwargs. Hope u can guide me, thanks! I tried with context but didn't achieve anything plausible -
How can I load my Django project into celery workers AFTER they fork?
This question might seem odd to folks, but it's actually a creative question. I'm using Django (v3.2.3) and celery (v5.2.3) for a project. I've noticed that the workers and master process all share the same code (probably b/c celery loads my app modules before it forks the child processes for configuration reasons). While this would normally be fine, I want to do something more unreasonable :smile: — I want the celery workers to each load my project code after they fork (similar to how uwsgi does with lazy-apps configuration). Some responses here will ask why, but let's not focus on that (remember, I'm being unreasonable). Let's just assume I don't want to write thread-safe code. The risks are understood, namely that each child worker would load more memory and be slow at restart. It's not clear to me from reading the celery code how this would be possible. I've tried this to no avail: listen to the signal worker_process_init (source here) then use my project's instantiated app ref and talk to the DjangoFixup interface app._fixups[0] here and try to manually call all the registered signal callbacks for the DjangoFixupWorker here Any ideas on the steps to get this to work … -
I want to add products to my cart and display the cart details like cart list. but the code is not showing the details on the page?
views is written as def cart_details(request, tot=0, count=0, cart_items=None): try:ct = cartlist.objects.get(cart_id=c_id(request)) ct_items = item.objects.filter(cart=ct, active=True) for i in ct_items: tot += (i.prodt.price * i.quan)count += i.quan except ObjectDoesNotExist: pass return render(request, 'cart.html', {'ci': cart_items, 't': tot, 'cn': count}) def c_id(request): ct_id = request.session.session_key if not ct_id: ct_id = request.session.create() return ct_id cart>models class cartlist(models.Model): cart_id = models.CharField(max_length=250, unique=True) date_added = models.DateTimeField(auto_now_add=True) class item(models.Model): prodt = models.ForeignKey(product, on_delete=models.CASCADE) cart = models.ForeignKey(cartlist, on_delete=models.CASCADE) quan = models.IntegerField() active = models.BooleanField(default=True) cart>urls urlpatterns = [' path('cartDetails', views.cart_details, name='cartDetails'), path('add/<int:product_id>/', views.add_cart, name='addcart'), ] cart.html <tr> {% for i in ci %} <td><a href="#"><img src="{{i.prodt.img.url}}" alt="img"></a></td> <td><a class="aa-cart-title" href="#">{{ i.prodt.name }}</a></td> <td>${{ i.prodt.price }}</td> {% endfor %} <tr> this is the cart page to get the view code has some mistakes, while adding the products the create the cart id and then the products are added but which is not shown in the chart HTML page -
Django Auth with Nginx works with Postman but not with Axios
I am using the default auth system from django (served with gunicorn and nginx) and it is working fine when I try the requests with Postman, but when I try the same requests from the browser with Axios. It seems that django receives the headers properly when the request comes from Postman, but when the request come from the browser/axios the header is incomplete. Thus, the user is never logged in after login in browser/axios. Header received by django from postman: {'Host': 'SERVER_NAME', 'X-Real-Ip': 'REAL_IP', 'X-Forwarded-For': 'IP', 'X-Forwarded-Proto': 'http', 'Connection': 'close', 'User-Agent': 'PostmanRuntime/7.29.0', 'Accept': '*/*', 'Postman-Token': '9342a13d-1db9-4c38-bbd9-0c66fd8ac727', 'Accept-Encoding': 'gzip, deflate, br', 'Cookie': 'csrftoken=CSRFTOKEN; sessionid=SESSIONID'} Header received by django from axios: {'Host': 'SERVER_NAME', 'X-Real-Ip': 'REAL_IP', 'X-Forwarded-For': 'ip', 'X-Forwarded-Proto': 'http', 'Connection': 'close', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip, deflate', 'Access-Control-Allow-Origin': 'true', 'Origin': 'http://localhost:8080', 'Referer': 'http://localhost:8080/', 'Cache-Control': 'max-age=0'} My nginx config is: server { listen 80; server_name SERVER_NAME; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/plataforma/backend/plataforma-back-end/pvanalytics_backend; } location / { include proxy_params; proxy_pass http://unix:/home/plataforma/backend.sock; proxy_set_header HTTP_Country-Code $geoip_country_code; proxy_pass_request_headers on; } } -
I want to calculate percentage in template with django
I want to calculate and show the discount interest of the product in the template. I tried something like below but it didn't work. Is there a practical way to do this? index.html {% if product.sale %} <span class="sale">{{((product.price - product.sale) / product.price) * 100}}</span> {% endif %} -
Personalizations field error when sending multiple dynamic template emails in sendgrid
I'm trying to send a bulk email using Sendgrid Dynamic Templates in Django and getting this error: The personalizations field is required and must have at least one personalization. Using sendgrid 6.9.7 Does anyone see where I might be going wrong: from django.conf import settings from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, To def send_mass_email(): to_emails = [ To(email='email1@gmail.com', dynamic_template_data={ "thing_i_want_personalized": 'hello email 1', }), To(email='email2@gmail.com', dynamic_template_data={ "thing_i_want_personalized": 'hello email 2', }), ] msg = Mail( from_email='notifications@mysite.com>', ) msg.to_emails = to_emails msg.is_multiple = True msg.template_id = "d-template_id" try: sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sendgrid_client.send(msg) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e) print(e.body) return The output is HTTP Error 400: Bad Request b'{"errors":[{"message":"The personalizations field is required and must have at least one personalization.","field":"personalizations","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Personalizations-Errors"}]}' -
Modeling frontend and backend in a use case diagram
I am trying to make a use case diagram for my project, the backend is going to be made using Django rest framework and the front end using react, my question is how can i model this situation in the right way, should i model the frontend and represent the backend as an actor or the opposite, since i am thinking of making a mobile application as a second front end? -
Problem trying to add my individual products to cart
I have created a button on my webpage, I want to add my individual product to a shopping basket when I press this button, but for some reason I am getting the following error: productindividual?id=1:117 POST http://127.0.0.1:8000/apiadd/ 500 (Internal Server Error) addToCart.onclick @ productindividual?id=1:117 VM4764:1 Uncaught (in promise) SyntaxError: Unexpected token I in JSON at position 0 Promise.then (async) addToCart.onclick @ productindividual?id=1:129 Below is my code: <script> window.onload = ()=>{ let params = window.location.search; let urlParams = new URLSearchParams(params); let productID = urlParams.get("id"); // http://127.0.0.1:8000/api/products/id if(productID != null && typeof(productID)!= 'undefined'){ fetch('http://127.0.0.1:8000/api/products/'+productID) .then(resp => resp.json()) .then(data => { console.log(data); if('detail' in data){ // display some generic product not found error alert("Product Not Found!"); } else{ let name = data['name']; let desc = data['description']; let price = data['price']; let image= data['image']; // display the product data let specific1Tag = document.getElementById("myname"); // returns the specific DOM node , the P tag with id="myparagraphid" specific1Tag.innerHTML=name; let specific2Tag = document.getElementById("mydesc"); // returns the specific DOM node , the P tag with id="myparagraphid" specific2Tag.innerHTML=desc; let specific3Tag = document.getElementById("myprice"); // returns the specific DOM node , the P tag with id="myparagraphid" specific3Tag.innerHTML=price; let specific4Tag = document.getElementById("myimg"); // returns the specific DOM node , the P tag … -
django async/background for long running task
I have a django app with an endpoint that kicks off a long running task. I want to do this in the background. I know I could do this with celery or django-q, but I wanted to try something simpler first. First thing I tried was ajax. In the python code I did this: cookie = request.META.get('HTTP_COOKIE') csrf_cookie = request.META.get('CSRF_COOKIE') host = '{}://{}'.format(request.scheme, request.META['HTTP_HOST']) data = {...} resp = requests.post('{}/report/TASKS/Work/ajax/run.json'.format(host), headers={'COOKIE': cookie, 'X-CSRFToken': csrf_cookie, 'referer': host}, data=data) The function being called has the @login_required decorator, and when that runs it does the auth as the anonymous user, which fails so it redirects to the login page. The thread sending in the request is logged in and I have verified the cookies are all correct. Why would it use the anonymous user? How can I get it to auth using the logged in user? Tried something else next - instead of using ajax I call it with multiprocessing.Process. This fails because the thread does not have a database connection. Anyone have any thought on how I could make this work? -
Deploying Django API on Heroku- after changing DEBUG = False (in settings.py) and deploying my app, URLconf defined in URLS.PY are not listed
I have created Django API with three apps (users, task, house) with with help of routers show data in ViewSets. Some of these routers have to register multiple ViewSets. When testing endpoints both locally and on remote server (Heroku gunicorn) they are working. As app should be deployed in DEBUG=False mode, when I changed that in settings.py I came across a problem.! I changed DEBUG=False as expected to be on a live server. When I entred domain name generated by Heroku, I got message ::::: Not Found – The requested resource was not found on this server. I tried to enter endpoints manually (domain_name/endpoint) and it worked. Obviously I do not have anything under path(' ', include(...............)) as there is no priority for any of the three apps. I you have any idea/suggesting on how to get listed URLS admin/, api/ as on local server please let me know. Many thanks in advance. -
UnboundLocalError in django while passing an sql query
This is my error message: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/mainpage.html Django Version: 3.2.12 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware') Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\desktop\dentist\website\views.py", line 40, in mainpage c.execute(query) Exception Type: UnboundLocalError at /mainpage.html Exception Value: local variable 'query' referenced before assignment This is my python views.py def logout(request): try: del request.session['your-email'] except KeyError: pass result_dict = {} result_dict['logout_success'] = 'See you next time! You have sucessfuly logged out' return render(request, 'home.html', result_dict) def mainpage(request): if 'your-email' not in request.session: if request.method == "POST": email = request.POST['your-email'] password = request.POST['your-password'] if email!='' and password!='': verification = "SELECT * FROM users WHERE email = '" + email + "' AND password = '" + password + "';" c = connection.cursor() c.execute(verification) account_exist = c.fetchall() results_dict = {} if not account_exist: results_dict = {'error':'Please try again. Entered username or password is wrong'} return render(request, 'login.html',results_dict) request.session['your-email'] = email else: query = "SELECT email, display_name, age, phone_number, vaccination_status, rating, count_rate FROM users … -
Django Python: Get the uploaded file name and add it to the body of the email message
This question is different than how to get uploaded file name in django as I need to add the file name to the body of the email message, and since all my email post and file upload code is in views.py, I'm not using a models.py file. How do I get the uploaded file name file and add it to the message part f'{form_data["message"]}' of the email? I'm not attaching the file to the email; I'm simply uploading it to the server via the forms.py. But I need to add the file name in the body of the email so I know which file has been uploaded by which email user. I am also aware that Django adds a random string of characters to the uploaded file name if it sees an existing file with the same name n the upload directory, so in that case, I need that file name included. Is that handled by file? views.py import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from django.shortcuts import render, get_object_or_404, redirect from django.core.files.storage import FileSystemStorage from contactform.forms import ContactForm from contact.settings import EMAIL_HOST_USER, EMAIL_PORT, EMAIL_HOST_PASSWORD, EMAIL_HOST def thanks(request): return render(request, 'thanks.html', {}) def contact(request): if request.method == … -
Python Django how to save many to one relationship JSON data in sqlite
I was wondering how I should go about saving data items in tables which have a many to one relationship with a model Here is the code that I got so far: models.py: class Recipes(models.Model): name = models.CharField(max_length=120, default='') pub_date = models.DateTimeField('date published') style = models.CharField(max_length=200, default='') brewer = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='All Grain') version = models.CharField(max_length=20, default='1') batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0) ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) notes = models.TextField(default='') carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) __fermentables = [] @classmethod def create(cls,attr): recipe = cls() # do something with the book for k in Recipes._meta.fields: if k.name in attr: setattr(recipe,k.name,attr[k.name]) return recipe @classmethod def addFermentables(self,items): for itm in items: self.__fermentables.append(itm) return self.__fermentables @classmethod def addHops(self,items): for i in items: return i class RecipeFermentable(models.Model): recipe = models.ForeignKey(Recipes, on_delete=models.CASCADE) name = models.CharField(max_length=200, default='') amount = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) extract = models.DecimalField(decimal_places=1, max_digits=8, default=0.0) type = models.CharField(max_length=20, default='') color= models.DecimalField(decimal_places=1, max_digits=8, default=0.0) fermentable = models.ForeignKey(Fermentable, on_delete=models.RESTRICT) def create(cls, attr, recipes): … -
How to append a list of users emails linked with a manytomany relation to other Model
First please take a look on the data structure. there are Three models class Partner(models.Model): name = models.CharField(max_length=100, blank=True, null=True) group = models.OneToOneField( Group, on_delete=models.DO_NOTHING, blank=True, null=True) class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) partner = models.ManyToManyField( Partner, blank=True) class Quote(models.Model): partner = models.ManyToManyField( Partner, blank=True, related_name='quote_partners') There can be multiple partners inside the Quote and CustomUser partner field. I want to make a list of users email who are linked with Partner inside the partner field set in the quote model. This is how I'm doing; quote = Quote.objects.get(id=id) partners = quote.partner.all() for partner in partners: recipient_list = [] for user in CustomUser.objects.filter(groups__partner=partner): recipient_list.append(user.email) Currently quote object has 3 partners and collectively 4 users linked to these partners then there should be 4 emails in the the recipient_list, But this returning empty array []. Please highlight what I'm doing wrong and how to fix it. -
Database name is longer than PostgreSQL's limit of 63 characters. How to Fix it?
I am beginner in Django. I created a database on using postgresql but facing problem when try to makenigration. in my Settings.py 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.path.join(BASE_DIR,'Data_Collection'), 'USER': 'postgres', 'PASSWORD' : '1234', 'HOST': 'localhost', } } when I try to run this command python manage.py makemigrations Im seeing following error/issue: django.core.exceptions.ImproperlyConfigured: The database name 'D:\Masters_FIT\4th\Webdatabese\Project\Code\Data_Collection\Data_Collection' (75 characters) is longer than PostgreSQL's limit of 63 characters. Supply a shorter NAME in settings.DATABASES. If i do changing in my setting then connection is not establishing.. Setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Data_Collection', 'USER': 'postgres', 'PASSWORD' : '1234', 'HOST': 'localhost', } } Then in get_new_connection connection = Database.connect(**conn_params) File "D:\Masters_FIT\4th\Webdatabese\Project\Code\data\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? Kinldy someone tell me how to fix it. Thank you -
IntegrityError duplicate key value violates unique constraint
I found this solution on how to fix the problem I was running into: SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1) but I am not familar with SQL statements so I don't understand what to replace the names with here. My table name is "student_course" so I assume that is what goes in tablename, but I do not understand what to do for the 'tablename_id_seq'. The error is occuring at "student_course_id_key", is that what I put for the id seq?