Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extremely slow Oauth authentication django-allauth
when I am trying to do sign up: Keeping email verification = "mandatory", via Github it is taking approximate 3-10 minutes for the callback url to load. via email / password sign up, it is taking 3-10 minutes for the url "after" the sign up button to load. Keeping email verification = "none", via Github it is taking approximate 3-10 minutes for the callback url to load. via email / password sign up is happening smoothly. Following are the code files: settings.py: Django settings for config project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-xc-592)no)((2&6grj56rfw$um58(cd(+0zvs2f=ar0wq6&@0=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # new 'userlogin', 'allauth', # new 'allauth.account', # new 'allauth.socialaccount', # … -
Django coverage doesn't cover APITestCase tests
I have a relatively large Django + DRF project with over 400 tests, but I fail to get coverage metrics of over 40%. Here are the results after running tests. From my understanding, there could be a few sources of issues here: (1) The directory structure of our application is weird We've tinkered a bit with our directory structure, here is what it looks like today: core_app - apis - businessapi - models - migrations - serializers - views - tests - business_tests.py - admin.py - urls.py - apps.py - __init__.py - userapi - transactionapi - ... - settings - production.py - celery_apps - ... - ... and here is what our business_tess.py file looks like: class TestBusiness(APITestCase): def setUp(self): self.businessA = BusinessFactory(...) self.businessB = BusinessFactory(...) self.primary_adminA = ProfileFactory(...) self.primary_adminB = ProfileFactory(...) # Create 10 spenders self.spendersA = ProfileFactory.create_batch(...) self.spendersB = ProfileFactory.create_batch(...) # Create 5 admins self.adminsA = ProfileFactory.create_batch(...) self.adminsB = ProfileFactory.create_batch(...) # Authorize self.primary_admin_client = APIClient() self.primary_admin_client.credentials(Accept="application/json") self.primary_admin_client.force_authenticate(self.primary_adminA) ... def test_business_permissions(self): expected_response = {...} sorted_expected = OrderedDict(sorted(expected_response.items())) # Try to access as primaryadmin _, client = authenticate_user(self.primary_adminA.id) response = client.get("url_to_test") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), sorted_expected) (2) Coverage doesn't pick up tests that are accessed through API calls I personally don't … -
manage.py and docker-compose in different directories?
I am no expert with docker and what I want to do I think should not be hard, I simply way to be able to run manage.py commands having my docker-compose in different directory and NOT specifying the location of manage.py when im rnning the command. So right now I have a directory that has a the docker-compose.yml and a folder called backend where the manage.py file is. I just want to be able to run docker-compose run --rm web python3 manage.py instead of docker-compose run --rm web python3 backend/manage.py How can I do it? -
Why is my log file not outputting my debug messages? (Django)
When I have my server locally output a log it works, but when I upload to the live environment I only see major errors and the selection of tables in my DB. Logging code in my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'debug.log'), }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } My views.py: def home(request): log = logging.getLogger('django') log.debug('test') return render(request, 'qit/index.html') debug.log output: (0.001) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1; args=(1,) (0.001) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2021-05-16T00:07:46.570887+00:00'::timestamptz AND "django_session"."session_key" = 'mn3oumf41ryqi9h7v9n3g33isk0hoxsk'); args=(datetime.datetime(2021, 5, 16, 0, 7, 46, 570887, tzinfo=<UTC>), 'mn3oumf41ryqi9h7v9n3g33isk0hoxsk') (0.001) SELECT "qit_queue"."id", "qit_queue"."owner_id", "qit_queue"."queue_string", "qit_queue"."name_string", "qit_queue"."anon_string", "qit_queue"."thumbnail_string", "qit_queue"."invite_code", "qit_queue"."password" FROM "qit_queue" WHERE "qit_queue"."invite_code" = 'esMou'; args=('esMou',) (0.001) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2021-05-16T00:07:57.077838+00:00'::timestamptz AND "django_session"."session_key" = 'mn3oumf41ryqi9h7v9n3g33isk0hoxsk'); args=(datetime.datetime(2021, 5, 16, 0, 7, 57, 77838, tzinfo=<UTC>), 'mn3oumf41ryqi9h7v9n3g33isk0hoxsk') (0.001) SELECT "qit_queue"."id", "qit_queue"."owner_id", "qit_queue"."queue_string", "qit_queue"."name_string", "qit_queue"."anon_string", "qit_queue"."thumbnail_string", "qit_queue"."invite_code", "qit_queue"."password" FROM "qit_queue" WHERE "qit_queue"."invite_code" = 'esMou'; args=('esMou',) Unfortunately the test does not show up on my debug.log file. If anyone has any … -
Automatically adding html in Django
I am making use of the {% extends 'core/base.html %} tag to include a header. I write this on the beginning line of each page I create so that it loads a navigation bar and other static files. Is there a way to not write the extends functionality on each page I create and instead it is injected automatically each time I create a page? -
sort dict of list based on max of values in list
I several models (ModelB, ModelC, ....) that have last_updated fields in all of them. They also share id values between them. So if I retrieve id=11, it will have last_updated values for each of the Models. I am trying to sort the id (and associated dict/list) according to the most recent last_updated value in each id. How I am getting the initial id ids = ModelA.objects.values_list('id', flat=True).filter(u=val1) ids returns <QuerySet [11, 12, 13, 14]> How I'm getting last_updated for each of the models updates = {} for i in ids: updates[i] = [] for my_models in (ModelB, ModelC): updates[i].append(my_models.objects.values_list('last_updated', flat=True).get(id=i)) Example output of updates { 11:[ datetime.datetime(2021, 5, 13, 17, 13, 15, 849356, tzinfo=<UTC>), datetime.datetime(2021, 5, 13, 19, 12, 24, 978689, tzinfo=<UTC>)], 12:[ datetime.datetime(2021, 5, 14, 0, 0, 4, 906100, tzinfo=<UTC>), datetime.datetime(2021, 5, 15, 0, 16, 20, 995024, tzinfo=<UTC>)], 13:[ datetime.datetime(2021, 5, 13, 3, 31, 14, 738902, tzinfo=<UTC>), datetime.datetime(2021, 5, 13, 2, 58, 0, 375691, tzinfo=<UTC>)], 14:[ datetime.datetime(2021, 5, 15, 19, 40, 24, 732034, tzinfo=<UTC>), datetime.datetime(2021, 5, 14, 0, 52, 27, 199480, tzinfo=<UTC>)] } How I'm selecting the max and sorting the ids based on the max datetime value. sort_ = {} for k in updates: sort_[k] = max(updates[k]) new_order … -
Django login not working even for django-admin
I know this question has been asked many times before but I am facing quit a unique satiation. My djagno project was working completely fine and I was able to login. But then I start working on django SSO so I had to install some cas packages and ran migrations. But then after some time I uninstall those packages and reset the project as it was before but when I tried to login I wasn't able to login, not even able to login to django admin section. I don't think there is a need of code snippet as I have some thing which was working before and not working now but to give you some idea about my login view. here is the code user = authenticate(request=request, username=request.POST['email'].lower().strip(), password=request.POST['password']) if user is None: return render_error('Sign in failed! Please try again.') else: login(request, user) # Redirect to 'next' url if it exists, otherwise index if 'next' in request.GET: return HttpResponseRedirect(request.GET['next']) -
Related object doesn't exist during _fixture_teardown using factory_boy in tests
I've setup a django test suite, using factory_boy to handle models. In tests where a related object is involved through a ForeignKey, I'm seeing an error suggesting that the related object doesn't exist during _fixture_teardown. And I can't understand why, given this is part of teardown. The error is; Traceback (most recent call last): File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/test/testcases.py", line 284, in _setup_and_call self._post_teardown() File "/Users/mwalker/Sites/consoles/project/tests/mixins.py", line 10, in _post_teardown super()._post_teardown() File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/test/testcases.py", line 1006, in _post_teardown self._fixture_teardown() File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/test/testcases.py", line 1248, in _fixture_teardown connections[db_name].check_constraints() File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 285, in check_constraints cursor.execute('SET CONSTRAINTS ALL IMMEDIATE') File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) django.db.utils.IntegrityError: insert or update on table "charity_listing" violates foreign key constraint "charity_listing_client_id_c3b74de6_fk_clients_client_id" DETAIL: Key (client_id)=(1) is not present in table "clients_client". So far, I'm only seeing this error from the Client table, but my tests are still very limited in scope. The failing test from the above error is; class ApplicationTest(TestCase): @classmethod def setUpTestData(cls): client = ClientFactory.create(name='Stackoverflow', enabled=True) listing … -
Initial dynamic data for django database
I want populate my database with initial data (dummy data). I have DateTimeFields in many models and for the DateTimeFields it would be good to have a variable in my fixtures files (json, yaml, xml). E.g.: now() + 7h, now() + 6d + 8h + 30m -
Heroku Database
Good day, I have a Django app that I hosted on Heroku with the codes from GitHub, it deployed fine and I have a domain, for instance myapp.herokuapp.com. But when I make some changes to the website itself, everything seems alright, then I make changes in the code and push it to GitHub. It deploys again perfectly, but all the former changes I made on the website get discarded, it now looks like a fresh deployed app. Auto-deploy from GitHub is enabled in my Heroku settings. how can I retain changes I make on the Heroku website after updating my code?? -
Django Channels Redis: Exception inside application: Lock is not acquired
Fully loaded multi-tenant Django application with 1000's of WebSockets using Daphne/Channels, running fine for a few months and suddenly tenants all calling it the support line the application running slow or outright hanging. Narrowed it down to WebSockets as HTTP REST API hits came through fast and error free. None of the application logs or OS logs indicate some issue, so only thing to go on is the exception noted below. It happened over and over again here and there throughout 2 days. Don't expect any deep debugging help, just some off-the-cuff advice on possibilities. Thanks. AWS Linux 1 Python 3..6.4 Elasticache Redis 5.0 channels==2.4.0 channels-redis==2.4.2 daphne==2.5.0 Django==2.2.13 Split configuration HTTP served by uwsgi, daphne serves asgi, Nginx May 10 08:08:16 prod-b-web1: [pid 15053] [version 119.5.10.5086] [tenant_id -] [domain_name -] [pathname /opt/releases/r119.5.10.5086/env/lib/python3.6/site-packages/daphne/server.py] [lineno 288] [priority ERROR] [funcname application_checker] [request_path -] [request_method -] [request_data -] [request_user -] [request_stack -] Exception inside application: Lock is not acquired. Traceback (most recent call last): File "/opt/releases/r119.5.10.5086/env/lib/python3.6/site-packages/channels_redis/core.py", line 435, in receive real_channel File "/opt/releases/r119.5.10.5086/env/lib/python3.6/site-packages/channels_redis/core.py", line 484, in receive_single await self.receive_clean_locks.acquire(channel_key) File "/opt/releases/r119.5.10.5086/env/lib/python3.6/site-packages/channels_redis/core.py", line 152, in acquire return await self.locks[channel].acquire() File "/opt/python3.6/lib/python3.6/asyncio/locks.py", line 176, in acquire yield from fut concurrent.futures._base.CancelledError During handling of the above exception, … -
how to stop videos from autostart in html
i m working on django where i need to show more than one video in one page . can anyone help me how to stop autostart my videos in iframe. thank you and here is my code. <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" width="1280" height="720" src="/static/assets/img/examples/vi.mp4?&autoPlay=0" frameborder="0" &autoPlay="false"></iframe> </div> -
Django deployment error on console when opening through Public IP
I am deploying a django site for the first time on aws ubuntu linux ec2 instance. I used Apache and mySQL database. I was able to successfully deploy the site and it was accessible through my public IP but it gave a warning in the Chrome console: [Deprecation] The website requested a subresource from a network that it could only access because of its users' privileged network position. These requests expose non-public devices and servers to the internet, increasing the risk of a cross-site request forgery (CSRF) attack, and/or information leakage. To mitigate these risks, Chrome deprecates requests to non-public subresources when initiated from non-secure contexts, and will start blocking them in Chrome 92 (July 2021). My project uses Django Rest Framework to post and get requests. I have used react for frontend so I use its build folder as a template in django and my frontend sends request to the public ip of my server. I am also attaching my settings.py file in case any of my settings might be a problem. I read somewhere that using a domain name would solve this error but I wasn't sure whether the issue was the same as mine. Also if this … -
Django login() authenticate always returns None
I have this code written up and it correctly registers users, though when it comes to the login function, it only works for the superuser i have in the database. Every time I try to log in a user that i greated using the register form, authenticate returns None. I'm having it print the form data and can confirm that the form being submitted has accurate info, yet it fails authentication every time unless i login the superuser. Views: def register(request): print(request.method) if request.method == 'POST': form = reg_form(request.POST) print(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') email = form.cleaned_data.get('email') phone = form.cleaned_data.get('phone') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') user = Users.objects.create( username=username, email=email, password=password, phone=phone,first_name=first_name, last_name=last_name ) try: user = Users.objects.get(phone=form.cleaned_data.get('phone')) print("User exists") except Users.DoesNotExist: print("DoesNotExist") return render(request, 'register.html', {'form': reg_form}) login(request, user) return render(request, 'profile.html') else: print(form.errors) return render(request, 'register.html', {'form': reg_form}) else: return render(request, 'register.html', {'form': reg_form}) def log_in(request): if request.method == 'POST': form = log_form(request.POST) print(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) print(user) if user is not None: print("user exists") login(request, user) return render(request, 'profile.html') else: print("user does not exist") print(form.errors) return render(request, 'login.html', { 'form2': log_form }) … -
django handling a form in a different view
I have three views : home, Product_List , Product_Detail that use the same form the addToCart form so i have to repeat the same code in these views to handle the form submission , so how to avoid that ?? i tried to create a function in the Cart model manager but when i call that function it retrun context errors and template tags errors this is the product_detail view : def product_detail(request, slug): if not request.session.exists(request.session.session_key): request.session.create() product_detail = get_object_or_404(Product, slug=slug) cart_obj = Cart.objects.new_or_get(request) object_viewed_signal.send(product_detail.__class__, instance=product_detail, request=request) if request.method == 'POST': Cart_Item_Post_Form = CartItemPostForm(request.POST or None) if Cart_Item_Post_Form.is_valid(): quantity = Cart_Item_Post_Form.cleaned_data['quantity'] product_id = request.POST.get("product_id") product_obj= Product.objects.get(id=product_id) try: get_cart_item = Cart_Item.objects.get(cart=cart_obj,products= product_obj) pre_quantity = get_cart_item.quantity new_quantity = pre_quantity + quantity get_cart_item.quantity = new_quantity get_cart_item.save() object_added_signal.send(product_detail.__class__, instance=product_detail, request=request) return redirect('cart_home') except(Cart_Item.DoesNotExist): Cart_Item_Post_Form.instance.products = product_obj Cart_Item_Post_Form.instance.cart = cart_obj Cart_Item_Post_Form.save() object_added_signal.send(product_detail.__class__, instance=product_detail, request=request) return redirect('cart_home') else: Cart_Item_Post_Form = CartItemPostForm() context = { 'product_detail' :product_detail, 'form' :Cart_Item_Post_Form, } return render(request,'product_detail.html', context) i want to replace the form handling code by some kind of a function -
Passing arguments to URL in template: No reverse match
I am using Django 3.2 I have a URL defined as follows urls.py app_name = event ... path('path/to/<int:event_id>/<slug:event_slug>', views.detail, name='detail'), ... mytemplate.html <a href="{% url 'event:detail' event_id=item.pk event_slug=item.slug %}" class="btn btn-primary">Find out more ...</a> When I visit the page in the browser, I get the error: NoReverseMatch at /path/to/ Reverse for 'detail' with keyword arguments '{'event_id': '', 'event_slug': ''}' not found. 1 pattern(s) tried: ['/path/to/(?P<event_id>[0-9]+)/(?P<event_slug>[-a-zA-Z0-9_]+)$'] Note: item is a variable passed to the template -
Django: I have a question about making an API in Django
guys! I'm doing a test that asks me to make an API and I don't have experience with that. The test says: "In order for us to know who the debtors are, the status of their credit recovery and more information, create an API to save and provide information about the cases and the people involved(credtors and debtors)." I'm confusing about the "to save" part. Do I have to make routes to save new creditors, debitors and cases, or the admin panel of Django is responsible for that and I have to just create routes to return information about the cases, creditors and debitors in json? -
Nginx redirecting to welcome page
I'm trying to deploy my Django app on VPS for the testing domain "yatsekk.pl". This is my first time deploying an app from scratch and I mostly follow the instructions from https://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/. The VPS server which I have runs with Centos 7. Almost everyting seems to be prepared and when I test it by gunicorn --bind 0.0.0.0:8000 strona.wsgi it seems to run correctly when I run it by "yatsekk.pl:8000" in the browser. I created the "gunicorn_run" file in the following way: NAME="polwysep" # Name of the application DJANGODIR=/root/Polwysep # Django project directory SOCKFILE=/root/run/gunicorn.sock # we will communicte using this unix socket USER=root # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=strona.settings # which settings file should Django use DJANGO_WSGI_MODULE=strona.wsgi # WSGI module name echo "Starting $NAME as `whoami`" cd $DJANGODIR source ../env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec env/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- Just to test it, I previosuly tried to change the --bind=unix:$SOCKFILE part to --bind=0.0.0.0:8000 and it once again did correctly run the page … -
Django - Is My Static File in the Wrong Place?
I'm creating a project for a weather app with Django, and I think my Javascript file is in the wrong place. I have it in a static folder. But I'm getting the console error GET http://127.0.0.1:8000/static/capstone/capstone.js net::ERR_ABORTED 404 (Not Found) Here is how my project files are set up. Is this correct? In settings.py I also have: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') -
Unable to calculate percentage with django and python
I know am doing something wrong here. Am trying to create an app where a user will deposit an amount and 8 percent of that amount deposited will be returned to the user in 10 days. Can someone please help me out. I want Eight percent of the deposited amount returned to the user in 10 days after the deposit to the user Models.py class Profile(models.Model): user = models.ForeignKey(UserModel, on_delete=models.CASCADE) balance = models.DecimalField(default=Decimal(0),max_digits=24,decimal_places=4) class Investment(FieldValidationMixin, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) fixed_price = models.DecimalField(max_digits=7, decimal_places=2, nulll=True, blank=True) percentageee = models.DecimalField(max_digits=3, decimal_places=0, nulll=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return _("{0}: (#{1} {2}%, ${3})".format(self.__class__.__name__, self.amount, self.percentage, self.fixed_price) ) This code intends to fetch the percentage of user amount payed in the investment models and calculate the percentage Views.py def get_percentage(self): pec_of_amount = Investment.objects.filter(amount=self.amount).annotate(percentageee=Sum('amount')) return '{:%}'.format(amount.percentageee / 8) def percentile(self, days=10): percent=Investment.objects.filter(self.amount*self.percentage)/100 in days return percentile #get the percentage balance of the amount invested after ten days def get_current_balance(self,percentile): total_expenses = Profile.objects.all().aggregate(Sum('balance')).annonate(percentile) return get_current_balance -
Django Integrity Error: Foreign Key Issue
I am creating an application where I have multiple stores and each store has an owner. One owner can own multiple stores but for a single store, there will only be one owner. I defined the store and owner models as follows:- ''' Store Owner Class ''' class Owner(models.Model): # Define the fields for the Customer first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=15) email = models.EmailField() password = models.CharField(max_length=500) ''' Store Model''' class Store(models.Model): """Model for the market which will hold all our stores and products Args: models: Inherits the model class """ # Define the fields of the market class name = models.CharField(max_length=100, null=False) description = models.CharField(max_length=1000, default="", null=True, blank=True) address = models.CharField(max_length=1000, null=True, default=" ", blank=True) logo = models.ImageField(upload_to='uploads/images/logos') owner = models.ForeignKey(Owner, on_delete=models.CASCADE) When I run migrate command on the models, I get the following error. django.db.utils.IntegrityError: The row in table 'market_store' with primary key '1' has an invalid foreign key: market_store.owner_id contains a value '1' that does not have a corresponding value in market_owner.id. I understand that this is a foreign key error in the store and owner table but I cannot seem to find a way through which I can connect my models without … -
Passing only one product to Stripe checkout from Django
I've integrated Django with Stripe and seems that works ok. However i have a problem by showing all products in stripe checkout page. I need to tell stripe which products we're going to buy. If i have 2 products in cart i see only one product in stripe checkout. views.py def payments_stripe(request): YOUR_DOMAIN = "http://127.0.0.1:8000/orders" print(request.body) body = json.loads(request.body) cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = cartItem.objects.filter(cart=cart, is_active=True) print(cart_items) order = Order.objects.get(cart=cart, is_ordered=False, order_number=body['orderID']) print(order) for cart_item in cart_items: quantity = cart_item.quantity print(quantity) name = cart_item.product.name print(name) try: checkout_session = stripe.checkout.Session.create( customer_email=order.email, billing_address_collection='auto', payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'eur', 'unit_amount': int(order.order_total * 100), 'product_data': { 'name': name, 'images': ['https://i.imgur.com/EHyR2nP.png'], }, }, 'quantity': quantity, }, ], metadata={ 'order_number': body['orderID'], 'payment_method': body['payment_method'], 'cart_id': cart, }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return JsonResponse({'id': checkout_session.id}) except Exception as e: return JsonResponse(error=str(e)), 403 I iterate over cart items and Iteration gives: 1 Golden Arrow 1 Silver Heart However in Stripe dashboard i see only one product 1 Golden Arrow. I suppose i need to create a new list. Is that right? How can i do that in my case? Thank you -
KeyError: 'product_id'
So I am following along with a youtube course and create an e-commerce web application and customizing it for specific needs. I am running into a KeyError in my api.py file when trying to assign product_id to the product_id SEE LINE BELOW: product_id = data['product_id'] from the request.body but this breaks the application as it cannot find that key. . After further inspection, I see that the request body dictionary only contains two of the three variables ('quantity' and 'update') and missing the 'product.id' variable. I am having trouble trying to figure out why that is. If anybody could help and kind of explain their reasoning that would be great(I am still learning so I would like to not just have the answer but know why as well). Below is the Vue code in cart.html and the api.py code which are where the issue is. Thnaks! I have been stuck on this for quite some time now and would like to understand and fix this so I can continue the project cart.html {% extends 'base.html' %} {% block title %}Cart | {% endblock %} {% block content %} <div id="hero" class="mid"> <div class="hero text-center"> <h2 class=" display-4 font-weight-bold">Cart</h2> <p class="text-light … -
Django DB API Response write in Model
i have a little Problem. Im trying to create an Calorietracker. The Calories for the meals are coming from an API. The Response of the API has many different listings in it which are similar to the food i searched for. Now i want to save my choice in the Django DB. Therefore i created a Model. The problem now is, i dont have any clue how to allocate my choice to the model. i would much appreciate it, if someone could give me some help ! Here is the code im using: Model: class Product(models.Model): productname = models.CharField(max_length=150) calories = models.FloatField(default=0) carbs = models.FloatField(default=0) protein = models.FloatField(default=0) fat = models.FloatField(default=0) views.py: def foodSearch(request): search_result = {} if 'food' in request.GET: searchform = APISearchForm(request.GET) if searchform.is_valid(): search_result = searchform.search() #print(search_result) context = {'searchform': searchform, 'search_result': search_result} else: searchform = APISearchForm() context = {'searchform': searchform, 'search_result': search_result} return render(request, 'search.html', context) search.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>search</title> </head> <h1> Lebensmittelsuche</h1> {% block content %} <label> When ? <input type="date" id="fooddate"> <input type="number" id="mealtime"> </label> <form method="get"> {{ searchform.as_p }} <button type="submit">Search</button> </form> {% if search_result %} <hr> {% for result in search_result.hints %} <form method="POST"> {%csrf_token%} <h3>{{ result.food.label … -
Change model field WITHIN model via method
I created a model that allows for courses and supporting info to be uploaded models.py from django.db import models from django.urls import reverse from datetime import datetime # Create your models here. class Course(models.Model): title = models.CharField(max_length=80) description = models.CharField(max_length=400) thumbnail = models.ImageField(upload_to="images/") video = models.FileField(upload_to="videos/") notes = models.FileField(upload_to="notes/") issued_at = models.DateField(auto_now_add=True) featured = models.BooleanField(default=False) is_fresh = models.BooleanField(default=True) def get_absolute_url(self): return reverse("courses:course_detail", kwargs={"pk": self.pk}) def time_passed(self): delta = datetime.now().date() - self.issued_at print(delta, "today: ", datetime.now().date()) return delta.days def is_fresh_check(self): if self.time_passed() >= 1: self.is_fresh = False return self.is_fresh As you can probably guess, I'm trying to see wether after ONE day or more of uploading the course, it should automatically change the value of 'is_fresh' attricbute to False. However, this isn't the case. I've also created an apiview to see the Course objects in json serializers.py from rest_framework import serializers from .models import Course class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('title', 'description', 'issued_at', 'is_fresh') def to_representation(self, instance): data = super().to_representation(instance) data['time_passed'] = instance.time_passed() data['is_fresh_check'] = instance.is_fresh_check() return data Finally, here's the rendered json for the object: [ { "title": "course_name", "description": "course_description", "is_fresh": true, "time_passed": 1, "is_fresh_check": false } ] I don't know why my 'is_fresh_check' method …