Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add proxy model to update existing data using django
I am trying this but I don't seem to be able to select an existing row from the parent model before creating proxy model from django_mail_admin.models import Mailbox, OutgoingEmail, IncomingEmail from core.models import User class MailboxProxy(Mailbox): user = models.ForeignKey(User, on_delete=models.CASCADE) class OutgoingEmailProxy(OutgoingEmail): user = models.ForeignKey(User, on_delete=models.CASCADE) class IncomingEmailProxy(IncomingEmail): user = models.ForeignKey(User, on_delete=models.CASCADE) -
rest api errors in forms of django
For my project, I implemented the option to add articles for the user with rest api Now when I fill in the fields, it doesn't send and says you have to fill in the photo. What is problem? I'm gonna to give user add or edit of article option and for this plan , I created a page for that and I created form for add or edit; but i have a problem, when I fill fields and click button for send data, i got an error that wants fill image fields! model: # Article model class Article(models.Model): title = models.CharField(max_length=37, verbose_name='عنوان') category = models.ManyToManyField(Category, related_name='articles', verbose_name='دسته بندی') text = models.TextField(verbose_name='متن') images = models.ManyToManyField(Image, related_name='articles', verbose_name='تصاویر', blank=True, null=True) main_image = models.ImageField(upload_to='article/main/images', blank=True, null=True, verbose_name='تصویر اصلی') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.BooleanField(default=True, verbose_name='وضعیت') slug = models.SlugField(blank=True, null=True, unique=True, verbose_name="اسلاگ") class Meta: verbose_name = "مقاله" verbose_name_plural = "مقالات" def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.slug = slugify(self.title) super(Article, self).save() def show_image(self): if self.images: return format_html(f'<img src="{self.images.url}" width="47px" height="37px">') else: return format_html('<h3 style="color: red">بدون تصویر</h3>') show_image.short_description = ' تصویر' def __str__(self): return self.title form: # form of add an article class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('title', … -
Why Boostrap styles override my custom styles in django project though i list bootstrap earlier then custom?
<link rel="stylesheet" href="{% static "bootstrap.css" %}"> <link rel="stylesheet" href="{% static "base.css" %}"> <script type="text/javascript" src="{% static "js/bootstrap.min.js"%}"></script> {% block css %}{% endblock css %} in my base html i use this code, and then in index htmp i inherit it with {% extends 'base.html' %} {% load static %} and then add custom styles {% block css %} <link rel="stylesheet" href="{% static "wotsales/index.css"%}"> <link rel="stylesheet" href="{% static "wotsales/single-service.css"%}"> {% endblock css %} And though my custom styles go after bottstrap styles, bootstrap override my custom styles anyway:( I resolved this issue with !important keyword, but some people say that is not what i should do, so the question is what i should do instead? i tried also to remove some classes from my elements but it didn't help. I've just started using bootstrap. Is it supposed to use things like background color and color on elements that don't have any bootstrap classes? for example i have <div class="service-text"> <a href="{% url "service" service.slug %}"><h5>{{service.name}}</h5></a> <p>{{service.text}}</p> </div> It doesn't have css classes in itself only it's parents have classes like p-4, d-sm-flex. I only sought bootstrap applied when u use class on sertain element. Here is css for this part. .service-text{ … -
Django DRF problem with authentication using oauth2
I'm trying to setup user authentication with discord oauth2. Everything worked fine but now I get infinite loops between my auth endpoints, I've been struggling for hours and I can't figure why it doesn't work. It basically works like this : path("oauth2/login", discord_login, name="discord_login"), path("oauth2/login/redirect", discord_login_redirect, name="discord_login_redirect"), path("auth/user", get_authenticated_user, name='get_authenticated_user') 'oauth2/login' redirects me to discord oauth2 then it redirects me to 'auth/user' after authentication succeeded. #@login_required(login_url="/oauth2/login") def get_authenticated_user(request): print("get_authenticated_user : authenticated = ", request.user.is_authenticated) print("get_authenticated_user : request = ", request) authenticated_user = request.user print("get_authenticated_user : user = ", authenticated_user) serialized_user = serialize_user(authenticated_user) return JsonResponse(serialized_user) def discord_login(request): return redirect(settings.SOCIAL_AUTH_DISCORD_REDIRECT_URI) def discord_login_redirect(request): if request.user.is_authenticated: return redirect('/auth/user') user_data = exchange_code(request.GET.get('code')) if user_data is not None: user = authenticate(request, user=user_data) if user is not None: login(request, user) print("discord_login_redirect : User = ", user) print("discord_login_redirect : authenticated = ", request.user.is_authenticated) return redirect('/auth/user') else: return HttpResponse("Authentication failed") return HttpResponseForbidden("Authentication canceled by user") As I've chosen to implement @login_required to '/auth/user', I get infinite loops between the 2 endpoints, It seems that user is authenticated but it doesn't recognize it. Here are my logs : 11:49:27 web.1 | Attempting to authenticate user with Discord ID: xxx 11:49:27 web.1 | User with Discord ID %s found. xxx 11:49:27 … -
I think my url path and code is correct but still why images are not showing in admin pannel
You can see in the image the product image is not displaying My models.py: # from email.policy import default # from pyexpat import model from django.db import models # from unicodedata import decimal from shortuuid.django_fields import ShortUUIDField from django.utils.html import mark_safe from userauths.models import CustomUser STATUS_CHOICE=( ("process","Processing"), ("shipped","Shipped"), ("delevered","Delevered"), ) STATUS=( ("draft","Draft"), ("disable","Disable"), ("rejected","Rejected"), ("In_review","In Review"), ("published","Published"), ) RATING=( (1,"⭐☆☆☆☆"), (2,"⭐⭐☆☆☆"), (3,"⭐⭐⭐☆☆"), (4,"⭐⭐⭐⭐☆"), (5,"⭐⭐⭐⭐⭐"), ) # Create your models here. def user_directory_path(instance,filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Category(models.Model): cid=ShortUUIDField(length=10,max_length=100,prefix="cat",alphabet="abcdef") title=models.CharField(max_length=100,default="Food") image=models.ImageField(upload_to="category",default="category.jpg") class Meta: verbose_name_plural="Categories" def catagory_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Tags(models.Model): pass class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=models.TextField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) # tags=models.ForeignKey(Tags, on_delete=models.SET_NULL ,null=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=(self.price/self.old_price) * 100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product, on_delete=models.SET_NULL … -
Django: The image list is empty from dropzone when save
I tried to use multi photo upload that the process was worked. But i using dropzone.js, the files list is empty。There is my code showed below. models.py class AssetImage(models.Model): asset = models.ForeignKey('Asset', related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='assets/') forms.py class AssetImageForm(forms.ModelForm): image = forms.FileField(label='', required=False, widget=forms.HiddenInput(attrs={'multiple': True})) class Meta: model = AssetImage fields = ['image'] views.py def asset_create(request): show_modal = False if request.method == 'POST': form = AssetForm(request.POST) image_form = AssetImageForm(request.POST, request.FILES) files = [request.FILES.get(f'image[{i}]') for i in range(0, len(request.FILES))] print(files) # Get the list of files print("here") if form.is_valid() and image_form.is_valid(): name = form.cleaned_data['name'] if Asset.objects.filter(name=name).exists(): show_modal = True else: asset = form.save() for f in files: AssetImage.objects.create(asset=asset, image=f) return redirect('asset') else: form = AssetForm() image_form = AssetImageForm() locations = Location.objects.all() return render(request, 'pages/asset/asset_create.html', { 'form': form, 'image_form': image_form, 'locations': locations, 'show_modal': show_modal }) asset_create.html <!-- [ Main Content ] start --> <div class="row"> <div class="col-sm-12"> <div class="card"> <div class="card-header"> <h5>Add Asset</h5> </div> <div class="card-block"> <form method="post" enctype="multipart/form-data" class="needs-validation" novalidate> {% csrf_token %} <!-- Other form fields --> <div class="form-group"> <label for="id_name">{{ form.name.label }}</label> {{ form.name }} </div> <div class="form-group"> <label for="serialnumber">Serial Number</label> {{ form.serialnumber }} </div> <div class="form-group"> <label for="id_location2">Location</label> {{ form.location }} </div> <div class="form-group"> <label for="id_model">Model</label> {{ … -
Why is the post form not displayed? django
There are 3 applications: “publication”, “app_test” - the main one, “usercreatepost”, also users with authorization, but everything is ok there. application publication: views.py: ` from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseNotFound, Http404 from publication.models import Userpublication from django.urls import reverse from publication.forms import PostEditForm from usercreatepost.forms import PostForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.views import LoginView from django.contrib.auth.decorators import login_required from django.contrib import messages ` def indexs(request): posted = Userpublication.published.filter(is_published=1) return render(request, 'publication/post.html', {'post_lists': posted}) def show_post(request, post_slug, *args, **kwargs): post = get_object_or_404(Userpublication, slug=post_slug) data = { 'user': post.user, 'content': post.content, 'post': post, } return render(request, 'publication/post_user.html', data) @login_required def edit_post(request, post_slug): post = get_object_or_404(Userpublication, slug=post_slug) if request.user != post.author: messages.error(request, 'Вы не можете редактировать этот пост') return redirect('feeds', post_slug=post.slug) if request.method == 'POST': form = PostEditForm(request.POST, instance=post) if form.is_valid(): form.save() messages.success(request, 'Post success') # flash-message return redirect('feeds', post_slug=post.slug) # redirect else: form = PostEditForm(instance=post) return render(request, 'publication/edit_post.html', {'form': form}) def get_edit_url(self): return reverse('edit_post', kwargs={'post_slug': self.slug}) def post_detail(request, post_slug): post = get_object_or_404(Userpublication, slug=post_slug) return render(request, 'publication/post_user.html', {'post': post}) urls.py: from django.urls import path from . import views from .views import edit_post from usercreatepost.views import create_post urlpatterns = [ path('create/', create_post, name='create_posts'), path('<slug:post_slug>/', edit_post, name='feeds'), path('posts/<slug:post_slug>/', views.show_post, … -
ImageField and ModelForm image preview
I have Profile class in my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to=path_and_rename) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) and ProfileUpdateForm, for editing profile, in my forms.py: class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] I'm passing ProfileUpdateForm as context(p_form) to my html file and displaying it with crispy: profile.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block body %} <div class="post"> <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset> <legend class="border-bottom mb-4">Update Profile</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Update </button> <a class="btn btn-outline-danger" href="{% url 'user-delete' user.id %}">Delete Profile</a> </div> </form> <div class="border-top pt-3"> <small class="text-muted">Already Have an Account? <a href="{% url 'login' %}" class="ml-2">Sign In</a> </small> </div> </div> {% endblock body %} All profile has is image, so I'm displaying u_form(UserUpdateForm, for username and email updating) and right after it p_form(ProfileUpdateForm) , when image is chosen, it displays … -
Hosting in Django
I have a project in Django, which uses Selenium Web Driver. I am trying to host it on Render, however it is not initializing Web Driver Instance and hence the app is not working. chrome_driver_path = ChromeDriverManager().install() driver = webdriver.Chrome(service=Service(chrome_driver_path), options=options) This is the particular code which is throwing an error Are there any other platforms where I might be able to host for free and any tutorial for it? -
Django CRUD functionalities are not showing on the UI [closed]
I'm working on a django project (job board) , and the CRUD functionalities are not displaying on the UI. I have been researching and i can't quite find the solution. CSS file also doesn't make any changes . if you're able to clone the project and give me feedback of mistakes you can identify i'll be grateful. https://github.com/Mugao-joy/CodeRecruit i have verified url configurations,view functions also seem ok -
Django with django-cleanup cannot remove old files
There is a ZipPrice model describing the parts. The save method is overridden in the model, using PIL.Image, it converts the file uploaded through the form into jpeg format, creates an additional thumbnail file, and saves them under the required names. The django-cleanup module is also used to remove unnecessary files. models.py from PIL import Image class ZipPrice(models.Model): id = models.SmallAutoField(primary_key=True) name = models.CharField(max_length=200, unique=True) price = models.IntegerField() full_image = models.ImageField(upload_to='zips/', null=False, max_length=255, default=settings.DEFAULT_IMAGE['full']) small_image = models.ImageField(upload_to='zips/', null=False, max_length=255, default=settings.DEFAULT_IMAGE['small']) class Meta: db_table = 'zip_price' ordering = ['-full_image'] def save(self, **kwargs): with Image.open(self.full_image).convert('RGB') as img: output_full = BytesIO() output_small = BytesIO() exif = img.getexif() img.save(output_full, format='JPEG', exif=exif) img.thumbnail((250, 250)) img.save(output_small, format='JPEG', exif=exif) file_name = get_random_string(length=32) self.full_image = InMemoryUploadedFile(output_full, 'full_image', f'{file_name}_full.jpg', 'image/jpeg', sys.getsizeof(output_full), None) self.small_image = InMemoryUploadedFile(output_small, 'small_image', f'{file_name}_small.jpg', 'image/jpeg', sys.getsizeof(output_small), None) super().save() views.py @method_decorator(login_required, name='dispatch') class CatalogEditZip(UpdateView): model = ZipPrice form_class = ZipForm success_url = reverse_lazy('catalog_zip') template_name = 'repair/catalog_edit_zip.html' forms.py class ZipForm(forms.ModelForm): class Meta: model = ZipPrice fields = {'name', 'price', 'full_image'} labels = {'name': 'Name', 'price': 'Price', 'full_image': 'Image' } widgets = {'name': Textarea(attrs={'cols': 50, 'rows': 4})} If i edit a model instance through a form with a new file uploaded, then everything is ok. If without loading a … -
AssertionError in django-allauth app_settings.py during Django application startup
I'm encountering an AssertionError in my Django application when trying to start the development server. The error occurs in the django-allauth package, specifically in the settings.py file. I've already tried reinstalling django-allauth, checking dependencies, and reviewing my configuration without success. The error occurs when I try to make the ACCOUNT_EMAIL_VERIFICATION = 'mandatory' instead of "none" here is the traceback: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\Desktop\Main_project\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\Desktop\Main_project\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\User\Desktop\Main_project\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\User\Desktop\Main_project\venv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\Desktop\Main_project\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\Desktop\Main_project\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\Desktop\Main_project\venv\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\User\Desktop\Main_project\venv\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_m odule return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line … -
Django authentication | store user data for each object
I'm learning Django class-based views and can not find a mistake. I'm writing todo application using classes. After successful authentication, I navigate to the task creation page, where the user is displayed correctly. I can save tasks, and I see a list of all tasks. Then, I lod out of the application and login as ahotner user. However, I still see the same tasks that I created for the first user. Where did I go wrong? Why aren't the tasks separated based on the user? Thank you! models.py: from django.db import models from django.contrib.auth.models import User class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) create = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['complete'] urls.py: from django.urls import path from .views import TaskDetail, TaskList, TaskCreate, TaskUpdate, DeleteTask, CustomLoginView from django.contrib.auth.views import LogoutView urlpatterns = [ path('login/', CustomLoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('', TaskList.as_view(), name='tasks'), path('task/<int:pk>/', TaskDetail.as_view(), name='task'), path('create-task/', TaskCreate.as_view(), name='create_task'), path('task-update/<int:pk>/', TaskUpdate.as_view(), name='update_task'), path('task-delete/<int:pk>/', DeleteTask.as_view(), name='delete_task'), views.py: from django.urls import reverse_lazy from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.views import LoginView from .models import Task from django.contrib.auth.mixins import LoginRequiredMixin class CustomLoginView(LoginView): template_name = 'todo_app/login.html' fields = '__all__' redirect_authenticated_user … -
Django JWT: Keep Refresh Token Expiry Fixed on Refresh
I'm implementing JWT-based authentication for a Django website using Django Rest Framework (DRF) and Simple JWT. In my configuration, I've set the access token lifetime to five minutes and enabled token rotation. To handle token refreshing before expiry, I've implemented a JavaScript function that sends a request to refresh the access token using the refresh token. However, I've encountered an issue where rotating refresh tokens result in changes to their expiry dates, which prevents users from being automatically logged out when their refresh tokens expire. Here's the relevant JavaScript code for token refreshing: async function updateToken() { let authTokens = getTokensFromLocalStorage(); let response = await fetch("http://127.0.0.1:8002/api/login/refresh/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ refresh: authTokens.refresh }), }); let data = await response.json(); if (response.status === 200) { setTokensToLocalStorage(data); // Save updated tokens to local storage setUser(jwtDecode(data.access)); // Update user } else { removeUser(); } } let fourminutes = 1000 * 60 * 3; // Change to 3 minutes let interval = setInterval(() => { if (authTokens) { updateToken(); } else { clearInterval(interval); } }, fourminutes); And here's a snippet of my Simple JWT settings in Django: SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(weeks=52), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, … -
how to save an instance after all processes are completed (including Stripe checkout session)?
#views @transaction.atomic def booking_form(request, id): franchise_id = id form = BookingForm(franchise_id=franchise_id) if request.method == 'POST': form = BookingForm(request.POST, franchise_id=franchise_id) if 'paynow-btn' in request.POST: if form.is_valid(): instance = form.save(commit=False) instance.payment_status = 'due' instance.booking_status = 'unconfirmed' instance.franchise_id = franchise_id #other code #stripe connect [standard account] direct charges connected_account_id = create_or_get_connected_account(franchise_id) success_urlpattern = reverse('booking:booking_successful', kwargs={'id': franchise_id}) success_urlpath = request.build_absolute_uri(success_urlpattern) # Create a Stripe checkout session print("Before checkout session creation") checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ "price_data": { "currency": "gbp", "unit_amount": int(instance.total_amount * 100), "product_data": { "name": f'Booking for {instance.full_name}', }, }, "quantity": 1, }], payment_intent_data={ 'metadata': { 'booking_id': instance.id, }, 'application_fee_amount': int(instance.total_amount * (franchise.payout_percentage / 100) * 100), }, mode='payment', # Create a Stripe checkout session success_url=success_urlpath, cancel_url=settings.PAYMENT_CANCEL_URL, stripe_account=connected_account_id, ) print("After checkout session creation") print(checkout_session) # Check if the checkout session was successfully created if checkout_session and checkout_session.status == 'completed': # Save the instance only if the checkout session is completed instance.save() return redirect(checkout_session.url) else: # Handle the case where the checkout session creation failed messages.error(request, 'Failed to create the checkout session. Please try again.') return redirect(reverse('booking:booking_form', kwargs={'id': franchise_id})) Hi, I'm trying to save the booking object instance after all the processes are completed! It doesn't work and leaves me with Failed to create … -
How can RetrieveUpdateDestroyAPIView supports POST?
I successfully implement Rest API to store IP address and Mac address mapping. The GET/PATCH/DELETE methods are supported, for example: curl -X GET -H 'Content-Type: application/json' -d '{"ip_address": "192.168.1.1"}' http://127.0.0.1:8000/api/ipmac/ curl -X PATCH -H 'Content-Type: application/json' -d '{"ip_address": "192.168.1.1", "mac_address": "aa:bb:cc:dd:ee:ff"}' http://127.0.0.1:8000/api/ipmac/ However, POST is not supported in RetrieveUpdateDestroyAPIView. I don't wanna create another endpoint for POST method. How to have only one endpoint and support all the methods? Here is my code: models.py from django.db import models class IPMacMapping(models.Model): ip_address = models.GenericIPAddressField(unique=True) mac_address = models.CharField(max_length=17, unique=True) created_at = models.DateTimeField(auto_now_add=True) serializers.py from rest_framework import serializers from .models import IPMacMapping class IPMacMappingSerializer(serializers.ModelSerializer): class Meta: model = IPMacMapping fields = '__all__' urls.py from django.urls import path from .views import IPMacMappingRetrieveUpdateDestroy urlpatterns = [ path('ipmac/', IPMacMappingRetrieveUpdateDestroy.as_view(), name='ipmac-list-create') ] views: from rest_framework import generics from .models import IPMacMapping from .serializers import IPMacMappingSerializer from django.shortcuts import get_object_or_404 class IPMacMappingRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): queryset = IPMacMapping.objects.all() serializer_class = IPMacMappingSerializer lookup_url_kwarg = "ip_address" def get_object(self): result = get_object_or_404(IPMacMapping, ip_address=self.request.data["ip_address"]) return result -
How to set up periodic tasks automatically
I have a celery task in one of my django apps. My django, celery and django-celery-beat services are ran in their own docker containers. Since this is a legacy project, I now assume they interact smoothly already with the current config. What I want is that when the app gets deployed/started it finds my perioidc tasks automatically and registers them in the django celery beat database tables. My task: # project.an_app.tasks.generate_statements from config import celery_app @celery_app.task(...) def generate_statements(): print("Statment generation runs. Current date and time:", datetime.now()) # my task logic This is one solution I've found. But this only gets triggered when I try to access the Periodic tasks tables via admin site (probably would be triggered other ways which interact with these tables, but I don't want to "wait" for anything like that). def schedule_task(): interval, _ = IntervalSchedule.objects.get_or_create( every=30, period=IntervalSchedule.SECONDS, ) PeriodicTask.objects.get_or_create( interval=interval, name="generate-statements", task=project.an_app.tasks.generate_statements, ) schedule_task() Looking at our legacy code I've found this, this one looks from project.an_app.tasks import generate_statements @celery_app.on_after_finalize.connect def register_periodic_tasks(sender, **kwargs): """ Callback for Celery to register periodic tasks. """ sender.add_periodic_task( 30.0, task=generate_statements, name="generate-statements", ) The task of the copied code is indeed already django_celery_beat_periodictask table. So I would say this works. However … -
Reusing the types from the DjangoObjectType in the graphene
I have created the PreferencesNode from the DjangoObjectType which contains the gateway provider as TextChoices. class GatewayProvider(models.TextChoices): STRIPE = "stripe", "Stripe" RAZORPAY = "razorpay", "Razorpay" class PreferencesNode(DjangoObjectType): class Meta: model = Preferences exclude_fields = ("user_id",) Now I want to use AccountPreferencesGatewayProviderChoices enum (created via PreferencesNode). How can I do this? Currently I am creating another enum inheriting graphene.Enum. class GatewayProviderEnum(graphene.Enum): STRIPE = GatewayProvider.STRIPE.value RAZORPAY = GatewayProvider.RAZORPAY.value But this is creating redundant enum type. -
Polling a Celery Task with Ajax
I have a Celery task that populates a PostgreSQL database over the course of a few minutes. I want to retrieve the current data from the database in a Django view and send it to a template where it will be constantly re-displayed according to the progress of the task. So, I want to update the template in real-time. Currently, I have a view that calls the Celery task and gets the result of the task. It then renders the template and sends it the result of the task in the form of a string, as well as the id of the task. I am not very familiar with AJAX, but from what I've read I will need another view that AJAX will call to retrieve the most up-to-date result of the task. Here is the code so far: View that renders the template: def dashboard(request): result = prepare_database.delay() result_str = result.get() return render(request, 'appname/template.html', {'task_id': result.task_id(), 'str': result_str}) View that gets the current data def current_data(request): task_id = request.GET.get('task_id') if task_id: async_result = AsyncResult(task_id) return JsonResponse({'data': async_result.get()}) Ajax to poll the task (again, very new to AJAX): $.ajax({ url: '/current_data/', method: 'GET', data: { data: 'data' }, success: function(response) … -
How to get 'value' attribute of tag <input> in Django?
I have this view function to delete task from ToDo application: def delete_task(request): if request.method == 'POST': task = Task.objects.get(pk=request.POST['delete']) task.delete() return HttpResponseRedirect(reverse('todoapp:index')) else: tasks = Task.objects.all() return render(request, 'index.html', {'tasks': tasks}) I get 'value' of tag Here is my html: <form action="{% url 'todoapp:delete_task' %}" method="post"> {% csrf_token %} <input type="submit" name="delete" value="{{ task.id }}" class="btn btn-primary"> </form> And my button shows id of task instead of word 'Delete' any ideas how I can get data of tag <input> in another way? Thank you advance!! -
How do i apply multiple filters on my website
THIS IS MY HTML CODE <div class="container"> <button id="buttonH" class="buttonhindi" onclick="toggleFilterLanguage('H')">Hindi</button> <button id="buttonE"class="buttonhindi" onclick="toggleFilterLanguage('E')">English</button> <button id="buttonP" class="buttonhindi" onclick="toggleFilterLanguage('P')">Punjabi</button> </div> <div class="container"> <button id="buttonA" class="buttonhindi" onclick="toggleFilter('A')">18+ / A </button> <button id="buttonUA" class="buttonhindi" onclick="toggleFilter('UA')">UA</button> </div> <div class="row" id="movieList"> </div> <div class="end"> <p class="pp"> Copy right @2024 screen and fun limited.<br><br> The content and images used on this site are copyright and protected and copyright vest with the respective owner. the usage of content and images<br> on this website is intented to promote the works and no endosments of the artist shall be implied.</p> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // Function to toggle dropdown menu function toggleDropdown() { var dropdownMenu = document.querySelector('.dropdown-menu'); dropdownMenu.style.display = (dropdownMenu.style.display === 'block') ? 'none' : 'block'; } // Function to select city and fetch movies function selectCity(city) { document.getElementById('buttonA').classList.remove('buttonhindiClicked'); document.getElementById('buttonUA').classList.remove('buttonhindiClicked'); document.getElementById('selectedCity').innerText = city; document.getElementById('selectedCity2').innerText = city; toggleDropdown(); fetchMovies(city); } // Function to fetch movies for the selected city async function fetchMovies(city) { try { const response = await fetch(`/get_movies/${city}`); // Replace with your endpoint URL const data = await response.json(); displayMovies(data); } catch (error) { console.error('Error fetching movies:', error); } } // Function to display movies function displayMovies(movies) { const movieList = document.getElementById('movieList'); movieList.innerHTML = ''; movies.forEach(movie => { … -
Strange issue using CryptoJS, encrypts fine but decrypts just shows a blank file
I'm creating a browser based Django app that allows a user to upload some files to encrypt and then to decrypt using a password. I have managed to get the encryption part working but when decrypting the files all return blank. I've read through the CryptoJS docs and searched around but can't find a solution that works. I'm sure this is just a minor mistake on my behalf but would really appreciate the help. Please ignore the public/private key encryption stuff, one problem at a time :') // Event listener for encrypt button click document.getElementById('encryptBtn').addEventListener('click', function() { // Retrieve encryption mode, encryption type, and password from input fields var mode = document.getElementById('modeSelect').value; var encryptionType = document.getElementById('encryptionType').value; var password = document.getElementById('password').value; // Retrieve selected files var files = document.getElementById('fileInput').files; // Create a new JSZip instance var zip = new JSZip(); // Total number of files to process var totalFiles = files.length; // Counter to track processed files var filesProcessed = 0; // Initialize SweetAlert2 progress popup Swal.fire({ title: mode === 'encrypt' ? 'Encrypting Files' : 'Decrypting Files', html: 'Processing: 0 / ' + totalFiles, allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } }); // Loop through each file for (var i … -
"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" in post method
(https://i.stack.imgur.com/4OABY.png) views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from .models import note from .serializers import noteSerializer @api_view(['GET']) def getroute(request): routes = [ { 'Endpoint':'/note/', 'method':'GET', 'body':None, 'description':'Returns an array of notes'}, { 'Endpoint':'/note/id', 'method':'GET', 'body':None, 'description':'Returns an single note object'}, { 'Endpoint':'/note/create/', 'method':'POST', 'body':{'body':""}, 'description':'creates a single note object'}, { 'Endpoint':'/note/id/update', 'method':'PUT', 'body':{'body':""}, 'description':'updates a single note object'}, { 'Endpoint':'/note/id/delete', 'method':'DELETE', 'body':None, 'description':'deletes a single note object'} ] return Response(routes) @api_view(['POST']) def createnote(request): print("request.data") data = JSONParser().parse(request) serializer = noteSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @api_view(['GET']) def getNotes(request): notes = note.objects.all().order_by('-updated') serializer = noteSerializer(notes,many=True) return Response(serializer.data) @api_view(['GET']) def getNote(request,pk): notes = note.objects.get(id=pk) serializer = noteSerializer(notes,many=False) return Response(serializer.data) @api_view(['PUT']) def updatenote(request,pk): data =request.data notes =note.objects.get(id=pk) serializer = noteSerializer(instance=notes,data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @api_view(['Delete']) def deletenote(request,pk): notes = note.objects.get(id=pk) notes.delete() return Response("Note deleted") models.py from django.db import models class note(models.Model): body = models.TextField(null=True,blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) serializers.py from rest_framework.serializers import ModelSerializer from .models import note class noteSerializer(ModelSerializer): class Meta: model = note fields = '__all__' atfirst I used the api/todo/create url and it showed me "detail": "Method "GET" not allowed." and I added get method in the apiview … -
How can I associate existing child to parent in Django
I trying to build an IPAM by Django. I will create the Subnet model and create the IPAddress by the post_save signal. class Subnet(models.Model): usage = models.CharField('Usage', max_length=40) vlan = models.PositiveSmallIntegerField('vlan') cidr = models.CharField('CIDR', max_length=18) gateway = models.GenericIPAddressField('Gateway') def __str__(self): return str(self.vlan) + ' ' + self.usage class IPAddress(models.Model): subnet = models.ForeignKey(Subnet, on_delete=models.CASCADE, verbose_name="Subnet") ip = models.GenericIPAddressField('IP Address', unique=True) mac = models.CharField('Mac Address', max_length=17, blank=True, null=True) vm = models.ForeignKey(VM, on_delete=models.SET_NULL, blank=True, null=True) class Meta: indexes = [ models.Index(fields=['ip','mac']), models.Index(fields=['ip'], name='vm_ip_idx'), ] verbose_name = 'IP Address' verbose_name_plural = 'IP Addresses' def __str__(self): return str(self.ip) @receiver(post_save, sender=Subnet) def create_ip(sender, instance, created, **kwargs): if created: except_ip = ["0","255"] for ip in ipaddress.IPv4Network(instance.cidr): if (str(ip) != str(instance.gateway)) and (str(ip).split('.')[-1] not in [i for i in except_ip]): IPAddress(subnet=instance, ip=str(ip)).save() class VM(models.Model): vm_name = models.CharField('VM Name', max_length=60) def __str__(self): return str(self.vm_name) What I want to do: I created a Subnet with CIDR 172.0.0.0/24 and will automatically create total 255 IPAddress (172.0.0.1-172.0.0.254). And now I want to attach one of the IPAddress to a VM and update the MAC address in admin page. I tried to edit in admin.py class VMIPAdminForm(forms.ModelForm): ip = forms.ModelChoiceField(queryset=IPAddress.objects.all(), empty_label="IP Address") mac = forms.CharField(max_length=17, required=False, label="MAC Address") class Meta: model = IPAddress … -
Django Daphne – Database connections max out + "took too long to shut down"
I'm implementing a messaging system, but experiencing the following two errors on the dev server: "Application instance <...> took too long to shut down and was killed." The database connections get increased on every new EventSource that is created, despite it being closed on the frontend. Here is my code: Backend: @transaction.non_atomic_requests async def stream_chat_messages(request: HttpRequest) -> StreamingHttpResponse: async def event_stream(): SLEEP_INTERVAL = 0.3 """ We use this function to send a continuous stream of data to the connected clients. """ async for message in get_existing_messages(): yield message last_id = await get_last_message_id() # Continuously check for new messages while True: new_messages = _get_messages().filter(id__gt=last_id) async for message in new_messages: yield f"data: {json.dumps(message)}\n\n" last_id = message["id"] await asyncio.sleep(SLEEP_INTERVAL) return StreamingHttpResponse(event_stream(), content_type="text/event-stream") Frontend (React): const [currentChatroom, setCurrentChatroom] = useState<ChatroomProps | null>( null, ); useEffect(() => { setMessages([]); if (!currentChatroom) return; let sse = new EventSource( `.../stream-chat-messages/?chatroom=${currentChatroom.id}`, ); sse.onmessage = (event) => { // ... }; sse.onerror = () => { sse.close(); }; return () => { sse.close(); }; }, [currentChatroom?.id]); What am I doing wrong here? Every time the page is loaded, a new database connection is created, but it keeps persisting. Thanks!