Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
microsoft sso is not working in social-auth-app-django=5.4.0 in Django
We have used the social-auth-app-django=5.4.0 package for sso both Microsoft and google. The Google SSo is working properly but Microsoft SSO is not working. It shows the below error while trying to SSO. Backend not found Request Method: GET Request URL: http://0.0.0.0:9090/login/microsoft-oauth2/ Raised by: social_django.views.auth Using the URLconf defined in jenkins_mail.urls, Django tried these URL patterns, in this order: app/ [name='home'] admin/ login/<str:backend>/ [name='begin'] The current path, login/microsoft-oauth2/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.``` -
Python: Compare date and bulk update some fields
I created a refresh function for my Event Module, where if the Event date already passed, it will bulk update the status to 0. models.py class Events(models.Model): id = models.AutoField(db_column='id', primary_key=True) title = models.CharField(max_length=45, blank=True, null=True) venue = models.CharField(max_length=45, blank=True, null=True) date = models.DateTimeField(max_length=45, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to=eventpath, blank=True, null=True) manager = models.CharField(max_length=100, blank=True, null=True) attendees = models.CharField(max_length=100, blank=True, null=True) date_posted = models.DateTimeField(max_length=45, blank=True, null=True) status = models.BooleanField(default=1) This is how I add an event. def uploadEvent(request): if request.method == "POST": item = Events() item.title = request.POST.get('title') item.venue = request.POST.get('venue') date = request.POST.get('date') date_object = datetime.datetime.strptime(date, '%a %b %d %Y %I:%M %p') item.date = date_object item.manager = request.POST.get('manager') item.attendees = request.POST.get('attendees') item.description = request.POST.get('description') date_posted = datetime.datetime.strptime(date, '%a %b %d %Y %I:%M %p') item.date_posted = date_posted if len(request.FILES) != 0: item.image = request.FILES['image'] item.save() return redirect('/amsai/events/') return render(request, 'admin/events_add.html') And this is how I want to update all events. I converted the obj.date to date() def refreshEvent(request): events = Events.objects.all() status = 0 date = datetime.datetime.today().date() if events: for obj in events: if obj.date.date() < date: Events.objects.filter(*****).update(status=status) return redirect('/amsai/events/') The problem is how can I filter those passed dates? I don't know what to … -
Django - how do I update the database with an expression of a field?
We are using Django for our website, and I want to remove personal information from one of the databases. For example I want to change email addresses to their id + "@example.com". I can do it with Python: for e in UserEmailAddress.objects.all(): e.email="{}@example.com".format(e.id) e.save() But it takes a long time if I have many users. Is there a way to do it with UserEmailAddress.objects.all().update(...) with one command that will do the same thing? I tried to use the F class but it didn't work, I probably didn't use it correctly. I also want to filter and exclude by these expressions - for example, query all users except users where their e.email=="{}@example.com".format(e.id). I tried both queries: from django.db.models import F el = UserEmailAddress.objects.all().filter(email="{}@example.com".format(F('id'))) print(len(el)) el = UserEmailAddress.objects.all().exclude(email="{}@example.com".format(F('id'))) print(len(el)) Both of them return incorrect results (not what I expected). -
Problems with Django Channels and signals
I have Vue script that retrieve notifications from Django and should display and update the notification count in a badge. I use Django channels, the Django version is 4.2.8, channels version 4, uvicorn 0.26 and websockets 12.0. To update the notification count I use a Django signal so when a new notification is added from the admin or another source, the post_save event gets triggered and the method update_notification_count in consumers.py should be called. Everything works fine from the browser, but when I add a new notification from the Django admin, the frontend does not get updated, that is, the update_notification_count is not called even if the event post_save gets triggered. Here is the code. First my config: # settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', 'CONFIG': { 'capacity': 1000, 'expiry': 60, }, } } Now asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from notifapi.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(websocket_urlpatterns), }) The signals.py file is coded that way from django.dispatch import receiver from django.db.models.signals import post_save from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from .models import NotifyModel as Notification from .consumers import NotificationConsumer @receiver(post_save, sender=Notification) def notification_created(sender, … -
Is Django (especially Django Rest Framework) really synchronous?
I know some concepts that Django (DRF) is synchronous and it has some workers, but I know little about this. I tried to verify this and created this view at the address http://localhost:8000/my-view/: def my_view(request): # Simulate some time-consuming task time.sleep(10) return HttpResponse("Response after 10 seconds") I proceeded to open 7 terminals and execute the same command on each of them within a range of 1-2 seconds (almost simultaneously): curl http://localhost:8000/my-view/ -H 'Content-Type: application/json' --> and the result was that in each terminal I received response in 10-12 seconds. Here is the question, if Django is synchronous so why it did not take 70 seconds to execute these requests one by one? The only explanation I can think of is that it uses multithreading. -
Load Large JSON File in Django
I try to load large json file (250mb) and when i open in django and use len() the size is 1060000, but after i use for loop and save it to database, the total data is always changing sometimes 1052000 or 1057000. How could this happen ? -
django oscar order change page keeps loading. getting 502 Bad Gateway
I am getting 502 Bad Gateway. I am using a django oscar application. its running on docker. i also have nginx configured in a container. All the other pages work, except order change page. http://localhost:888/admin/order/order/60/change/ When i looked into gunicorn logs, it is showing [CRITICAL] WORKER TIMEOUT. Maybe a memory leak or an infinite loop? But i dont see any stack trace, or where it is getting this error. How do i debug this? Its a faily large application. Any help is appreciated. version: '3' services: web: restart: unless-stopped build: dockerfile: local.Dockerfile context: ./src working_dir: /opt/supplyme_core command: | sh -c " while ! timeout 1 bash -c 'cat < /dev/null > /dev/tcp/db/5432'; do sleep 1; done while ! timeout 1 bash -c 'cat < /dev/null > /dev/tcp/e_search/9200'; do sleep 1; done python manage.py collectstatic --noinput /usr/local/bin/gunicorn project.wsgi:application --timeout 300 -w 2 -b 0.0.0.0:888 & \ python service_runner.py api.web.service -c /opt/supplyme_core/api/conf/local_config.yml" ports: - "0.0.0.0:2220:22" volumes: - ./src/supplyme_core:/opt/supplyme_core - ./.pycharm_helpers:/root/.pycharm_helpers - public:/opt/public - ./src/scripts/local/freeze.py:/opt/freeze.py:ro - ./.ssh:/root/.ssh db: restart: unless-stopped build: context: ./pg/x64 environment: POSTGRES_PASSWORD: postgres expose: - "5432" ports: - "0.0.0.0:5432:5432" e_search: restart: unless-stopped build: ./elastic environment: - discovery.type=single-node - xpack.security.enabled=false - xpack.monitoring.enabled=false - xpack.watcher.enabled=false expose: - "9200" kibana: image: kibana:7.14.1 expose: … -
What is the best way to run a python file on a front end?
I am developing a medical app that uses sci-kit for machine learning. I have developed a Python file for the logic of my app. It takes input a couple of times from the command line and then uses the responses to predict what disease a user is suffering from. The problem I'm having is how to put it on a front-end so that anyone can use it. I have tried using Django, ReactJS, Flask, and PyScript so far, and the main problem I'm facing is that all tutorials are showing me how to support scripts in Python with only one input. My app predicts what symptoms the user might be suffering from next, and so needs to pass the next question to the front end while remembering what state it is in, requiring multiple inputs. I am looking for any frameworks, api's or general info that might be useful in my situation. Any help would be appreciated. -
django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied
while trying to connect my postgresql database with django i'm facing this error django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied this is my settings.py `DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_USER_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), } }` this is my .env file `export DB_NAME=demo export DB_USER=postgres export DB_USER_PASSWORD=12345678 export DB_HOST=localhost` -
Class() got an unexpected keyword argument 'unique_id', when trying to connect to a WebSocket
I'm trying to connect to my Django WebSocket, but I keep getting the following exception: TypeError: ChatConsumer() got an unexpected keyword argument 'unique_id' "GET /ws/chat_app/sjfAmH/ HTTP/1.1" 500 64965 I'm basically following a tutorial and that is how the guy does it in there. I have also looked at other implementations and I find it as the same way.. I'm new at using WebSockets, I would appreciate any kind of help. Thanks in advance! This is my ChatConsumer class: # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Message from room_app.models import Room class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.unique_id = self.scope['url_route']['kwargs']['unique_id'] self.room_group_name = f'chat_{self.unique_id}' # Check if the room exists in the database if not await self.room_exists(): await self.close() return # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Save message to database Message.objects.create( room=self.unique_id, user=self.scope['user'], content=message ) # Send message to room group self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': self.scope['user'].username } ) # Receive message from room group def chat_message(self, event): message = event['message'] username = … -
Django PasswordResetView not Sending Email (Django 5, Gmail SMTP)
Problem: I'm facing an issue where the PasswordResetView in my Django project is not sending emails. I have tested my email configurations using the Django shell and a custom email route, and emails are sent successfully. However, the default PasswordResetView and the password reset page in the Django administration panel do not send emails. Environment: Django 5 Gmail SMTP Using a custom user model Email Settings (settings.py): EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD") DEFAULT_FROM_EMAIL = os.environ.get("EMAIL_HOST_USER") SERVER_EMAIL = os.environ.get("EMAIL_HOST_USER") # Custom User Model AUTH_USER_MODEL = "accounts.CustomUser" Views and URLs: I have tried using a custom view (custom_password_reset) and the default PasswordResetView, but both do not send emails. # views.py def custom_password_reset(request): return auth_views.PasswordResetView.as_view( template_name="accounts/password-reset.html", success_url=reverse_lazy("accounts:password-reset-done"), extra_email_context={"request": request}, )(request) # urls.py path("password-reset/", views.custom_password_reset, name="password-reset"), Additional Information: I have tested sending emails from the Django shell, and it works. I have allowed less-secure app access for my Gmail account. I appreciate any insights or suggestions on resolving this issue. Thank you! -
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 …