Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to expose docker container port to another container
I have been trying for days to solve the following issue. I cannot make container A expose port for container B in docker compose. The two containers, however, can ping the other (so they are on the same network e.g. ping db from Container B resolves the IP). Example: Container A: postgres (exposes port 5432) Container B: django project (trys to connect to postgres on port 5432) django.env DB_NAME=freelancetracker DB_USER=freelance DB_PASSWORD=freelance1234 DB_HOST=postgresdb DB_PORT=5432 postgres.env POSTGRES_PASSWORD=freelance1234 POSTGRES_USER=freelance POSTGRES_DB=freelancedb version: "3.9" services: db: image: postgres env_file: - postgres.env ports: - 9001:5432 environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: - ./data/db:/var/lib/postgresql/data web: build: context: . network: host args: progress: plain volumes: - .:/code ports: - 9101:9100 env_file: - django.env depends_on: - db Container postgres: { "Id": "sha256:680aba37fd0f0766e7568a00daf18cfd4916c2689def0f17962a3e1508c22856", "RepoTags": [ "postgres:latest" ], "RepoDigests": [ "postgres@sha256:901df890146ec46a5cab7a33f4ac84e81bac2fe92b2c9a14fd649502c4adf954" ], "Parent": "", "Comment": "", "Created": "2023-02-11T05:02:41.267291947Z", "Container": "7f186dd9993cc4c4ee68d8e17c42f9205a5b09b06131c62d79861b85ff4aec1d", "ContainerConfig": { "Hostname": "7f186dd9993c", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "ExposedPorts": { "5432/tcp": {} }, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/postgresql/15/bin", "GOSU_VERSION=1.16", "LANG=en_US.utf8", "PG_MAJOR=15", "PG_VERSION=15.2-1.pgdg110+1", "PGDATA=/var/lib/postgresql/data" ], "Cmd": [ "/bin/sh", "-c", "#(nop) ", "CMD [\"postgres\"]" ], "Image": "sha256:073c3dc2528e2f091ce4497b9f51f4a69105de3faff43bd8675b99c5c2e470a6", "Volumes": { "/var/lib/postgresql/data": {} }, "WorkingDir": "", "Entrypoint": [ "docker-entrypoint.sh" ], "OnBuild": null, "Labels": {}, "StopSignal": "SIGINT" }, … -
How to render new tag using Django views?
I have index.html template in Django 4. Before. <video><source src="https://mysite/dfh2/video.mp4"></video> When I click play in player I want to render iframe, and hide all in video tag. After. <iframe src="https://somesite/ideo.mp4"></iframe> How can I do it in views.py ? -
from django.db.models.functions.math import Random2 ImportError: cannot import name 'Random2' from 'django.db.models.functions.math'
How can fix this problem ? Now I am using my Django version is 3.0.7 , I am tried another version but not support this solutions. -
How to Store file_paths for fast matching queries?
I am trying to store the file path of all files in a BUCKET. In my case a bucket can have millions of files. I have to display that folder structure in a UI for navigation. storage_folder: - bucket_1 - bucket_files.txt - bucket_metadata.txt - bucket_2 - bucket_files.txt - bucket_metadata.txt # bucket_file.txt contains folder1/sub_folder1/file1.txt folder1/sub_folder1/file2.zip folder1/sub_folder2/file1.txt folder2/..... .... .... Current approach: I will create a .txt file corresponding to each BUCKET which will contain absolute paths of each file in that bucket. Then whenever a query comes the whole file goes through lots of string matching which is really slow. What I want: I want to store those files in a tree based structure for optimized queries. Is there any solution for this? for context I am building my backend in Django. -
I have problem in Graphql. I can not get any query with Django use Graphql
I start new with Graphql. I write code from documentation. I create app named grph my project name is book. I added schema.py into my app named grph How can help me. I do not now what problem i think i write code right. Could this problem be due to the version of graphql? I use graphene 3.2.1 graphene-django 3.0.0 graphql-core 3.2.3 graphql-relay 3.2.0 It is my schema.py import graphene from .models import Category, Ingredient from graphene_django import DjangoObjectType class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id", "name", "ingredients") class IngredientType(DjangoObjectType): class Meta: model = Ingredient fields = ("id", "name", "notes", "category") class Query(graphene.ObjectType): all_ingredients = graphene.List(IngredientType) category_by_name = graphene.Field(CategoryType, name=graphene.String(required=True)) def resolve_all_ingredients(root, info): # We can easily optimize query count in the resolve method return Ingredient.objects.select_related("category").all() def resolve_category_by_name(root, info, name): try: return Category.objects.get(name=name) except Category.DoesNotExist: return None schema = graphene.Schema(query=Query) It is my models.py from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=100) notes = models.TextField() category = models.ForeignKey( Category, related_name="ingredients", on_delete=models.CASCADE ) def __str__(self): return self.name It is my settings.py INSTALLED_APPS = [ 'grph.apps.GrphConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', ] … -
ERROR: Service 'docs' failed to build : Build failed
So I had this django project for a few days and have delted and re-built it a couple of times already. I built it again this morning but it encountered an error: ERROR: Service 'docs' failed to build : Build failed The error in much detail is : ERROR: failed to solve: process "/bin/sh -c apt-get update && apt-get install --no-install-recommends -y build-essential libpq-dev && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false && rm -rf /var/lib/apt/lists/*" did not complete successfully: exit code: 100 Here's my local.yml file: version: '3' volumes: rantr_local_postgres_data: {} rantr_local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: rantr_local_django container_name: rantr_local_django depends_on: - postgres - redis volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: rantr_production_postgres container_name: rantr_local_postgres volumes: - rantr_local_postgres_data:/var/lib/postgresql/data - rantr_local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres docs: image: rantr_local_docs container_name: rantr_local_docs build: context: . dockerfile: ./compose/local/docs/Dockerfile env_file: - ./.envs/.local/.django volumes: - ./docs:/docs:z - ./config:/app/config:z - ./rantr:/app/rantr:z ports: - "9000:9000" command: /start-docs redis: image: redis:6 container_name: rantr_local_redis celeryworker: <<: *django image: rantr_local_celeryworker container_name: rantr_local_celeryworker depends_on: - redis - postgres ports: [] command: /start-celeryworker celerybeat: <<: *django image: rantr_local_celerybeat container_name: rantr_local_celerybeat depends_on: - redis - postgres ports: … -
How to show and keep the last record in Django
I'm new to Django I hope I'm making sense. I have two models: Usecase and Usecase_progress. I'm creating a page where I can see a list of all the use cases with their information + the usecase progress for each use case gets recorded. My views.py: def view_usecase(request): usecase_details = Usecase.objects.all() context = {'usecase_details': usecase_details} return render(request, 'ViewUsecase.html', context) My template: {% extends 'EmpDashboard.html' %} {% block body %} <div class="row d-flex"> <div class="col-12 mb-4"> <div class="card border-light shadow-sm components-section d-flex"> <div class="card-body d-flex row col-12"> <div class="row mb-4"> <div class="col-lg-12 col-sm-16"> <h3 class="h3 mb-4">View Usecases:</h3> </div> {% if usecase_details is not none and usecase_details %} <div class="table-responsive"> <table id="example" class="table table-flush text-wrap table-sm" cellspacing="0" width="100%"> <thead class="thead-light"> <tr> <th scope="col">No.</th> <th scope="col">Usecase ID</th> <th scope="col">Usecase Name</th> <th scope="col">Client</th> <th scope="col">KPI</th> <th scope="col">Progress</th> <th scope="col">Progress date</th> <th scope="col">Pipeline</th> <th scope="col">View</th> </tr> </thead> <tbody> {% for result in usecase_details %} <tr> <td>{{ forloop.counter }}</td> <td><span class="badge bg-info">{{result.usecase_id}}</span></td> <td>{{result.usecase_name}}</td> <td>{{result.business_owner.business_owner_name}}</td> <td>{{result.kpi.kpi_name}}</td> {% for progress in result.usecaseids.all %} <td><div class="progress-wrapper"> <div class="progress-info"> <div class="progress-percentage"> <span>{{progress.usecase_progress_value}}</span> </div> </div> <div class="progress"> <div class="progress-bar bg-success" role="progressbar" style="width: 60%;" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> </td> <td>{{progress.usecase_progress_date}}</td> <td>{{progress.pipeline.pipeline_name}}</td> {% endfor %} <td> <a href="/view-usecase/{{result.usecase_id}}" class="btn btn-success">VIEW</a> </td> </tr> … -
Django Template dynamically generated sidebar
I have created a two django views home() and machine_detail(). Home view renders an home.html template and pass it a dictionary containing equipment names. my side bar consists of the items in this dictionary which is dynamically generated below these names. The equipment model is related to Machines model and I have used django foreign key relation to make a drop down for each equipment showing all the machines related to that specific equipment. all the machines are in an anchor tag and upon click i want to show a detail of machine page but why cant i see my side bar contents in machine detail template it is extending home.html but still the sidebar is not showing anyhting. please help me Equipment Model name = models.CharField(max_length=255) quantity = models.IntegerField() manufacturer = models.ForeignKey(Manufacturer, on_delete=models.PROTECT) contractor = models.ForeignKey(Contractor, on_delete=models.PROTECT, null=True, blank=True) Machines Model name = models.CharField(max_length=50) type_of_machine = models.ForeignKey(Equipment, on_delete=models.CASCADE, related_name='typeOfMachine') spares = models.ManyToManyField(Spares,related_name='machines' ,blank=True) dop = models.DateField(verbose_name="Date of Purcahse", blank=True, null=True) purchase_cost = models.FloatField(default=0) model = models.CharField(max_length=50,blank=True, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) Home View def home(request): eq_map = {} equipment = models.Equipment.objects.all() for e in equipment: eq_map[e] = e.typeOfMachine.all() return render(request, "user/sidebar.html",{'equipments':eq_map}) machine_Detail view def machine_detail(request,pk): machine_detail = models.Machines.objects.get(pk=pk) … -
I am getting this error Page not found on my ecommerce store which i am making using django
`The problem being Django not able to find the that, I told it to, I am trying to access the add to cart feature which shows me this error Here's a look at my urls.py path('add-to-cart/`<int:product_id>`/', views.add_to_cart, name='add-to-cart'), path('cart/', views.show_cart, name='showcart')`, #Views.py def add_to_cart(request): user = request.user product_id = request.GET.get('product_id') product = Product.objects.get(id=product_id) Cart(user=user, product=product).save() return redirect("/cart") ``def `show_cart`(request):` user = `request.user` cart = Cart.objects.filter`(user=user) amount = 0``your text`` for p in cart: value = p.quantity * p.product.discounted_price amount = amount + value ` totalamount = amount + 40 return render(request, 'app/add-to-cart.html',locals())`` and my html file name is add-to-cart.html please help I tried to use the feature add to cart on my website when it showed me this error, i was expecting it to add this to the cart function` -
Django showing error 'constraints' refers to the joined field
I have two models Product and Cart. Product model has maximum_order_quantity. While updating quantity in cart, I'll have to check whether quantity is greater than maximum_order_quantityat database level. For that am comparing quantity with maximum_order_quantity in Cart Model But it throws an error when I try to migrate cart.CartItems: (models.E041) 'constraints' refers to the joined field 'product__maximum_order_quantity'. Below are my models class Products(models.Model): category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="products" ) product_name = models.CharField(max_length=50, unique=True) base_price = models.IntegerField() product_image = models.ImageField( upload_to="photos/products", null=True, blank=True ) stock = models.IntegerField(validators=[MinValueValidator(0)]) maximum_order_quantity = models.IntegerField(null=True, blank=True) ) class CartItems(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) quantity = models.IntegerField() class Meta: verbose_name_plural = "Cart Items" constraints = [ models.CheckConstraint( check=models.Q(quantity__gt=models.F("product__maximum_order_quantity")), name="Quantity cannot be more than maximum order quantity" ) ] #Error SystemCheckError: System check identified some issues: ERRORS: cart.CartItems: (models.E041) 'constraints' refers to the joined field 'product__maximum_order_quantity'. -
Django css and javascript app not served in production
I have a django project which in development mode css are loaded just fine but not in production. In my settings.py file I've set these trhee variables STATIC_ROOT = BASE_DIR / 'staticfiles/' STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] I also set DEBUG = False When I run python manage.py collectstatic command the staticfiles folder receives the files properly. I created a static folder in the root of the project to install bootstrap there, again, in developent runs just fine. I'm using Apache server throug XAMPP becasuse I'm on Windows. the configuration for the project is next: `LoadFile "C:/Python310/python310.dll" LoadModule wsgi_module "C:/Users/life/.virtualenvs/outgoing-qJCH8A9k/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/life/.virtualenvs/outgoing-qJCH8A9k" WSGIScriptAlias /outgoing "D:/DEV/PYTHON/GASTOS/software/outgoing/project/wsgi.py" application-group=%{GLOBAL} WSGIPythonPath "D:/DEV/PYTHON/GASTOS/software/outgoing" <Directory "D:/DEV/PYTHON/GASTOS/software/outgoing/project"> Require all granted Alias /static/ "D:/DEV/PYTHON/GASTOS/software/outgoing/staticfiles/" <Directory "D:/DEV/PYTHON/GASTOS/software/outgoing/staticfiles"> Require all granted ` The point is, the app load well but without the bootstrap css and javascript files. Also the browser console tells this. `Refused to apply style from 'http://localhost/outgoing/static/node_modules/bootstrap/dist/css/bootstrap.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET http://localhost/outgoing/static/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js` Help please. -
How to filter a trasaction model in django
i am trying to make transctions between two users models.py class Trasaction(models.Model): sender = models.ForeignKey( Account, on_delete=models.PROTECT" ) recceiver = models.ForeignKey( Account, on_delete=models.PROTECT" ) amount = models.IntegerField() purpose = models.CharField(max_length=100, null=True, blank=True) date = date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.sender.username}" i want to query for all transactions where a user is either a sender or a receiver. views.py def transactions_log(request): user = request.user transactions = Transactions.objects.filter #am stuck return render(request, "trasaction.html") -
Django - Authentication credentials were not provided for magiclink
I am trying to create authenticaiton sytem where a user can loging using a magic link. i am usign a custom user mode. class UserAuthView(CreateAPIView): http_method_names = ['post'] serializer_class = TestUserListSerializer permission_classes = (IsAuthenticatedTestUserPermissionAdmin,) def post(self, request, name, *args, **kwargs): serializer = self.serializer_class( data=request.data, context={'request': request} ) if serializer.is_valid(): email_id = serializer.validated_data['email'] try: user = TestUser.objects.filter(email=email_id).first() if user: company = str(user.company) user_id = user.id # Add the random string here random_string = get_random_string(16) request.session["login_state"] = random_string token = signing.dumps({"email": email_id, "login_state": random_string}) qs = urlencode({'token': token}) magic_link = request.build_absolute_uri( location=reverse('api-magiclink'), ) + f"?{qs}" return Response({ 'success': True, 'message': 'magiclink created .', 'data': { 'access_token': magic_link, } }) else: return Response({ 'message': 'User does not exist', }) except TestUser.DoesNotExist: return Response({ 'message': 'Unable to login user' }) else: return Response(serializer.errors) Then tryin to validate this using the following code class PartnerUserMagicLink(CreateAPIView): http_method_names = ['get'] permission_classes = (IsAuthenticatedTestUserPermissionAdmin,) def get(self, request, token, **kwargs): token = request.GET.get("token") if not token: # Go back to main page; alternatively show an error page return redirect("/") # Max age of 15 minutes data = signing.loads(token, max_age=900) email = data.get("email") if not email: return redirect("/") user = TestUser.objects.filter(username=email, is_active=True).first() if not user: # user does not exist … -
Django+PostgreSQL: creating user with UserCreationForm saves it to auth_user table, but not to the table created for the User model
I'm learning Django and now developing a simple food blog app for practice, using Django 4.1 and PostgreSQL. Since I'm not quite good yet at understanding how some concepts work in practice, I started with creating the basic structure (models, views, etc.) as per MDN Django Tutorial, and then went on adding other things based on various Youtube tutorials. I also created some users with Django Admin to see if everything works, and work it did... until I implemented user registration. I successfully registered several users via registration form and could log in as anyone of them, view their profile page, etc., but found out they were not displayed anywhere in the users list. At the same time, I couldn't log in to any of the accounts I created previously with Django Admin. Having searched for errors through the code of my 'recipeblog' app, I finally went to check the database I used. There, I found two different tables with different users: the first one named recipeblog_user, containing users created with Django Admin, and the second one named auth_user, containing users created with registration form. Thus I seem to have found the problem, but it got me stuck, for I … -
Which method to implement Websocket in Django?
I know that there are two ways to implement websocket in Django With Django channels Deploying a separate WebSocket server next to Django project My question is which one is better for scaling and customization ? -
Chain-Model Getting all objects for template
models.py class Sirket(models.Model): isim = models.CharField(max_length=20) def __str__(self): return f"{self.isim}" class Proje(models.Model): ad = models.CharField(max_length=20) total = models.DecimalField(max_digits=20,decimal_places=0) kalan = models.DecimalField(max_digits=20,decimal_places=0) tarih = models.DateField() firma = models.ForeignKey(Sirket, on_delete=models.CASCADE) def __str__(self): return f"{self.ad}" class Santiye(models.Model): isim = models.CharField(max_length=20) kasa = models.DecimalField(max_digits=20, decimal_places=0, default=0) araclar = models.ManyToManyField(Arac) baglanti = models.ForeignKey(Proje, on_delete=models.CASCADE) def __str__(self): return f"{self.isim}" class Personel(models.Model): ad = models.CharField(max_length=50) cinsiyet = models.CharField(max_length=10) yas = models.DecimalField(max_digits=4, decimal_places=0) baslamaTarih = models.DateField() resim = models.FileField(default="static/images/avatar.jpg") birim = models.ForeignKey(Santiye, on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.ad}" views.py def firma(request): sirket = Sirket.objects.all().prefetch_related('proje_set').order_by('id') # i have multiple classes with connect each other. # like Proje class connected to Sirket class with many-to-one relationship. # It goes like : Sirket -> Proje -> Santiye -> Personel # I'm trying to access the Personel.ad objects that are linked to the Sirket. template <div class="container"> <div class="row"> {% for sirket in sirket %} <div class="card mb-3"> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-9"> <div class="card-body"> <h3 class="card-title"><b>{{ sirket.isim }}</h3></b> <p class="card-text"><b>Şantiyeler:</b></p> <p>{% for araclar in santiye.araclar.all %} <li>{{ araclar }}</li> {% endfor %}</p> <p class="card-text"><b>Çalışan Personeller:</b></p> <p>{% for personel in santiye.personel_set.all %} <li>{{personel.ad}}</li> {% endfor %}</p> **<!-- I try to list santiye personels like above --> ** </div> </div> </div> … -
Terminal unresponsive after running server in Django and Python
I was following a tutorial on Django in python to learn how to build a website. But when I run the command "python manage.py runserver" it executes the command successfully, but after that I cannot type anything into the terminal, I can't even break. Here's a screenshot if it helps you understand my issue I've tried closing everything and rewriting all the code again, and it yields the same results. -
How to solve AttributeError: 'bool' object has no attribute '_committed' in Django
Traceback error: Internal Server Error: /home/absensi_masuk/face_detection Traceback (most recent call last): File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\skripsi\program\new_sisfocvwaero\project_sisfocvwaero\app_sisfocvwaero\views.py", line 332, in face_detection instance.save() File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\base.py", line 812, in save self.save_base( File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\base.py", line 863, in save_base updated = self._save_table( File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\base.py", line 1006, in _save_table results = self._do_insert( File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\base.py", line 1047, in _do_insert return manager._insert( File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\query.py", line 1791, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1659, in execute_sql for sql, params in self.as_sql(): File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1583, in as_sql value_rows = [ File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1584, in [ File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1585, in self.prepare_value(field, self.pre_save_val(field, obj)) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1533, in pre_save_val return field.pre_save(obj, add=True) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\fields\files.py", line 313, in pre_save if file and not file._committed: AttributeError: 'bool' object has no attribute '_committed' My Views.py : `while True: ret, frame = cap.read() face_cascade = cv2.CascadeClassifier('E:/skripsi/program/new_sisfocvwaero/project_sisfocvwaero/app_sisfocvwaero/face.xml') gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.putText(frame, str("OK"), (x+40, y-10), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 255, 0)) … -
Loading html file using js in django project
I have a django template in which I want to load a html file in a div depending on the value of a select box. This is the target div: <table id="template" class="table"> Where to load tables. </table> I have an tag: <a href="#" onclick='loadHtml("template", "user_table.html")'>dadjias</a> Which when clicked calls the javascript function: function loadHtml(id, filename) { let xhttp; let element = document.getElementById(id); let file = filename; if (file) { xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { if (this.status == 200) {element.innerHTML = this.responseText;} if (this.status == 404) {element.innerHTML = "<h1> Page not found.</h1>";} } } xhttp.open("GET", `templates/${file}`, true); xhttp.send(); return; } } However the issue is that for some reason when the function is called, the file cannot be found so the 'Page not found' displays on screen. These are the files in my django project: Files in Django project The html file I am tring to load in the div is at the bottom. Any help would be much appreciated and thank you in advance. -
How to hide stuff in template if Current User isn't on their own profile in Django?
I have a profile page with a button 'edit profile'. however, it shows up for all users when they access the profile. How do I hide/remove it if the profile doesn't belong to the owner?? For example: Alice visits Bob's profile page or vice versa. They can both see 'edit profile' button on each other's page. <a class="btn btn-primary" href="{% url 'editprofile' %}" role="Edit">Edit Profile</a>' my views @login_required # profile page def profile(request): return render(request, 'profile.html') my model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username -
How can I make my Django rest API run along side my react app on a custom domain HTTPS server?
I was wondering if it would be possible to run my Django rest API along side my react app on a custom domain HTTPS server. Currently I have my website on a google cloud VM with a custom domain attached to it via the CloudFlare service. The issue that I am currently facing is that I cannot set the csrftoken cookie on my browser since I would be trying to access my API on port 8000 (Unsafe) while my page is on HTTP or even HTTPS on a different domain. What should I do in this situation? What would be my best option? I have tried setting the CSRF_COOKIE_SAMESITE to None but it requires me to set Secure as well but once I do this I end up with a similar problem where I cannot access the token as my API is not on a secure server. -
Django: NOT NULL constraint failed: payments_orderdetail.stripe_payment_intent
I am trying to integrate stripe into my django application, i have followed the documentation and some articles, but when i hit the checkout button i get this error that says NOT NULL constraint failed: payments_orderdetail.stripe_payment_intent, what could be the issue here because everything seems to be working fine, this is the github repo. views.py @csrf_exempt def create_checkout_session(request, id): request_data = json.loads(request.body) product = get_object_or_404(Product, pk=id) stripe.api_key = settings.STRIPE_SECRET_KEY checkout_session = stripe.checkout.Session.create( # Customer Email is optional, # It is not safe to accept email directly from the client side customer_email = request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'inr', 'product_data': { 'name': product.name, }, 'unit_amount': int(product.price * 100), }, 'quantity': 1, } ], mode='payment', success_url=request.build_absolute_uri( reverse('success') ) + "?session_id={CHECKOUT_SESSION_ID}", cancel_url=request.build_absolute_uri(reverse('failed')), ) # OrderDetail.objects.create( # customer_email=email, # product=product, ...... # ) order = OrderDetail() order.customer_email = request_data['email'] order.product = product order.stripe_payment_intent = checkout_session['payment_intent'] order.amount = int(product.price * 100) order.save() # return JsonResponse({'data': checkout_session}) return JsonResponse({'sessionId': checkout_session.id}) models.py class OrderDetail(models.Model): id = models.BigAutoField( primary_key=True ) # You can change as a Foreign Key to the user model customer_email = models.EmailField( verbose_name='Customer Email' ) product = models.ForeignKey( to=Product, verbose_name='Product', on_delete=models.PROTECT ) amount = models.IntegerField( verbose_name='Amount' ) stripe_payment_intent = models.CharField( max_length=200, null=True, blank=True … -
How to get the detailed page by slug and not id in Django Rest Framework class based views
I am building an API using Django Rest Framework. I have the /api/localities endpoint where all of the objects on my database are displayed. Now I want to create the endpoint for a single page of a particular locality, and I want to make it by slug and not id for example /api/localities/munich. I am using Class based views and right now I can get the single page by id, for example /api/localities/2, but I want to change that to the slug. How can I do this? Here is my code: models.py class Localities(models.Model): id_from_api = models.IntegerField() city = models.CharField(max_length=255, null=True, blank=True) slug = models.CharField(max_length=255, null=True, blank=True) postal_code = models.CharField(max_length=20, null=True, blank=True) country_code = models.CharField(max_length=10, null=True, blank=True) lat = models.CharField(max_length=255, null=True, blank=True) lng = models.CharField(max_length=255, null=True, blank=True) google_places_id = models.CharField(max_length=255, null=True, blank=True) search_description = models.CharField(max_length=500, null=True, blank=True) seo_title = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.city serializers.py from rest_framework import serializers from .models import Localities class LocalitiesSerializers(serializers.ModelSerializer): class Meta: model = Localities fields = ( "id", "id_from_api", "city", "slug", "postal_code", "country_code", "lat", "lng", "google_places_id", "search_description", "seo_title", ) views.py from django.shortcuts import render from django.http import HttpResponse from wagtail.core.models import Page from .models import LocalityPage, Localities from django.core.exceptions import ObjectDoesNotExist from … -
trying to link css in html file for a django project
Directories Attached is a photo of my directories. Am am trying to use sudokuStyle.css in sudoku_board.html. However, it does not seem to make the connection in my html file. I am including my head for the HTML. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sudoku Solver</title> <link rel="stylesheet" type="text/css" href="{% static 'css/sudokuStyle.css' %}"> </head> Where could I be going wrong? I have tried a variety of ways to connect but it does not work. -
How to align text or url in Django template? - Python Crash Course, Project "Learning Log"
I am creating "Learning Log" Django web-application using "Python Crash Course, 2nd edition" book. But since I reached 20th chapter of the book, I started having problems. I created a template, that displays all entries of the particular topic. On the page we have entry title, date, a button to edit it, and of course its text. Following the book, I use bootstrap4 to make pages looks more beautiful. But I would like to align the entry date and the "edit entry" url to the right side. I tried style="text-align:right;" , but it doesn't work. I am really new to web development , so I beg you to not judge me strictly :) Page with topic and its entries topic.html {% extends 'learning_logs/base.html' %} {% block page_header %} <h3>{{ topic }}</h3> {% endblock page_header %} {% block content %} <p> <a href="{% url 'learning_logs:new_entry' topic.id %}">Add a new entry</a> </p> {% for entry in entries %} <div class="card mb-3"> <h4 class="card-header"> {{ entry.title }} <small style="text-align:right;"> {{ entry.date_added|date:'M d, Y'}} <a style="text-align:right;" href="{% url 'learning_logs:edit_entry' entry.id %}">edit entry</a> </small> </h4> <div class ="card-body"> {% if entry.text|length > 500 %} {{ entry.text|linebreaks|truncatechars:500 }} <p><a href="{% url 'learning_logs:entry' entry.id %}">Read more</a></p> {% …