Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unwanted whitespace in Django urls
I have an unwanted whitespace in my url pattern and I think this is making trouble when I try to handshake my Flutter app with my Django backend. I know there are similar questions in answered on this, but I could not find where this comes from or how to fix it.. These are my URL patterns and when I try to handshake with the WebSocket, I', getting the following error in Django terminal: Not Found: /ws/chat_app/sjfAmH "GET /ws/chat_app/sjfAmH HTTP/1.1" 404 4349 Those are my URL patterns I have an Django app called chat_app, where I have defined my WebSocket consumer class. Then I added the routing, pointing at that consumers class in my routing.py file: from django.urls import re_path from .consumers import ChatConsumer # The WebSocket URL pattern for chat rooms is defined by this code websocket_urlpatterns = [ re_path(r'chat_app/(?P<unique_id>\w+)/$', ChatConsumer.as_asgi()), ] Also, I have added the chat_app into settings.py installed apps and defined the URL path in my Django project urls.py: from django.contrib import admin from django.urls import include, path from chat_app.routing import websocket_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), ..., path('ws/', include(websocket_urlpatterns)), ] -
Customize a delete selected confirmation page in the Django admin site
I need to show an additional alarm message in the delete selected confirmation page. The message should not appear always. It shoud appear depending on certain conditions. I copied the delete_selected_confirmation.html template from the django/contrib/admin/templates/admin directory. I can now add an additional alarm message. But the message should appear depending on certain conditions. Which function inside class MyModelAdmin(admin.ModelAdmin) should I use? E.g., to set context for the delete_confirmation.html template I use def render_delete_form(self, request, context). Which function should I use for the delete_selected_confirmation.html template? -
How to make model with list of different data type
I'm really new to django, especially SQL, I usually use NO SQL as a database, I want to know how to create a model like this? { "title" : "Smarthome by me", "description" : "A Hello World App", "publishedAt" : "2024-02-18 20:14:34.208116", "modifiedAt" : "2024-02-18 20:14:34.208116", "contents" : [ { "type" : "ImageBased", "name" : "im1 it's a lake with two mountain", "content" : "img.png" #Store some Image field }, { "type" : "TextBased", "name" : None, "content" : "" #Store some Text field }, { "type" : "URLTextBased", "name" : None, "content" : "https://www.youtube.com/watch?v=AswXiy8JCsI&t=1808s" #Store some Text field }, { "type" : "VideoBased", "name" : None, "content" : "video.mp4" #Store some File field }, ] } Main needs: The order of content must match what is posted publishedAt cannot be modified modifiedAt must be updated every time there is an update -
Image is not showing in admin pannel
The image: My index.html: <div class="product-main"> <h2 class="title">New Products</h2> <div class="product-grid"> {% for i in products %} <div class="showcase"> <div class="showcase-banner"> <a href="#"> <img src="{{ i.image.url }}" alt="" /> <img src="{{ i.image.url }}" alt="" /> </a> <p class="showcase-badge">15%</p> </div> </div> {% endfor %} Admin.py: from django.contrib import admin from core.models import * # Register your models here. class ProductImagesAdmin(admin.TabularInline): model= ProductImages class ProductAdmin(admin.ModelAdmin): inlines=[ProductImagesAdmin] list_display=['user','title','product_image','price','featured','product_status'] class CategoryAdmin(admin.ModelAdmin): list_display=['title','catagory_image'] class VendorAdmin(admin.ModelAdmin): list_display=['title','Vendor_image'] class CartOrderAdmin(admin.ModelAdmin): list_display=['user','price','paid_status','order_date','product_status'] class CartOrderItemsAdmin(admin.ModelAdmin): list_display=['order','invoice_num','product_status','item','image','qty','price','total'] class ProductReviewAdmin(admin.ModelAdmin): list_display=['user','product','review','rating','date'] class wishlistAdmin(admin.ModelAdmin): list_display=['user','product','date'] class AddressAdmin(admin.ModelAdmin): list_display=['user','address','status'] admin.site.register(Product,ProductAdmin) admin.site.register(Category,CategoryAdmin) admin.site.register(Vendor,VendorAdmin) admin.site.register(CartOrder,CartOrderAdmin) admin.site.register(CartOrderItems,CartOrderItemsAdmin) admin.site.register(ProductReview,ProductReviewAdmin) admin.site.register(wishlist,wishlistAdmin) admin.site.register(Address,AddressAdmin) 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) … -
'<', "<!DOCTYPE "... is not valid JSON Promise.then (async) error in Django
I m currently learning Django and i m trying to build an ecommerce website. I m trying to figure out why am i getting this error in my console.I m trying to do a fetch call and trying to send data to the url by name of update_item and i m expecting the view function to return the json response in my console but i m constantly getting this error. Can someone pls help. **This is my js file. ** var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser'){ console.log('User is not authenticated') }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json() }) .then((data) => { console.log('data:', data) }); } This is my views.py file. from django.shortcuts import render from django.http import JsonResponse from .models import * # Create your views here. def store(request): products = Product.objects.all() context = {'products':products} return render(request,'store/store.html',context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = … -
Website images not displaying after server subscription was renewed
So I hosted a website for my client on using linode. It's made using Django and I used the Nginx and gunicorn technologies for hosting. After we renewed our subscription cuz we forgot to pay our monthly bill for the server, the website was down. We renewed our subscription but the site is still not displaying the images I added. The rest of the functionality seems fine but the images just don't show up. The website is https://scopeplus.org . I looked up a lot of stuff online and found the issue might be linked with the permissions but the permissions are fine: (venvPath) root@localhost:~/scope_website# ls -l scope/static/scope/ total 76152 -rwxr-xr-x 1 www-data www-data 9784828 Jan 11 20:14 10.JPG -rwxr-xr-x 1 www-data www-data 8516385 Jan 11 20:14 11.JPG -rwxr-xr-x 1 www-data www-data 251044 Jan 11 20:14 12.jpg -rwxr-xr-x 1 www-data www-data 298429 Jan 11 20:14 13.jpg -rwxr-xr-x 1 www-data www-data 406636 Jan 11 20:14 1st.jpg -rwxr-xr-x 1 www-data www-data 9409731 Jan 11 20:14 2nd.JPG -rwxr-xr-x 1 www-data www-data 8956352 Jan 11 20:14 3rd.JPG -rwxr-xr-x 1 www-data www-data 8661715 Jan 11 20:14 4.JPG -rwxr-xr-x 1 www-data www-data 9226816 Jan 11 20:14 5.JPG -rwxr-xr-x 1 www-data www-data 202005 Jan 11 20:14 6.jpg -rwxr-xr-x … -
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) …