Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check two time period for overlap in django?
For e.g., I have two time periods 02:00:00 - 03:00:00 now I want to check that new incoming start time and end time does not fall between this range. 01:00:00 to 02:00:00 and 03:00:00 to 04:00:00 should be acceptable. -
django rest fraemwork. Save extendet user data to db
I try implement regestration endpoint fow user with additional attributes like phone_number and full_name. I implement logick for saving user data, which come from request, bit i xan't unserstand how i can save profile data, like phone_number and full_name. I have user model: class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) is_verified = models.BooleanField(_('is verified by admin'), default=False) EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def save(self, *args, **kwargs): if not self.username: self.set_username() super().save(*args, **kwargs) def email_user(self, subject, message, from_email=None, **kwargs): """Send an email to this user.""" send_mail(subject, message, from_email, [self.email], **kwargs) def set_username(self): pass And profile model: class Profile(TimeStampedModel): STATUS = Choices( ("inactive", _("inactive")), ("active", _("active")), ("banned", _("banned")) ) user = models.OneToOneField( User, verbose_name=_('related user'), on_delete=models.CASCADE, related_name='profile', related_query_name='profile' ) description = models.TextField( _("description of user's profile"), blank=True, default='' ) status = StatusField( _("status of the user") ) birth_date = models.DateField( _("Date of birth"), validators=[ MinValueValidator( datetime.date(1910, 1, 1) ), MaxValueValidator( datetime.date.today ) ], null=True, blank=True ) avatar = models.OneToOneField( "files.Avatar", on_delete=models.SET_NULL, null=True, blank=True, related_name="profile" ) full_name = models.CharField( max_length=30, default='', blank=False ) phone_number_regex_validator = RegexValidator(regex=COMPILED_REGEXP) phone_number = models.CharField( max_length=16, default='', blank=False, validators=[phone_number_regex_validator] ) objects = ProfileQuerySet.as_manager() def __str__(self): return f"profile of … -
How to extend a Django form in template?
i have an html of base step0.html i extend it {% extends "step0.html" %} all it's good but only my Django form not extends how can I do this? -
drf_spectacular schema generation threw exception when using ./manage.py makemigrations
I get this error when I run ./manage.py makemigrations and I don't know what is causing it (no relevant logs). ERRORS: ?: (drf_spectacular.E001) Schema generation threw exception "relation "global_preferences" does not exist LINE 1: ..."preferences"."preferences" FROM "global_prefer... Django 3.2.4 DRF: 3.12 -
How to return an HttpResponse object instead of None
can you help me out through this problem?, I'm a beginner and trying to learn django..even tho i tried so many other ways but it just wont work out. i hope you can help me models.py from django.db import models from django.db.models.fields import CharField , IntegerField, EmailField class Member(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=50) email = models.EmailField() age = models.IntegerField() password = models.CharField(max_length=100,null=True) def __str__(self): return self.first_name + " " + self.last_name form.py from django.db.models import fields from django.forms import ModelForm from django import forms from .models import Member class MemberForm(forms.ModelForm): class Meta: model = Member fields = ["first_name", "last_name", "age", "email", "password"] views.py from django.shortcuts import render from .models import Member from .form import MemberForm # Create your views here. def join(request): if request.method == "POST": form = MemberForm(request.POST or None) if form.is_valid(): form.save() return render(request, "HTML/join.html",{}) else: form = MemberForm() return render(request, "HTML/base.html",{}) error The view myapp.views.join didn't return an HttpResponse object. It returned None instead. -
Determine count of object retrieval per day in django
In a model like the one below class Watched(Stamping): user = models.ForeignKey("User", null=True, blank=True, on_delete=models.CASCADE) count = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Anytime an object is retrieved, I increment the count attribute. Now my problem is how to get the number of times an object was retrieved for each day of the week For example, WatchedObject1 will have {'Sun': 10, 'Tue': 70, 'Wed': 35} -
Compare expression with constant in CHECK constraint
I'd like to use Django's CheckConstraint to add a check constraint to a table using PostgreSQLs num_nonnulls() function, similar to this: create table foo( a text, b int, [...], check num_nonnulls(a, b, ...) = n); n is a constant but may be different for different tables (mostly it's going to be 1 but I'd like to find a general solution). This is how far I got: class Foo(models.Model): a = models.TextField(null=True) b = models.IntegerField(null=True) [...] class Meta: constraints = [ models.CheckConstraint( check=models.ExpressionWrapper( models.Func('a', 'b', function='num_nonnulls'), models.BooleanField()), name='num_nonnulls_check')] This is of course missing the step where the result of num_nonnulls() is compared to some constant integer. I tried defining a function to do this: def equals(a, b): return models.Func(a, b, template='%(expressions[0])s = %(expressions[1])s') But this doesn't work because the template argument expressions is (I think) a string (and %-template strings don't have this syntax to extract parts of an argument, I think). Where do I go from here? I'd like to find a solution that allows me to use arbitrary expressions supported by the Django ORM and also compare these expressions with other expressions or constants using an equality or inequality relation (e.g. = or <=). -
Django/Ajax/Post/ How do I send data from one table to another table
I have two tables, Exercises and Workouts. The Django models are below: name = models.CharField(max_length=200) exercises = models.ManyToManyField(Exercise, null=True) description = models.TextField(max_length=3000, default=None, blank=True, null=True) goals = models.TextField(max_length=3000, default=None, blank=True, null=True) workout_time = models.CharField(max_length=200, default=None, blank=True, null=True) difficulty = models.CharField(max_length=200, default=None, blank=True, null=True) workout_rating = models.PositiveIntegerField(default=None, blank=True, null=True) notes = models.TextField(max_length=5000, blank=True, null=True) def __str__(self): return self.name HTML form for Workouts: <forms id="workout_form" method='POST'> {{form|crispy}} <div class="row"> <div class="text-center pt-4"> <button type="button" class="btn btn-primary" id="create_workout"> Create </button> </div> </div> </forms> Above my forms, I already have a list of exercises I want to add, but this forms gives me a list of all of my exercises - which I don't want. Using Ajax, I want to send this data to Django to add to my database. I am stuck on how to add the exercises. my views.py: def workout_builder_details(request): form = WorkoutForm(request.POST or None, request.FILES or None) data = [] if request.is_ajax(): if form.is_valid(): form.save() data['name'] = form.cleaned_data.get('name') data['status'] = 'ok' return JsonResponse(data) context = { 'form': form, } return render(request, 'application/workout_builder_details.html', context) forms.py class WorkoutForm(forms.ModelForm): class Meta: model = Workout fields = ( 'name', 'exercises', 'description', 'goals', 'workout_time', 'difficulty') How can I save the data, with the exercises I've … -
Deploy Django App on subdirectory (Namecheap)
I'm Trying To deploy Django App on My Namecheap Cpanel But I want to deploy it on subdirectory Is it possible to deploy on subdirectory. And How Can I do it. (I'm new ) -
Using Select to Order my products by price,
How do you query the database when you select highest, it orders product from the most expensive price to list and vice versa. Here is my templates. I think you can see the select sort. <section class="body-section"> <!--Cleaning services--> {%for category in categories%} <section class="main-products cooler"> <div class="upper-bar"> <div> <h2>{{category.name}}</h2> </div> <div class="sortby"> <span>Sort By: <select class="sort"> <option value="highest">Highest Price</option> <option value="lowest">Lowest Price</option> </select></span> </div> </div> <hr /> <!--Single Products-wrap--> <div class="specific-product-wrap specific-product-wrap-cooler"> {% for product in category.product_set.all %} <a href="{%url 'product' product.pk%}"> <div class="specific-single-product"> <div class="product-image center"> <img class="product-image-shape" src="{{product.image.url}}" alt="adamol Distilled" /> </div> <div class="produc-descriptions"> <h4 class="specific-product-title">{{product.title}}</h4> <p class="one-line-description"></p> <p class="price">Ksh.{{product.price}}</p></a> <button data-product="{{product.id}}" data-action="add" class="AddToCart update-cart" id="addToCart update-cart">Add To Cart</button> </div> </div>` {% empty %} <p>No Product Lol</p> {%endfor%} </div> </section> Here is my model.py class Product(models.Model): image = models.ImageField(null=False, blank=False) title = models.CharField(max_length=2000, null=False, blank=False) category = models.ForeignKey( Category, on_delete=models.CASCADE, default=True, null=False) price = models.DecimalField(max_digits=5, decimal_places=2) description = models.TextField() delivery_time = models.DateTimeField(default=datetime.now, blank=True) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(default=datetime.now, blank=True) digital = models.BooleanField(default=False, null=True, blank=False) def __str__(self): return self.title I want the user to be able to view product, when they select highest, it sorts, when they select lowest it sorts by prices. Have truid different methods … -
Pytesseract - using .traineddata file on hosted server (Heroku)
I have a Vue, Django integrated project. I hosted the Vue project on Netlify and the Django project on Heroku. A python script (integrated into Heroku) is called on certain buttons which extract data and posts this to the Django API to be viewed on the frontend. I have trained a font type for my pytesseract OCR script. However, when i run it on Heroku, it seems like i can only use the 'eng' (normal font) as 'language' for my pytesseract image_to_string function. If I have the .traineddata file of the font type that I want to use, how can I use this file within the pytesseract functions? I can call the individual file, but I need the right TESSDATA_PREFIX as well. Does someone know how to deal with this? Thanks! -
Vue development version works but production doesn't (Vue CLI + Django)
I have build a site using Django and Vue+Vuetify, with Django running the backend and Vue the front end. I have been using Vue CLI to compile by .vue files. However, now that I am preparing to move the code to production version, I have run into following issue: Vue app created by vue-cli-service build does not work. When run in development mode with vue-cli-service build --mode development it all works fine, but the build version doesn't work. The JavaScript console doesn't give any errors. Almost nothing renders and what little renders doesn't seem to have styling included. However, I can see that axios calls do work, and using inspector shows that various elements are added to the body, they simply do not render. However, looking at my package.json I can't see any obvious errors. { "name": "vueapp", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "build-dev": "vue-cli-service build --mode development", "lint": "vue-cli-service lint" }, "dependencies": { "axios": "^0.21.1", "core-js": "^3.6.5", "vue": "^2.6.11", "vue-router": "^3.2.0", "vuetify": "^2.4.0" }, "devDependencies": { "@mdi/font": "^5.9.55", "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-plugin-router": "~4.5.0", "@vue/cli-service": "~4.5.0", "babel-eslint": "^10.1.0", "eslint": "^6.7.2", "eslint-plugin-vue": "^6.2.2", "material-design-icons-iconfont": "^6.1.0", "sass": "~1.32.0", "sass-loader": "^10.0.0", "vue-cli-plugin-vuetify": "~2.4.1", "vue-template-compiler": "^2.6.11", … -
Tooltip ignores bootstrap5 css
I am having problems using bootstrap 5 tooltips in my webapp. My django template works as follows: {% block css %} <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <!-- Bootstrap CSS for Tabulator --> <link rel="stylesheet" href="{% static 'css/tabulator_bootstrap4.min.css' %}"> {% endblock %} ... {% block javascript %} <!-- jQuery --> <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script> <!-- tabulator --> <script src="{% static 'js/tabulator.min.js' %}"></script> <!-- Bootstrap JavaScript --> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> <!-- bootstrap select picker --> <script src="{% static 'js/bootstrap-select.js' %}"></script> <link rel="stylesheet" href="{% static 'css/bootstrap-select.min.css' %}"></script> <!-- font awesome --> <script src="{% static 'fontawesome_free/js/all.min.js' %}"></script> {% endblock javascript %} In my html I use this code: var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')) var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) { console.log("added a tooltip"); return new bootstrap.Tooltip(tooltipTriggerEl) for this button, which shows just an ordinary tooltip: `<button type = button class="btn btn-sm btn-primary" data-bs-toggle="tooltip" data-bs-placement="top" title="${row.tooltip}"> <i class="fas fa-print"></i> </button>`; I can see the added a tooltip message never shows ... why? -
what is happening on os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
while iam creating a bot using botframework within a django application, i am not able to call the models of that appliction from the bot.i got the solution as put """os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = Ture""" in the settings.py file.its works fine for me.But iam curious to know what is happening while i making this step.is it safe? -
Print entire HTML table to .pdf Doc || Python Django
I currently have an app that prints a trial balance in a table format from a MySQL database. The code is shown below and so is the end result of the code. I am trying to find a way to print that exact data in that exact format to a pdf by the push of a button. If anyone has code to do this, please assist. Views.py: def Kyletrb(request): all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] '\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = PostGL.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = row[3] xAll_l.append(rdict) return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l}) Kyletrb.html: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> {% extends "main/base.html"%} {% block content%} <h1 class = 'center'>Kyle Database Trial Balance</h1> <br> <style> .img-container { text-align: center; width: 150px; height: 100px; } </style> <style> .center{ text-align: center; } </style> <style> .table-container{ border-spacing: 10px; padding-left: 300px; text-align: center; border-bottom: 1px solid #ddd; border-top: 1px solid #ddd; } </style> </div> <br> <br> <div class="table-container"> <table style="width:80%"> … -
Troubles with downloading and saving a document in django
I have a few problems, cannot figure it out, maybe there are connected. Problem 1.1: file is exported in django documentation and it works, but when I try to rename it, it has some error. I want to be like this with pd.ExcelWriter(newdoc + 'output.xlsx') as writer: in order to every file has a "new" name. I got this error, TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str' Problem 1.2: How to add path where to save? Problem 2: I get to download file but it is empty, and name of document is Donwload.xlsx. I want to be like this, but this got many errors... filename = newdoc + '_calculated.xlsx' response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response When I do this, I got this... in terminal UserWarning: Calling close() on already closed file. and this in browser TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str' This is views.py, and if code is like this, there are no errors but I got to download empty document. def my_view(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) with … -
Django Logging Emails not Arriving while other Emails do
I'm currently using this configuration to receive logging emails from my development as well as my production servers. ADMINS = [('Test1', 'somename@example.com'), ('Test2', 'someothername@example.com')] SERVER_EMAIL = "correctsender@example.com" LOGGING = { 'version': 1, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, } } The email is then sent with the following configuration for SMTP. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'correctsender@example.com' EMAIL_HOST_PASSWORD = 'thepassword' # normally loaded from environment EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'correctsender@example.com' I have enabled "Less secure Apps" in Gmail. For a few days now, we suspected that error logging was broken. Today we confirmed that the Mails sent via AdminEmailHandler were not arriving, while all other Mails send via the ordinary mail pipeline (no matter if from celery workers or directly from the server) were. Test with other backends showed that the Mail was sent by django. A quick test with smtplib showed that login was not blocked. How can it be that certain mails are accepted by Gmail while others, only differing in content, are not? Also, is there a place where rejected Emails are kept … -
'OnlineClassSerializer' object has no attribute 'onlineClassItems_set'
Hi I am using django and django-restframework for my website can you help me with this problem the problem is when I am trying to get all the data from the other serializer it can not find the attribute of the data how can I get the whole serialized data from another model ? the models.py class OnlineClass(models.Model): teacher = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name= models.CharField(max_length=255 ,null=True , blank=True) subject= models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True, blank=True) price=models.DecimalField(max_digits=7, decimal_places=0, null=True,blank=True) image= models.ImageField(null=True,blank=True) createdAt= models.DateTimeField(auto_now_add=True) category= models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) numReviews= models.IntegerField(null=True, blank=True, default=0) isAvailable = models.BooleanField(default=False,null=True,blank=True) hasOff = models.CharField(max_length=200,null=True,blank=True) rating= models.DecimalField(max_digits=7, decimal_places=2, null=True,blank=True) students= models.IntegerField() def __str__(self): return self.name class OnlineClassItems(models.Model): onlineClass= models.ForeignKey(OnlineClass, on_delete=models.CASCADE, null=True, blank=True) id= models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) title= models.CharField(max_length=255 ,null=True , blank=True) description= models.TextField(null=True , blank=True) file= models.FileField(null=True,blank=True) image= models.ImageField(null=True,blank=True) def __str__(self): return self.title here is the code the problem is in serializer.py class OnlineClassItemsSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField(read_only=True) class Meta: model=OnlineClassItems fields="__all__" def get_comments(obj,self): comments = obj.comments_set.all().order_by("-createdAt") serializer = CommentsSerializer(comments , many=True) return serializer.data class OnlineClassSerializer(serializers.ModelSerializer): onlineclassitems= serializers.SerializerMethodField(read_only=True) reviews= serializers.SerializerMethodField(read_only=True) teacher= serializers.SerializerMethodField(read_only=True) class Meta: model =OnlineClass fields ="__all__" def get_onlineclassitems(obj,self): onlineclassitems= obj.onlineClassItems_set.all().order_by("-createdAt") #error is here serializer = OnlineClassItemsSerializer(onlineclassitems , many=True) return serializer.data def … -
can't set attribute in django
There are 2 fields id and video_id in model,but i don't know how to assign the id value to request.data view def post(self, request, *args, **kwargs): try: if 'id' in kwargs: id = self.kwargs.get('id') else: id = request.learner request.data.id = id print(request.data) serializer = Serializer(data=request.data) serializer def create(self, validated_data): print('v', validated_data) recommended_courses = RecentlyViewedVideos.objects.create(**validated_data) return recommended_courses And the error is "Id- This field is required." I chose different methods to find the solution, but it did not work. Give me a solution to overcome this problem -
Django Docker deployment
Having never made a website or used Docker before, I've built a Django application with MySQL inside Docker and am finally ready for deployment, but completely overlooked that a web server was necessary. I've been quite stuck getting it to work and was wondering what approach others used. Is Apache or Nginx easier to set up, and does it need to be set up inside the Dockerfile and docker-compose.yml file, or can it be set up externally? I haven't been able to find much relevant information for this, so any advice or links would be appreciated. -
adding links to data table rows in javascript or jquery
I'm using django. Here is my code: <div class="card-body"> <div class="table-responsive"> <table id="datatables" class="table table-striped table-bordered text-nowrap w-100"> <thead> <tr> <th class="wd-15p">devEUI</th> <th class="wd-15p">appID</th> <th class="wd-20p">Type machine</th> <th class="wd-20p">Date création</th> </tr> </thead> <tbody> {% for machine in machines %} <tr> <a href="{% url 'details_of_element' %}"> <td>{{machine.devEUI}}</td> <td>{{machine.appID}}</td> <td>{{machine.type_machine}}</td> <td>{{machine.date_creation}}</td> </a> </tr> {% endfor %} </tbody> </table> </div> </div> It does not work. I want to add a link to each line to see the details of each item. How can I do this with django, jquery or javascript? -
FileNotFoundError: [Errno 2] No such file or directory in react with docker | python manage.py collectstatic is not working inside docker container
This is my django backend Dockerfile: FROM python:3.9.5-slim ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apt-get update && apt-get install build-essential python-dev -y COPY requirements.txt /var/www/html/requirements.txt RUN pip install -r /var/www/html/requirements.txt && pip install uwsgi WORKDIR /var/www/html COPY . . EXPOSE 8000 CMD ["uwsgi", "--http", ":9090", "--wsgi-file", "IMS/wsgi.py", "--master", "--processes", "4", "--threads", "2"] And this is my react Docker file: FROM node:13.12.0-alpine WORKDIR /var/www/html COPY package.json package-lock.json ./ RUN npm install COPY . . RUN npm run build EXPOSE 3000 And here is my docker-compose.yml file version: "3.3" services: backend: build: context: ./backend command: gunicorn IMS.wsgi --bind 0.0.0.0:8000 ports: - "8000:8000" frontend: build: context: ./frontend/ims volumes: - react_build:/frontend/ims/build/static nginx: image: nginx:latest ports: - "8089:8080" volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - react_build/frontend/ims/build/static depends_on: - backend - frontend volumes: react_build: -
can I call a function to set my USERNAME_FIELD = ''?
can I call a function in USERNAME_FIELD = '' to create an optional choice for login, using email or phone number? if yes how? -
Linking cart model to stripe checkout
How can I link price and items from cart Model to the Stripe checkout in Django Web Framework? I get and ValueError at /create_checkout_session when I changed default settings to the code below. When I leave it unchanged as default from the Stripe page it worked but of course it was a test example of checkout.. views.py @csrf_exempt def create_checkout_session(request): MY_DOMAIN = 'localhost:8000' cart = Cart.objects.get(order_user=request.user) try: session = stripe.checkout.Session.create( line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': cart.total, 'product_data': { 'name': cart.order_items.title } }, 'quantity': 1, }, ], payment_method_types=[ 'card', 'p24', ], mode='payment', success_url= request.build_absolute_uri(reverse('success-page')) + '?session_id={CHECKOUT_SESSION_ID}', cancel_url= request.build_absolute_uri(reverse('cancel-page')), ) except Exception as e: return print(e) return redirect(session.url, code=303) models.py class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = MoneyField( default=0.00, decimal_places=2, max_digits=11, default_currency='USD') class Item(Visits, models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) urls.py urlpatterns = [ path('create_checkout_session', views.create_checkout_session, name='checkout-page'), path('success', views.success, name='success-page'), path('cancel', views.cancel, name='cancel-page') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML form to get into the checkout: <form action="{% url 'checkout-page' %}" method="GET"> <button type="submit">Checkout</button> </form> -
Why oauth2 url is not opened on my client side?
I have a problem about my google drive oauth2. I have this code : def getService(creds): service = build('drive', 'v3', credentials=creds) return service def getCredentials(): # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/drive'] """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'code_clientXXX.json', SCOPES) creds = flow.run_local_server(port=0) print(creds) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) return creds When I run in localhost, i works very well, this url is automatically opened on my browser: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=XXXX&[..............] But, when I deploy my front (angular app) and my back (django app) on a distant server, using docker. There is a problem. 1 - If my token.json is already generated : It works …