Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my background picture is not loading in my webite?
this one is snipsets of my css file body { background-image: url(../img/backgroung.jpg); color: #333333; margin-top: 5rem; } this one is my settings.py file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'blog-home' LOGIN_URL = 'login' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('DB_USER') EMAIL_HOST_PASSWORD = os.environ.get('DB_PASSWORD') this one is my base.html file <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css" integrity="sha384- SI27wrMjH3ZZ89r4o+fGIJtnzkAnFs3E4qz9DIYioCQ5l9Rd/7UAa8DHcaL8jkWt" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'stripes_blog/main.css' %}"> {% if title %} <title> STRIPES - {{ title }} </title> {% else %} <title> STRIPES </title> {% endif %} </head> I tried everything and still it's not working, i don't know where am i lacking behind. -
TypeError: 'method' object is not subscriptable Python/django
I have a test case that is returning the following error. Traceback Traceback (most recent call last): File "/usr/lib/python3.7/unittest/mock.py", line 1255, in patched return func(*args, **keywargs) File "/dir/to/project/Anwser/qanda/tests.py", line 29, in test_elasticsearch_upsert_on_save q.save() File "/dir/to/project/Anwser/qanda/models.py", line 40, in save elasticsearch.upsert(self) File "/dir/to/project/Anwser/qanda/service/elasticsearch.py", line 54, in upsert doc_type = question_dict['_type'] TypeError: 'method' object is not subscriptable Here is the function that lives inside elasticsearch.py def upsert(question_model): client = get_client() question_dict = question_model.as_elastic_search_dict doc_type = question_dict['_type'] del question_dict['_id'] del question_dict['_type'] response = client.update( settings.ES_IDENX, question_dict, id=question_model.id, body={ 'doc': doc_type, 'doc_as_upsert': True, } ) return response As i have read other threads about similar issues, i came to a conclusion that the problem relies in __getItem(self)__ of the object that is calling the function. Since the function should return a dictionary, it returns a method instead. Here is the function inside of model. def as_elastic_search_dict(self): return { '_id': self.id, '_type': 'doc', 'text': '{}\n{}'.format(self.title, self.question), 'question_body': self.question, 'title': self.title, 'id': self.id, 'created': self.created, } TestCase: class QuestionSaveTestCase(TestCase): """ Testing Question.save() """ @patch('qanda.service.elasticsearch.Elasticsearch') def test_elasticsearch_upsert_on_save(self, ElasticSearchMock): user = User.objects.create( username='unittest', password='unittest' ) question_title = 'Unit test' question_body = 'Some unit test' q = Question(title=question_title, question=question_body, user=user) q.save() self.assertIsNotNone(q.id) self.assertTrue(ElasticSearchMock.called) mock_client = ElasticSearchMock.return_value mock_client.update.assert_called_once_with( settings.ES_IDENX, id=q.id, … -
Can I get all flags, switches and samples in django waffle in one call?
I need to get all configured properties in the user context. I was wondering if there was a more efficient way of getting all of them at once, the documentation of waffle didn't seem to mention any such facility -
Every day reset a field to "0"
I need that every day at 00:00am, reset a studied_today field to 0. original code: models.py from django.db import models from django.conf import settings class Studied(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) studied_today = models.IntegerField(default=0) def __str__(self): return self.collection.title I try it: $ pip install schedule after, I change the original code: from django.db import models from django.conf import settings import schedule class Subscription(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) studied_today = models.IntegerField(default=0) def __str__(self): return self.collection.title def job(): studied_today = 0 schedule.every().day.at("00:00").do(job) What did I do wrong and how can I do this? Any suggestion? -
How to custom folder structure in django using unipath library
enter image description here import os,sys from unipath import Path Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) PROJECT_DIR = Path(file).ancestor(2) PROJECT_APPS = Path(file).ancestor(2) sys.path.insert(0, Path(PROJECT_APPS, 'apps')) -
Grading System in Django
Is there any Source code in Django that the teachers gives grade to their students? please send link. cause I am now done in file maintenance in admin site, and now I am doing teacher user where the teacher will give grades to their students this is the model of file maintenance class configuration(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Description = models.CharField(max_length=500, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def __str__(self): suser = '{0.Description}' return suser.format(self) class gradeScalesSetting(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] configuration_select = models.ForeignKey(configuration, related_name='+', on_delete=models.CASCADE, null=True) NumberOfGrades = models.IntegerField(blank=True, null=True) Rounding = models.CharField(max_length=500, null=True) Precision = models.IntegerField() Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def __str__(self): suser = '{0.configuration_select}' return suser.format(self) class gradescale(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] configuration_select = models.ForeignKey(configuration, related_name='+', on_delete=models.CASCADE, null=True) Display_Sequence = models.IntegerField() Symbol = models.CharField(max_length=500, null=True) LowerLimit = models.FloatField() GPAValue = models.FloatField() Description = models.CharField(max_length=500, blank=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def __str__(self): suser = '{0.Description}' return suser.format(self) class gradingCategories(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Display_Sequence = models.IntegerField() CategoryName = models.CharField(max_length=500, null=True) PercentageWeight = models.FloatField() Calendar = models.BooleanField(null=True, blank=True) MaximumItemsPerPeriod = models.IntegerField(blank=True, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def … -
Heroku seems to be stripping out the JSON from POST requests
I can run my code locally and it works just as I want, but when I run it in Heroku it returns NoneTypes for everything and seems like it has no data in the request. from django.shortcuts import render from rest_framework import generics from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.decorators import api_view import psycopg2 @api_view(['GET', 'POST']) def testVert(request): user = request.data.get('username') password = request.data.get('password') response = { "user": user, "pass": password } return Response(data=response) #request.readline() The readline also works on my local computer, but not on Heroku. I'm wondering if maybe there are some Heroku settings or if I need to look for the data elsewhere after it goes through Heroku's stuff. Thanks for any help! -
django how to show list of category in blog and by clicking category show specific list of category
I have tried many ways i am new to django, but i couldn't able to solve that show list of specific category post from category section in html slider this how actually i wanted and clicking go to desire list of category post i did able to go to category list from post category but **couldn't able to go from category slider in index page ** how can i do that this style is working to go specific category but i also wanted do like above image models.py class Category(models.Model): title = models.CharField(max_length=20) thumbnail = models.ImageField() detail = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-category', kwargs={ 'pk': self.pk }) class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() featured = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) #content = HTMLField() user = models.ForeignKey(Author,on_delete=models.CASCADE) thumbnail = models.ImageField() category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title views.py class IndexView(TemplateView): model = Post model = Recipe model = Category template_name = 'shit.html' context_object_name = 'queryset' def get_context_data(self, **kwargs): recents = Post.objects.order_by('-timestamp')[0:4] recipe = Recipe.objects.filter()[0:2] category = Category.objects.all()[0:4] context = super().get_context_data(**kwargs) context['recents'] = recents context['recipe'] = recipe context['category'] = category return context class PostCategory(ListView): model = Post template_name = 'cat.html' def get_queryset(self): self.category = get_object_or_404(Category, pk=self.kwargs['pk']) … -
How to show popup "Success" or "Error" after I clicked the update button in which it is a modal
I am working on this employee registration project and Im not exactly sure how to implement this one on django. How could I show popupbox or like a small modal box "Success" or "Error" after I clicked the update button? It would be success if they have input all the necessary details on the modal. And error if they forgot to enter some details. Here is the views.py def save_employee_update(request): print(request.POST) emp_id = request.POST['employee_id'] fname = request.POST['first_name'] midname = request.POST['middle_name'] lname = request.POST['last_name'] pr_address = request.POST['present_address'] pm_address = request.POST['permanent_address'] zcode = request.POST['zipcode'] bday = request.POST['birthday'] email = request.POST['email_address'] pagibig = request.POST['pagibig_id'] sss = request.POST['sss_id'] tin = request.POST['tin_id'] sg_pr_id = request.POST['solo_parental_id'] # rg_sched = request.POST['reg_schedule'] usid = request.POST['userid'] defpass = request.POST['default_pass'] ustype = request.POST['user_type'] # j_title = request.POST['JobTitle'] employee = Employee.objects.get(employee_id=emp_id) employee.first_name = fname employee.middle_name = midname employee.last_name = lname employee.present_address = pr_address employee.permanent_address = pm_address employee.zipcode = zcode employee.birthday = bday employee.email_address = email employee.pagibig_id = pagibig employee.sss_id = sss employee.tin_id = tin employee.solo_parental_id = sg_pr_id # employee.reg_schedule = rg_sched employee.userid = usid employee.default_pass = defpass employee.user_type = ustype # employee.JobTitle = j_title employee.save() return render(request, 'index.html') Here is the modal <!-- Modal --> <div class="modal fade" id="employee.employee_id_{{ employee.employee_id }}" … -
Unable to connect to cloudamqp
I’m using python pika to connect to RabbitMQ but I keep getting an error: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it My configuration is: am_url = 'amqp://xxxxxx:xxxxxxxxx@xxxxxx.rmq.cloudamqp.com/xxxxxxxx' url = os.environ.get('CLOUDAMQP_URL', am_url) params = pika.URLParameters(url) connection = pika.BlockingConnection(params) Am I configuring it wrong? -
django oauth toolkit with python social auth for android user from social platform
So i am using django-oauth-toolkit in order to provide oauth2 authentication for my android application. Now i have to implement social(facebook, google) authentication. And my workflow should be like when user hits signup with facebook button it does authorize successfully thanks to python social auth. So as it is supposed to be, python social auth does create user and it is fine. Now, this case works fine on side of web user. Problem is how can i handle android user tries to login with facebook?, Do i have to pass facebook authorization token to oauth toolkit? -
webpack font names rename to new name and in browser get not found error
I am using webpack with Django. in my .scss file: @font-face { font-family: 'Lato'; src: url(fonts/lato/Lato-Regular.ttf) format('truetype'); } @font-face { font-family: 'Lato Black'; src: url(fonts/lato/Lato-Black.ttf) format('truetype'); } after it in console: 06e1c8dbe641dd9dfa4367dc2a6efb9f.ttf 586 KiB [emitted] 3b0cd7254b3b6ddb8a313d41573fda8b.ttf 600 KiB [emitted] 6d4e78225df0cfd5fe1bf3e8547fefe4.ttf 593 KiB [emitted] 72c6dd530f0acc74b5286a7dcfa9e2d8.ttf 589 KiB [emitted] a54bddbc1689d05277d2127f58589917.ttf 570 KiB [emitted] bundle.js 595 KiB main [emitted] main and finally in the browser, I am getting an error like this: test_page:1 GET http://127.0.0.1:8000/static/b23d682ec78893e5b4598ecd6dfb1030.ttf net::ERR_ABORTED 404 (Not Found) -
How can I create a working production build for my django-rest site?
I've been running yarn build, but when I visit index.html I see not only <noscript>You need to enable JavaScript to run this app.</noscript>, but when I click a link on that page, I find that the pathing does not work. For example, when I click a link that would take me to a sign up page, I just get Your file was not found. The URLs are clearly different between the two pages, one being file:///C:/Users/icant/GitProjects/moodzaic/moodzaic_django/assets/bundles/index.html and the other just being file:///C:/signup. I want to say that something in production_settings.py needs to be changed, but some pointers would be appreciated~ -
How to parse request.body into json in django
When I use Postman to send a post request to my django server, I receive request.body like user=abc&pwd=123, not like a json And when I use my android app to send a post request to my django server, I also receive the request.body like user=abc&pwd=123 How can I parse this kind of format like user=abc&pwd=123 into json in python? -
django remote user (trusted connection on IIS)
I set up django for a trusted connection (remote user) on IIS but on the client side, it is always asking for the user to type the username and password on a pop up alert from browser. Does anyone knows how can I solve it? See the screenshot from the browser below: -
How to use Facebook's picture api in django template?
I got back {"picture": {"data": {"height": 50, "is_silhouette": false, "url": "https://platform-lookaside.fbsbx.com/platform/profilepic/foo", "width": 50}} from facebook api call but in my template for django I tried using <img src = "{{object.picture.data.url}}"> And nothing is showing up. The other fields works fine for the first_name and last_name but I couldn't get why it doesn't work D: -
django error cannot import name 'RemovedInDjango30Warning'
Guys im fairly new to Django and I just started working on a personal project and decided that ill-use pycharm (i think its related to the error, or not). when I run python manage.py runserverI get the error posted below. I did a bit of googling and looks like its caused by inconsistency with Django versions. I currently have Django 3.0 and I checked both globally and in the venv. I tried to start a project outside of py charm and im running into the same issue. idk what I need to do to start using Django again. Did anyone run into this? Is this because of pycharm? If so what can I do to fix the issue? (venv) aiden@aiden-XPS-15-9570:~/PycharmProjects/NewsAggregator$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/aiden/.local/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/aiden/.local/lib/python3.6/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen … -
Django + VueJS: POST 403 Forbidden - CSRF token missing or incorrect
I am running Django + Django REST framework in the backend and Vue.js in the frontend. GET requests work fine, POST requests via Postman/Insomnia also do, but POST requests via the Vue.js frontend return an error in the Browser console: POST http://127.0.0.1:8000/api/questions/ 403 (Forbidden) {detail: "CSRF Failed: CSRF token missing or incorrect."} This is how I get the CSRF token and then fetch a POST request: File: csrf_token.js: import Cookies from "js-cookie"; var CSRF_TOKEN = Cookies.get("csrftoken"); export { CSRF_TOKEN }; File: api.service.js: import CSRF_TOKEN from "./csrf_token.js"; async function getJSON(response) { if (response.status === 204) return ""; return response.json(); } function apiService(endpoint, method, data) { const config = { credentials: "same-origin", method: method || "GET", body: data !== undefined ? JSON.stringify(data) : null, headers: { "content-type": "application/json", "X-CSRFToken": CSRF_TOKEN } }; return fetch(endpoint, config) .then(getJSON) .catch(error => console.log(error)); } export { apiService }; MyComponent.vue: ... methods: { onSubmit() { apiService(endpoint, method, { content: this.content }) .then(response_content => { console.log(response_content) }); } } ... -
Can't install mysqlclient via pip on macOS Mojave 10.14.6
There are several related questions and answers on this topic. One would think I'd have found a solution in the several hours I've been trying to resolve this, but no luck. Installs fine in Ubuntu and WSL. Starting from scratch, this is what I've done (in a Python 3 venv): pip install mysqlclient As expected, this generates a lengthy error that can be abbreviated as: OSError: mysql_config not found brew install mysql so the mysql_config is "foundable" export PATH=$PATH:/usr/local/mysql/bin source ~/.bash_profile Try pip install mysqlclient again Another lengthy error where it isn't quite as clear to the cause, but it looks like it has to do with ld: library not found for -lssl: Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/work/Projects/current/testapp/testappclient/.venv/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/df/092qy_7d0tdd_gg_l0wdj_vc0000gp/T/pip-install-0_hdtx9z/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/df/092qy_7d0tdd_gg_l0wdj_vc0000gp/T/pip-install-0_hdtx9z/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/df/092qy_7d0tdd_gg_l0wdj_vc0000gp/T/pip-wheel-91u90oa5 --python-tag cp37 cwd: /private/var/folders/df/092qy_7d0tdd_gg_l0wdj_vc0000gp/T/pip-install-0_hdtx9z/mysqlclient/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.14-x86_64-3.7 creating build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying … -
settings.Database improperly configured. switching to psql from sqlite
Getting this error - ImproperlyConfigured at /boards/ settings.DATABASES is improperly configured. Please supply the NAME value. DATABASES {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'localhost', 'NAME': '', 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': ''}} I'm using dj_database_url, DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } I was having some errors when my production db is psql and my dev is sqlite - so i figured i'd make it all psql. I copied my .env from prod to the local, and i think i messed up there. it currently looks like: DATABASE_URL=postgres://test:test@localhost:5432/test ALLOWED_HOSTS=.localhost,127.0.0.1 No idea what to do from here. I'm definitely missing something that's probably obvious. -
Django Rest Framework TypeError a bytes-like object is required, not 'str'
I have created a Rest Api with DRF. Everything works fine, but one resource (shoppingListItems) always throws this error: TypeError at /v1/shoppingListItems/ a bytes-like object is required, not 'str' Request Method: GET Request URL: http://localhost:8000/v1/shoppingListItems/ Django Version: 2.2.7 Exception Type: TypeError Exception Value: a bytes-like object is required, not 'str' The problem only occurs, if one or more items are matched. If the resultset is empty there is no error. Here's my views.py: class ShoppingListViewSet(viewsets.ModelViewSet): queryset = ShoppingList.objects.all() serializer_class = ShoppingListSerializer class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer class ShoppingListItemViewSet(viewsets.ModelViewSet): queryset = ShoppingListItem.objects.all() serializer_class = ShoppingListItemSerializer Here's my models.py: class Item(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) def __str__(self): return self.name class ShoppingList(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) members = models.ManyToManyField(User, through='Membership') items = models.ManyToManyField(Item, through='ShoppingListItem') def __str__(self): return self.name class ShoppingListItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) shoppinglist = models.ForeignKey(ShoppingList, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) amount = models.IntegerField() price = models.FloatField(null=True) status = models.BinaryField() Here's my serializers.py: class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Item fields = ['id', 'name'] class ShoppingListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ShoppingList fields = ['id', 'name', 'members'] class ShoppingListItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ShoppingListItem fields = ['id', 'shoppinglist', 'item', 'amount', 'price', … -
Django: trouble adjusting stock when an order is cancelled
So in my website when a user cancels an order I want the stock of the products that the user has bought to be brought back up, but whenever I test it the stock remains the same (But successfully decreases when a user buys something). The function I am trying to do this with is adjust_stock in order/views.py as follows: from django.shortcuts import render, get_object_or_404, redirect from .models import OrderItem, Order from cart.models import Cart, CartItem from cart.views import _cart_id from shop.models import Product from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.decorators import login_required from datetime import datetime, timezone from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, InvalidPage import stripe @login_required() def order_create(request, total=0, cart_items = None): if request.method == 'POST': cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart) for item in cart_items: total += (item.quantity * item.product.price) print('Total', total) charge = stripe.Charge.create( amount=str(int(total*100)), currency='EUR', description = 'Credit card charge', source=request.POST['stripeToken'] ) if request.user.is_authenticated: email = str(request.user.email) order_details = Order.objects.create(emailAddress = email) order_details.save() try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart) for order_item in cart_items: oi = OrderItem.objects.create( product = order_item.product.name, quantity = order_item.quantity, price = order_item.product.price, order = order_details) total += (order_item.quantity * order_item.product.price) oi.save() #Reduce stock when order is placed or saved … -
getting error while running django==1.11 in atom text editor
the following error it is throwing (newenv) PS C:\Users\priyaratnam\Desktop\example\protwo> py manage.py startapp apptwo Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\core\management__init__.py", line 363, in execute _from_command_line File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module> File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\filters.py", line 10, in <module> from django.contrib.admin.options import IncorrectLookupParameters File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\options.py", line 12, in <module> from django.contrib.admin import helpers, widgets File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\widgets.py", line 151`enter code here` '%s=%s' % (k, v) for k, v in params.items(), ^ SyntaxError: Generator expression must be parenthesized -
Nginx 502 Bad Gateway after a Site Update - How to Resolve?
I updated my site, which is on a DO droplet, restarted gunicorn and nginx, and now I'm getting a 502 bad gateway error. I ran sudo tail -30 /var/log/nginx/error.log and here is the output: 2019/12/02 22:01:32 [crit] 24429#24429: *1 connect() to unix:/home/jake/mysite-main/mysite.sock failed (2: No such file or directory) while connecting to upstream, client: 198.85.222.158, server: 165.22.38.243, request: "GET / HTTP/1.1", upstream: "http://unix:/home/jake/mysite-main/mysite.sock:/", host: "www.mysite.com" 2019/12/02 22:02:44 [crit] 24466#24466: *1 connect() to unix:/home/jake/mysite-main/mysite.sock failed (2: No such file or directory) while connecting to upstream, client: 198.85.222.158, server: 165.22.38.243, request: "GET / HTTP/1.1", upstream: "http://unix:/home/jake/mysite-main/mysite.sock:/", host: "www.mysite.com" What are the best next steps? Thanks for any advice, I've been Googling and still haven't found the solution. -
Django Auto generate 10 digit unique number
So i been trying to generate 10 digit unique random number in django model without making it my primary key. My model is Class Transaction(models.Model): Referrence_Number = models.Charfield(max_lenght = 10, blank=True, editable=False, unique=True) I know that Django has special feature inside it to generate random string that i came to know after reading documentation. from django.utils.crypto import get_random_string get_random_string(10).lower() But my problem is how can i incorporate this get_random_string function inside my django transaction model in my Transcation_number Instance. I m actually new to django and cant able to figure it that out.