Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing Django request object into script to build absolute URI?
I am trying to build a one time script by passing in a django request in order to build an absolute URI. I am using the HttpRequest() method as follows... request = HttpRequest() And passing it into the function that I am calling when running my script. I keep running into a KeyError My script that is being ran is as follows, from django.http import HttpRequest for form in forms: form_data = get_data(form) for user in User.objects.all(): request = HttpRequest() config_user_forms(request, user) Errors out with the following, File "config_user_forms.py", line 65, in <module> redeploy_form(request, user) File "/tmp/8dae22604556cc2/users/admin/users.py", line 654, in redeploy_form build_url = request.build_absolute_uri( File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 223, in build_url location = self._current_scheme_host + location File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/utils/functional.py", line 45, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 240, in _current_scheme_host return "{}://{}".format(self.scheme, self.get_host()) File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 121, in get_host host = self._get_raw_host() File "/tmp/8dae22604556cc2/antenv/lib/python3.8/site-packages/django/http/request.py", line 111, in _get_raw_host host = self.META["SERVER_NAME"] KeyError: 'SERVER_NAME' I am a bit stumped on a work around, and appreciate any help in advance! -
How to run "SELECT FOR UPDATE" for the default "Delete selected" in Django Admin Actions?
I have Person model as shown below: # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) And, this is Person admin below: # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): pass Then, when clicking Go to go to delete the selected persons as shown below: Then, clicking Yes I'm sure to delete the selected persons: Only DELETE query is run in transaction as shown below: Now, how can I run SELECT FOR UPDATE for the default "Delete selected" in Django Admin Actions? -
Cannot generate instances of abstract factory UserFactory ( Factory boy)
factory.errors.FactoryError: Cannot generate instances of abstract factory UserFactory; Ensure UserFactory.Meta.model is set and UserFactory.Meta.abstract is either not set or False. Im using factory boy library To test my functions my class UserFactory Here enter image description here Here Model User I'm inheritance from class abstract user enter image description here I added class meta abstract and still not working I added class meta abstract and still not working -
How can I use Date Range with Sum and Order By in Django
I am working on a project where I have an Income Model with description among other fields as shown below. The description is a choice field and I want to use Date Range to Sum by each description. i.e. I would want to sum all amount for each description and display their total in HTML Template. Below is what I have tried but I am getting error which says too many values to unpack (expected 2). Models code: CATEGORY_INCOME = ( ('Photocopy', 'Photocopy'), ('Type & Print', 'Type & Print'), ('Normal Print', 'Normal Print'), ('Color Print', 'Color Print'), ('Passport', 'Passport'), ('Graphic Design', 'Graphic Design'), ('Admission Check', 'Admission Check'), ('Lamination', 'Lamination'), ('Document Scan', 'Document Scan'), ('Email Creation', 'Email Creation'), ('Email Check', 'Email Check'), ('Online Application', 'Online Application'), ('Agreement Form', 'Agreement Form'), ('Envelope / Binding Film', 'Envelope / Binding Film'), ('Web Development ', 'Web Development'), ) class Income(models.Model): description = models.CharField(max_length=100, choices=CATEGORY_INCOME, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) amount = models.PositiveIntegerField(null=False) date = models.DateField(auto_now_add=False, auto_now=False, null=False) addedDate = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Income Sources' def __str__(self): return self.description Views Code def generate_reports(request): searchForm = IncomeSearchForm(request.POST or None) searchExpensesForm = ExpensesSearchForm(request.POST or None) if request.method == "POST" and searchForm.is_valid() and searchExpensesForm.is_valid(): listIncome = … -
Raise Error 404 using django-hosts in Django
I have the following problem. I'm using django-hosts for subdomains like blog.example.com, es.example.com. The problem is that there are urls where I manage id, such as: blog.example.com/url/id And suppose the user doesn't touch anything, because everything is an OK 200 but if the user goes from clever and touches the id to one that doesn't exist, the site returns a 404. But here comes the problem, when using django-hosts if I do a handler404 in the urls of the subdomain. It throws me an Error 500 and if I then do a handler500 in the urls of the subdomain, literally, it breaks the server, since then apache tells me that there is a problem in the server. Here I leave my url.py of the subdomain. from django.urls import path from django.views.generic.base import TemplateView from django.conf.urls import handler404, handler500 from django.conf import settings from django.conf.urls.static import static from django.contrib.sitemaps.views import sitemap # MODULO PROPIO from . import views from .sitemaps import MapaDeSitio sitemaps = { 'blog': MapaDeSitio } urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [ # SITIO path('', views.indexView, name='IndexView'), path('articulo/<str:url>/<int:id>', views.ArticuloView, name="ArticuloView"), # SEO path('robots.txt', views.RobotsView.as_view()), path('BingSiteAuth.xml', TemplateView.as_view(template_name="blog/BingSiteAuth.xml", content_type="text/xml")), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] # MANEJO DE ERRORES HTTP handler404 … -
Query M2M from Django template language
This might be a rookie problem but I cannot find a way around it. I am trying to implement add recipe to favourites. The view and model work properly as when I hit the button once it sends the request and adds the recipe to the user's favourites. Then when clicked again it removes it correctly from the database. Alas now when i try to make visible on the template I ran into trouble with the template language. I cannot find a way to check if the current user's profile has liked the paginated recipe. I have the following class based list view class Home(ListView): model = Recipe template_name = 'home.html' cloudinary_name = settings.CLOUDINARY_STORAGE.get('CLOUD_NAME') extra_context = { 'cloudinary_name': cloudinary_name, } paginate_by = 2 def get_queryset(self): return Recipe.objects.order_by('id').prefetch_related('profile__recipecomment_set__recipe') and the following Recipe model class Recipe(models.Model): title = models.CharField( max_length=TITLE_MAX_LENGTH, validators=( MaxLengthValidator(TITLE_MAX_LENGTH), MinLengthValidator(TITLE_MIN_LENGTH), ), null=False, blank=False, ) profile = models.ForeignKey( Profile, on_delete=models.RESTRICT, null=False, blank=True, editable=False, ) favourites = models.ManyToManyField( Profile, related_name='favourite', default=None, blank=True, ) the template.html is as follows {% for recipe in page_obj %} {% if request.user.profile.id in recipe.favorites %} <button>Recipe added to favourites</button> {% else %} <button>Add to favourites</button> {% endif %} {% endfor %} the pagination works, everything else … -
I am trying to edit basic crud command with basic application using python django
I can create an obj just find. I want to pre load the form have a user make a change and update/save it in the db. After an edit is made it adds " ", (), [[[enter image description here](https://i.stack.imgur.com/Tan5A.png)](https://i.stack.imgur.com/jGJsK.png)](https://i.stack.imgur.com/WKowu.png)marks and commas after everything. I have tried to use the replace function to remove the ""'s, still doesnt do any good? I just want to edit and save without adding characters to my data. I tried value={{task.reminder}} and it shows fine on my page, after I check the edit it will show "Take trash out", All I need is Take trash out. Thank you!!!!!!!! the photos showed what I tried, however, I have no idea how to fix. Thank you. -
Google Calendar API v3 error after allowing permission using oauth2.0
I followed the quickstart example to integrate my django app with google calendar. The difference from quickstart to my situation is that i just want to generate a URL and send it back to my user, through from google_auth_oauthlib.flow import InstalledAppFlow SCOPES = ['https://www.googleapis.com/auth/calendar'] flow = InstalledAppFlow.from_client_secrets_file(f"{PATH_TO_FILE}/{CLIENT_SECRET_FILE}", SCOPES) (auth_url, state) = flow.authorization_url() if is_dev(): auth_url += '&redirect_uri=http%3A%2F%2Flocalhost%3A43759%2F' print(auth_url) (OBS: I added this is_dev option, because no redirect_uri was not considered) I get this printed URL and get this steps: 1- The URL from auth_url printed when i ran the program 2- After choosing my user 3- and BAM, I cant proceed (i am redirected to localhost:47759 and cant access) What should I do? -
What is the best practice of handling buttons in Djnago?
I am not sure about the best practice on generating a high amount of buttons, that will connect with Django backend, after they are clicked. I am currently making sample online store in Django as my first project, so I can learn the framework. Each product on the page is going to have a button to add the product to the cart of a logged user. Should I make every button as a form, or handle the buttons with JS and fetch API. I did not fail to notice, Django heavily relies on forms as a default way to get user input, but making a so many generated forms on one page (the products are going to be a list) just doesn't feels right I was thinking of the solution like this: document.querySelectorAll('.add_product').forEach(e => { e.addEventListener('click', e => // POST request (with crsf cookie and all) // redirecting the user, depending on the output ) }) Just get all buttons, get data-pk from <button>, and send it with the JS Fetch API as POST request to Django endpoint The thing I don't like about it is, I see potential CORS Issues, and I do not know if this is the … -
How can i filtering tags with Alpine.js
I want to filter the tags based on user clicks. But the problem is when I use the HTML tag, everything becomes hidden as I cannot see any content on the page. Even when clicking on a specific tag, I do not see any results.The result after using The model.py : class Challenge_code(models.Model): #create a table auther = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 200, null = False) body =RichTextUploadingField(blank=True, null=True) image = models.ImageField(null = True,blank=True ,upload_to='attach/') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) tags = TaggableManager() def __str__(self): return self.title serializers.py from rest_framework import serializers from taggit.serializers import (TagListSerializerField, TaggitSerializer) from .models import Challenge_code class ChallengeSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Challenge_code #fielsds = ('id','title','body','image','tags') fields = '__all__' the urls.py : urlpatterns =[ path('challengePage/', views.ChallengePage, name ='challengePage'), path('tag/<slug:tag_slug>', views.ChallengePage, name='tag'), path('challenge-list/', views.ChallengeListAPIView.as_view(), name='challenge-list'), ] the views.py : def ChallengePage(request): challenges = Challenge_code.objects.prefetch_related('tags').all().order_by('-created_at') tags = Tag.objects.all() context = { 'challenges' : challenges, 'tags':tags, } return render(request,'challengePage.html',context) class ChallengeListAPIView(ListAPIView): queryset = Challenge_code.objects.all() serializer_class = ChallengeSerializer The ChallengePage HTML page : <script defer src="https://unpkg.com/alpinejs@3.9.0/dist/cdn.min.js"></script> <div style="text-align: center;" x-data = "{tag: 'ALL', challenges: []}" x-init="challenges = await (await fetch('/challenge-list')).json()"> {% for tag in tags %} … -
The page of my website does not load on iPhones
I made my first website (https://pasta-la-vista.ck.ua/), but I ran into a problem. The site works on a computer and Android, but the menu page (https://pasta-la-vista.ck.ua/menu/) does not load on an iPhone. I couldn't find any information about what this is related to, so I hope to find help here. I fixed all the errors that appeared in the console but it didn't help me. I also looked for information on the Internet, but did not find anything Thank you all in advance for your help! -
I have a django app in a ubuntu virtual machine and can't remotely access the postgres database
I deployed an application in django on GCP in a VM (ubuntu 22.04 01 LTS) The app is working normally, database is postgresql. But I can't remotely access the database, I always get timeout error. My settings.py .... DATABASES = { 'default': { 'ENGINE': os.environ.get('DATABASE_ENGINE'), 'NAME': os.environ.get('DATABASE_NAME'), 'USER': os.environ.get('DATABASE_USER'), 'PASSWORD': os.environ.get('DATABASE_PASSWORD'), 'HOST': os.environ.get('DATABASE_HOST'), 'PORT': os.environ.get('DATABASE_PORT'), } } ... My .env file : # Postgres DATABASE_ENGINE = 'django.db.backends.postgresql' DATABASE_NAME = "basededados" DATABASE_USER = "user" DATABASE_PASSWORD = "senha" DATABASE_HOST = "127.0.0.1" DATABASE_PORT = "5432" I created the database like this: sudo -u postgres psql CREATE ROLE user WITH LOGIN SUPERUSER CREATEDB CREATEROLE PASSWORD 'senha'; CREATE DATABASE basededados WITH OWNER user; GRANT ALL PRIVILEGES ON DATABASE basededados TO user; I already set up the postgres.conf file: listen_addresses = '*' And the pg_hba.conf file**:** # IPv4 local connections: host all all 0.0.0.0/0 md5 I alredy allowed port 5432 through the firewall by executing: sudo ufw allow 5432/tcp I'm trying to access the DB like this: psql -h {Virtual machine IP} -d basededados -U user the error: psql: error: connection to server at {Virtual machine IP}, port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? Am I … -
admin is not able to approve post for the required like field django
In my django project, users can create posts. but the admin has to approve the post first. Then the users can see the posts created by them in their timeline. The users can like or unlike post from the post-detail page. However, when the admin logs in from the django admin panel to approve post and click the save button, it shows that the like field is required. How can I solve this problem so that the admin can approve the post? blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField # first I installed ckeditor by this command: pip install django-ckeditor # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) # content = models.TextField() content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved = models.BooleanField('Approved', default=False) like = models.ManyToManyField(get_user_model(), related_name='likes') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) @property def total_likes(self): return self.like.count() users/models.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your … -
Failed to execute 'fetch' on 'WorkerGlobalScope'
I'm trying to pass variables from background.js file to views.py in Django. I tried many ways to do it and I write the following code, it seems to work but I stuck with this error. I searched a lot for a solution but I didn't found anything yet //background.js fetch("http://127.0.0.1:8000/my_app/views") .then(response => response.text()) .then(responseText => { // Extract the X-CSRF-TOKEN cookie from the response let csrfToken = getCookieValue(responseText, "csrftoken"); // Set up the data to send to the server let data = { variable1: "value1", variable2: "value2" }; // Make the request to the server with the X-CSRF-TOKEN header fetch("http://127.0.0.1:8000/my_app/views", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken } }) .then(response => response.json()) .then(responseData => { console.log(responseData); }); }); // Helper function to extract a cookie value from a string function getCookieValue(text, name) { let start = text.indexOf(name + "=") + name.length + 1; let end = text.indexOf(";", start); if (end === -1) { end = text.length; } return text.substring(start, end); } the error is the follwing: Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Invalid value please help me.. -
How do I adapt my import statements to my folder structure in Django?
I just set up a basic folder structure for a new project, however I am doing it a bit different than the standard file structure, since my front-end is in React and will be in a separate git repository. The problem is, my virtual environment is installed in the "backend-django" project and when I try to access my package imports (that I installed in my virtual env) in backend/settings.py it does not recognize them. As an example: I pip installed django-environ into my venv but when I go to settings.py (like I normally do) and import environ, I get a 'no module named environ' error. This is my first foray into Django (clearly). For reference, I have previously only used Flask for Python projects. Any help is appreciated! A mockup of my basic folder structure is here: folder structure I have already tried from backend-django import environ and from . import environ. I am still getting the same error. -
Django allauth render login fields manually user or email not displayed
I'm trying to display the login fields manually, instead of using: {{form.as_p}} I'm setting allauth as follows in order to login with email: ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True In HTML I have the following: <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} <!-- Email input --> <div class="form-outline mb-4"> {{form.email}} <label class="form-label" for="form2Example1">Email address</label> </div> <!-- Password input --> <div class="form-outline mb-4"> {{form.password}} <label class="form-label" for="form2Example2">Password</label> </div> {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> <button class="btn btn-lg btn-block btn-primary" type="submit">{% trans "Sign In" %}</button> </form> The email field is not being displayed, I have also tried with: {{form.user}} and the field is not displayed -
Nginx subdomain running the wrong web application
so I have a ubuntu server that run two different website with two different domain: www.firstwebsite.com www.secondwebsite.com But when I create an AAA record to create a subdomain with the first domain (like this) demo.firstwebsite.com If I go to this subdomain it automatically run the application website of my other domain (www.secondwebsite.com) I tried creating a specific socket&service file for the subdomain for it still run the web application of the second domain. Im not sure what is causing that and how to fix that? thank you -
create superuser in django custom User model with phone number as username
I have a django project which I want it to have phone number as its username field. I've created an app named accounts, and this is the models.py: class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, phone_number, password, **extra_fields): user = self.model(phone_number=phone_number, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self.create_user(phone_number, password, **extra_fields) class User(AbstractUser): phone_number = models.CharField(max_length=20, null=False, blank=False, unique=True) USERNAME_FIELD = "phone_number" username = None first_name = None last_name = None objects = UserManager() REQUIRED_FIELDS = [phone_number] And I've declared it as my user model, in settings.py. AUTH_USER_MODEL = "accounts.User" ACCOUNT_USER_MODEL_USERNAME_FIELD = "phone_number" When I run python manage.py createsuperuser, I get this error: django.core.exceptions.FieldDoesNotExist: User has no field named 'accounts.User.phone_number' I can't figure out what is the problem. -
dockerized django application cannot connect to mysql server on localhost
I have a Dockerized django application I am running and I am trying to connect it to a mysql server I have that is port forwarded from another docker container. I have done a sanity test already and confirmed that I can connect to my mysql server using mysql workbench on my localhost. I have my dockerized django application running on network_mode: host so I thought I would be able to simply connect. Sadly I currently error out on docker-compose build with the error django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)") An accepted resolution to this issue means that my dockerized django application would be able to connect successfully to my mysql server running localhost:29998 SETTINGS.PY (Django Application) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mytestdb', 'USER': 'userone', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '29998', } } DJANGO App compose file version: '3.3' services: mydjangoapp: container_name: mydjangoapp restart: always env_file: .env build: . volumes: - ./apps:/apps - ./core:/core network_mode: host Django app dockerfile: FROM python:3.9 COPY . . # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements.txt . # install python dependencies RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt # … -
Receiving email content with in a template using Django contact form
I have set up a fully operational contact form and now I would like to render the users inputs into a html template, so when I receive the email it is easier to read. How do I do this? Do I link the template below some where, or link the form with in a template? Thank you in advance def contactPage(request): if request.method == 'POST': form = contactForm(request.POST) if form.is_valid(): subject = "INQUIRY" body = { 'full_name': form.cleaned_data['full_name'], 'email': form.cleaned_data['email_address'], 'message':form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message, '', ['email]) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ('thankyou') form = contactForm() return render(request, "contact.html", {'form':form}) -
django: aggregation-of-aggregation with subquery: cannot-compute-avg-is-an-aggregate
I've been scouting & testing for quite some time now and I'm unable to get anything working with MariaDB. I have a subquery: rating_average_by_puzzle_from_completion_plays = Play.objects.filter(completion_id=OuterRef('id')).values('puzzle_id').order_by('puzzle_id').annotate(puzzle_rating_average=Avg('rating')).values('puzzle_rating_average') where the ratings of all plays corresponding to a given completion are averaged per puzzle_id Afterwards, I'm trying, for each completion, to average the puzzle_rating_average corresponding to each puzzle_id: if I do annotate, I end up with : SequenceCompletion.objects.annotate(rating_avg_from_completion_plays=Subquery(rating_average_by_puzzle_from_completion_plays.annotate(result=Avg('puzzle_rating_average')).order_by().values('result'))) django.core.exceptions.FieldError: Cannot compute Avg('puzzle_rating_average'): 'puzzle_rating_average' is an aggregate if I do aggregate, I end up with : SequenceCompletion.objects.annotate(rating_avg_from_completion_plays=Subquery(rating_average_by_puzzle_from_completion_plays.aggregate(result=Avg('puzzle_rating_average')).order_by().values('result'))) ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. I tried as well: SequenceCompletion.objects.annotate(rating_avg_from_completion_plays=Avg(Subquery(rating_average_by_puzzle_from_completion_plays))) and I end up with: MySQLdb._exceptions.OperationalError: (1242, 'Subquery returns more than 1 row' Nothing I could find on the documentation or in any post would work, so I'll appreciate any help -
Page not found (404) Error in Django when creating a checkout session with Stripe
I am working on my first Stripe integration project to Django and I have landed into a problem that I have not managed to figure out a solution. I am trying to create a session whereby users can be redirected to the page where they can make a payment. Here is my views.py: class ProductLandingPageView(TemplateView): template_name = "landing.html" def get_context_data(self, **kwargs): product = Product.objects.get(name="Test Product") context = super(ProductLandingPageView, self).get_context_data(**kwargs) context.update({ "product": product, "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLISHABLE_KEY }) return context class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs["pk"] product = Product.objects.get(id=product_id) YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( line_items=[ { # Provide the exact Price ID (for example, pr_1234) of the product you want to sell 'price': '{{product.price}}', 'quantity': 1, }, ], metadata={ "product_id": product.id }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return redirect(checkout_session.url, code=303) Here is my urls.py; urlpatterns = [ path('', ProductLandingPageView.as_view(), name='landing'), path('success/', SuccessView.as_view(), name='success'), path('cancel/', CancelView.as_view(), name='cancel'), path('create-checkout-session/<pk>', CreateCheckoutSessionView.as_view(), name='create-checkout-session'), ] Also here is the templatate where the checkout button is located: <body> <section> <div class="product"> <!-- <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> --> <div class="description"> <h3>{{product.name}}</h3> <h5>${{product.price}}</h5> </div> </div> <form action="/create-checkout-session" method="POST"> <button type="submit" id="checkout-button">Checkout</button> </form> </section> {% csrf_token %} </body> <script type="text/javascript"> … -
i have defined block content in base.html and extents in index.html , block content is not working
in template/app/index.html {% extends 'base.html' %} {% block content %} replace me {% endblock %} in template/app/base.html <!doctype html> <html> <head> <title>Base title</title> </head> <body> {% block content %} {% endblock %} </body> </html> in app/urls.py from django.urls import path from app import views urlpatterns = [ path('',views.index) ] in app/views.py from django.shortcuts import render # Create your views here. def index(request): return render(request,'app/base.html',{}) this is the code...! i have tried changing the folder location and saw level of the folder -
Can't import anything from django
I'm having problems with importing stuff from django. I'm completely new to python and I'm following a tutorial where I'm taught how to make my first django project (I'm using pycharm btw). The problem I'm encountering is when I try to import something from django it says Unresolved reference 'django'. from django.http import HttpResponse from django.shortcuts import render In this case it only shows the red squiggly line under the two django, HttpResponse and render. Any help would be appreciated I have tried searching on google, but i couldn't find what I'm looking for. -
Django token authentication error: cURL request without header shows 401 unauthorized, but adding header token auth changes to 404 not found error
Titles lays out the issue I am facing. Working on a boiler plate Django app with an API endpoint. I am able to (semi-successfully) access the endpoint via a simple cURL without header which returns a 401, but when I add the header token, I now get a 404 not found error. What could be going wrong? I've tried multiple different combinations of django settings changes across these forums and cannot get it to change. Examples of some things I have tried: Changing order of MIDDLEWARE CORS_ORIGIN_WHITELIST CORS_ALLOWED_ORIGINS CORS_ALLOW_CREDENTIALS CORS_ORIGIN_ALLOW_ALL Playing with REST_FRAMEWORK settings -- both DEFAULT_AUTHENTICATION_CLASSES & DEFAULT_PERMISSION_CLASSES Changing ALLOWED_HOSTS from [] to current value below CORS_ALLOWED_ORIGINS Attaching snippets of relevant code: 401 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/ 404 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/ -H "Authorization: Token <super secret but valid token>" settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<secret hidden key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # helpers 'rest_framework', 'rest_framework.authtoken', 'corsheaders', # my apps 'Bets', 'Users', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", …