Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my signup data are not saving in database table auth_user
I have created a signup form using django default django.contrib.auth signup form but it's not saving any data from sign up form.i watched many tutorial but couldn't reslove it tried deleting all my previous migrations as well but still facing this is issue , i am using mysql as my database kindly help if one can my form.py class SignUpForm(UserCreationForm): class Meta: model = User fields = ['username', 'email',] views.py from django.shortcuts import render from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.forms.utils import ErrorList from django.http import HttpResponse from .forms import LoginForm, SignUpForm def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "accounts/login.html", {"form": form, "msg" : msg}) def signup(request): if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): form.save() return redirect('admin') else: form = SignUpForm() else: form = SignUpForm() return render(request, "accounts/register.html", {"form": form}) signup template {% extends "layouts/base-fullscreen.html" %} {% load static %} {% block title %} Login {% endblock … -
Activating virtual environment for django in command line versus activating it in the Atom terminal
I am having a hard time activating virtual environment, after I have created it. The thing is, that when I try to activate virtual environment in command line, it works - virtualenvironmentname\Scripts\activate But when I try to run the same command in Atom, (I am using the Terminus package in order to be able to run the terminal inside of Atom) I get this message - (path) cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. I was trying to run it by using slightly different commands such as - activate virtualenvironmentname or activate (virtualenvironmentname) , but it did not work. I was further investigating a little more and I have found some clues, that I might need to change some script execution policies, but I am little bit afraid to do so, because I do not want to mess up my computer since I am just a beginner when it comes to system configuration. Could anybody please tell me, how could I fix this problem? It would be really convenient for me to be able to run the virtual environment from Atom, since I will be writing my Python and … -
Cann't send email in production
I am developing online shop and everything worked fine on local machine.Client add item to cart, enter his credentials click 'Make Order' and than order confirmation should be sent to his email. And it was working fine, even with redis + celery, but since when I've deployed project to server (linode.com), order confirmation doesn't work. Worker took tasks but never execute this. I thought it was due to celery, and I've made decision to make sending email without task manager and queue. But it didn't help. I use UFW firewall in the server: To Action From -- ------ ---- 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere Anywhere ALLOW 96.126.119.66 443 ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 443 (v6) ALLOW Anywhere (v6) I get error like this: [Errno 110] Connection timed out Hope you will help me to understand the issue Traceback: Environment: Request Method: POST Request URL: https://bauerdress.ru/orders/create/ Django Version: 3.1 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'shop.apps.ShopConfig', 'cart.apps.CartConfig', 'orders.apps.OrdersConfig', 'wishlist.apps.WishlistConfig', 'widget_tweaks', 'crispy_forms', 'information.apps.InformationConfig', 'promotion.apps.PromotionConfig', 'django_filters', 'email_sub.apps.EmailSubConfig', 'django_simple_coupons', 'ckeditor', 'flower', 'allauth', 'allauth.account', 'allauth.socialaccount'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/kirill/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", … -
How to filter Posts Query in order to just see the posts of friends and Myself in Django
Guys I have built up a friendship system in my social media and it works properly. The last step is to restrict each user to see the posts from his or her own and friends. The following shows everything which I have guessed would be important. The view for the posts: class PostListView(LoginRequiredMixin,ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' def get_queryset(self): friends = User.objects.get(id=self.request.user.id).profile.friends.all() posts = Post.objects.filter(author = self.request.user) return posts def get_friends(self): friends = User.objects.filter(profile.friends).all() return friends the Post model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) content= models.TextField() image = models.ImageField(blank=True, null=True, upload_to='post_pics') likes = models.ManyToManyField(User, related_name='blog_post') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def save(self, *args, **kwargs): super().save() if self.image: img = Image.open(self.image.path) if img.height > 900 and img.width > 900: output_size = (900,900) img.thumbnail(output_size) img.save(self.image.path) def get_absolute_url(self): return reverse('post_detail', kwargs={'pk':self.pk}) def get_number_of_likes(self): return self.likes.count() The profile model which is is created via signals whenever a new user registers: class Profile(models.Model): love_status_choices = [ ('-', '------'), ('married', 'Married'), ('single', 'Single'), ('inrel', 'In Releationship') ] user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') image = models.ImageField(default='default.png', upload_to='profile_pics') bio = models.TextField(blank=True, null=True) expertise = models.CharField(max_length=100, blank=True, null=True) age = models .IntegerField(blank=True, null=True) love_status = models.TextField(choices=love_status_choices, default="-", blank=True, … -
How do I get the path from MEDIA_ROOT to save it as a string in my Model?
So, I've successfully uploaded and saved my uploaded files in the "Media" directory in my project. Now what I'm trying to do is get the path of the saved file and save it as a string in my CharField made in my model. Executing data1.append('doc1', $('#file1').val()) gets the path where the file is originally saved like this: C:\fakepath\<filename>. However, what I need is the full path of the media directory where I've saved the file via the form, which would be: C:\Users\bilal\PycharmProjects\<proj name>\media\<filename>. So how would I go about getting this done? I'm sharing the complete project for clarity as well. Thank you. index.html <body> <div class="container-fluid"> <div class="col-md-4"> <form id="data"> <label for="docn"> <input type="text" id="docn" placeholder="Please enter document name"> </label> <label for="docc"> <input type="file" id="doc" name="docu"> </label> <button type="button" onclick="enterdata()">Submit</button> </form> </div> </div> <script> function enterdata() { var data1 = new FormData() data1.append('dcn', $('#docn').val()) data1.append('dc', $('#doc').val()) data1.append('docf', $('#doc')[0].files[0]) var token = '{{ csrf_token }}'; alert('csrf generated'); $.ajax({ type: 'POST', url: '/user', data: data1, processData: false, contentType: false, headers: {'X-CSRFToken': token}, success: function () { alert("Added"); } }) } </script> </body> views.py def insert(request): return render(request, 'index.html') def testing_data(request): if request.method == 'POST': dcn1 = request.POST['dcn'] upload_file = request.FILES['docf'] path … -
How to consolidate Django (different models) database and store at centralized place
I have created a Django-based webpage where different vendor company employees can logins and can change their Shift Timing. (Now we are controlling this job with Linux script but due to large user size ~8k doing it for all requests is a difficult task). To resolve this I have created a Django webpage( 6 separate models/DB) and used default SQLite DB. Requirement: The user is working on some application which needs to be controlled by updated shift timing on the portal. Question: How to consolidate OR store DB data in a centralized place? so that if tomorrow I have to reset the Timing for all the users in the portal to default consider General Shift. I have the below Idea to do this but not sure if this is the best way to complete this work. by using the REST API I will get the JSON data.OR manage.py dumpdata apple.CompanyName(Model) --indent 5 any help/Suggestion on this would be appreciated. -
Django not displaying images after adding product details
Django can be able to display the image if I comment out the product details page. I would like to know why it does that and how can I make it always display the images. Product model item_name = models.CharField(max_length=20) item_description = models.TextField( max_length=200, verbose_name="Item Description") item_price = models.FloatField(default=0.00) slug = models.SlugField(null=True, unique=True) item_details = models.TextField( max_length=1000, verbose_name="Item Details") item_quantity = models.IntegerField(default=0) item_availability = models.BooleanField(default=False) is_item_featured = models.BooleanField(default=False) is_item_recommended = models.BooleanField(default=False) # Todo: add Is On Carousel Filter item_brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE) item_categories = models.ForeignKey( Category, null=True, on_delete=models.CASCADE) item_image = models.ImageField(upload_to='images/product/', default="images/product/image-placeholder-500x500.jpg") Product Views class HomePageView(ListView): model = Product template_name = 'product/index.html' class ProductListView(ListView): model = Product template_name = 'product/product_list.html' def product_detail(request, slug): objec = get_object_or_404(Product, slug=slug) template_name = 'product/product_detail.html' return render(request, template_name, context={'object': objec}) Product Templates {% for product in object_list %} <div class="col-md-3 col-sm-6"> <div class="product-grid4"> <div class="product-image4"> <a href="product/{{ product.slug }}"> <!-- <img src="{{ product.item_brand.brand_image.url }}" alt="{{ product.item_brand.brand_name }}" width="30px"> --> <img class="pic-1" src="{{ product.item_image.url }}" alt="{{ product.item_name }}"> </a> <!-- <span class="product-new-label">Recommended</span> --> <!-- <span class="product-discount-label">-10%</span> --> </div> <div class="product-content"> <h3 class="title"><a href="#">{{ product.item_name }}</a></h3> <div class="price"> Kshs. {{product.item_price }} <!-- <span>$16.00</span> --> </div> <a class="add-to-cart" href="{% url 'add-to-cart' product.slug %}">ADD TO CART</a> </div> </div> … -
join two django models other than foreignkey
I have two models class Invoice(models.Model): invoice_id = models.IntegerField(blank=True, null=True) quotation_id = models.IntegerField(blank=True, null=True) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) invoice_number = models.IntegerField(blank=True, null=True) quotation_number = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) total_tax = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) document_type = models.CharField(max_length=50, default='', blank=True, null=True) and class Invoice_Description(models.Model): invoice_id = models.IntegerField(blank=True, null=True) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) quotation_id = models.IntegerField(blank=True, null=True) item_id = models.ForeignKey(tbl_item, on_delete=models.CASCADE) item_qty = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) item_unit_price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) Invoice contains information about the invoice document, its total price, date, etc while Invoice_Description keeps the records of items added on that particular invoice, item price, total quantity, discount on each item, etc. I want to display all the records in reports with respect to items like ITEM NAME CUSTOMER NAME INV. NO. QTY DOCUMENT TYPE UNIT PRICE SALE PRICE Item1 Client1 01 950.00 1000.00 I have all the columns available from Invoice_Description except for the INV. NO. and DOCUMENT TYPE which are in the Invoice model. I don't want to use a ForeignKey in this case because these models are already in use in many places, changing the database will require changes everywhere. my problem is just that I want … -
deploy React and Django with Nginx and Docker
I'm trying to deploy my React build and Django API using Nginx and Docker. I'm still really new to deployment and have never hosted a website that would go into production so am a little at a loss. Right now I have my Django API run on port 8000 and the React app runs on port 3000. I'm hoping to use Nginx to direct the IP address to the React app or Django API depending on the URL. Some examples: http://10.2.5.250/: would serve the React build at port 3000 http://10.2.5.250/upload: would serve the Django template file index.html at port 8000 http://10.2.5.250/median-rent?table=MedianRent: would serve the Django api at port 8000 This is my project structure: . ├── docker-compose.yml ├── front-end │ ├── Dockerfile │ ├── README.md │ ├── debug.log │ ├── node_modules │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── src │ └── yarn.lock ├── housing_dashboard_project │ └── housing_dashboard │ ├── Dockerfile │ ├── dashboard_app │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ ├── models.py │ │ ├── serializers.py │ │ ├── static │ │ ├── templates │ │ │ └── dashboard_app │ │ │ └── index.html │ │ ├── urls.py │ … -
Python, Django: New Line in Mail
Good day to all of you, the django-function for sending a mail (see bellow) works perfectly fine! from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) Unfortunately there are no informations about creating new lines inside the message text! Does anyone know the solution or has the same problem? What's the best way to include these? Thanks and a great weekend! -
Fetch data from size table by getting id from mapping table in django?
I am creating a printing ordering service website in django and i am stuck on order page. I have three tables named "product" ,"size" and "sizeProductMap" table. I want to get all those sizes from size table releted to a particular product here a single product can have different sizes. The sizeProductMap tables stores primary key of product table and size table as foreign key, now i want to get those sizes which has mapping with a particular product. -
Prefetch won't filter (django)
If I do following prefetch, django won't do my filter in the prefetch: devices = Device.objects.filter(site__id=site_pk,).prefetch_related( "site", Prefetch( "deckdevice__deck__airspace", queryset=DeckDevice.objects.filter(end__isnull=True), ) ) but doing this works: devices = Device.objects.filter(site__id=site_pk,).prefetch_related( "site", Prefetch( "deckdevice", queryset=DeckDevice.objects.filter(end__isnull=True), ), "deckdevice__deck__airspace", ) Is that normal? Because the second approach seems inefficient to me. -
Django Celery beat 5.x does not execute periodic_task
I'm currently trying to migrate from celery 4.x to 5.x but I'm unable to get celery beat to process a periodic_task. Celery beat simply does not touche the code here it seems. Processing tasks I call manually from a view is not a problem at all and working fine for the worker process. So I would at least expect that my settings are fine but I don't understand why the periodic_task are not processed. Can smb help? did I forget to call something?! Also see docs here: https://docs.celeryproject.org/en/stable/userguide/periodic-tasks.html settings.py # Celery Settings: BROKER_URL = 'redis://' + ':' + env.str('REDIS_PWD') + '@' + env.str('REDIS_HOST') + ":" + env.str('REDIS_PORT') BROKER_TRANSPORT = 'redis' CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_RESULT_EXPIRES = 3600 CELERY_REDIS_HOST = env.str('REDIS_HOST') REDIS_PWD = env.str('REDIS_PWD') CELERY_REDIS_PORT = env.str('REDIS_PORT') CELERY_REDIS_DB = env.str('REDIS_CACHE_DB') CELERY_CACHE_BACKEND = 'default' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'GMT' CELERYD_TASK_SOFT_TIME_LIMIT = 900 celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery import environ from django.conf import settings from MyApp import settings env = environ.Env() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyApp.settings") app = Celery(settings.SITE_NAME) app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(10.0, … -
How to delete old styles of django
I have multiple projects of django running on my PC for learning. When I open second project, it is still loading the styles of first project. How to clear this? -
how to submit form with ajax and than redirect on another page with data in django
i want to send my form data via ajax and than redirect page and get form on another page in django.But i am not able to access data please help. this is my search.py file : def search(request): if request.method == "GET": get_query = request.GET.get('country') get_nationality = request.GET.get('nationality') if get_query == "" or get_nationality == "": return redirect('/') get_country = Country.objects.filter(name=get_query) legal = Legal.objects.all() get_package = Package.objects.filter(country_name__name__contains=get_query) return render(request,'frontend/search_result.html',{ 'nationality':get_nationality, 'country':get_country, 'package':get_package, 'legal':legal, }) else: return redirect('/') and than i am showing this data on search_result.html : <form name="form" method="POST" id="form"> {% csrf_token %} <table class="table table-bordered table-responsive" id="flip-scroll"> <thead> <tr> <th scope="col">Package Option</th> <th scope="col">Processing Type</th> <th height="60" scope="col">Travel Date</th> <th scope="col">Price</th> </tr> </thead> <tbody> {% for j in package %} <tr class="valid-container" data-id="{{ j.id }}"> <td style="cursor:pointer;" width="200"><input type="checkbox" name="c1" class="checkbox">&nbsp; <output class="type" style="font-size:14.5px !important;">{{ j.type }}</output></td> <td height="52" width="158"> <select class="custom-select processing_type" name="processing_type" required> <option value="{{ j.price }}" selected>Normal</option> <option value="{{ j.express_price }}">Express</option> </select> </td> <td width="190" height="60"> <div class="input-group date" data-date-format="dd.mm.yyyy"> <div class="input-group mb-2"> <input type="text" class="form-control travel_date" name="travel_date" value="dd.mm.yyyy" placeholder="dd.mm.yyyy"> <div class="input-group-text"><i class="ti-calendar"></i></div> <div class="input-group-addon"> </div> <div class="input-group-prepend"> </div> </div> </div> </td> <td width="166">{{ j.currency_type }}&nbsp;&nbsp; <output name="result" class="package_price">{{ j.price }}</output>.00</td> </tr> {% endfor %} … -
Can Django be used to build REST APIs without DRF?
I am developing an application whose front-end will be in React. I am familiar with the Django Templating system, returning html pages on requests. I am not sure how to build REST APIs in Django. Can anyone share code examples. I want to use pure Django not Django REST Framework -
django admin: how to remove apps links
due to some reasons, I want to remove links on apps inside django admin panel. i have written some code inside base_site.html to customize the logo and title but I need to know how to remove the links of the apps. here is the code {% extends 'admin/base.html' %} {% load static %} {% block branding %} <h1 id="head"> <img src="{% static 'images/logo.png' %}" alt="Saleem's website." class="brand_img" width=170> Admin Panel </h1> {% endblock %} {% block extrastyle%} <link rel="stylesheet" href="{% static 'admin.css' %}"> {% endblock %} attached is the screenshot to know better where I wan to remove the links -
On automated sign up
I am learning Django/Python to make the multi-vendor e-commerce website I always wanted to make. I have this question in my mind for a long time and I couldn't see the tutorial anywhere. I didn't try anything because I am a complete beginner. My question is; I am accepting payments through Transferwise, and when the payment is done, how to automate creating profile? To create an AI to accept the payment or? -
How to delete an account in django allauth using a generic.DeletView
I'm currently developing a web application using python3, Django, and AllAuth. This application has a signup system using a custom user model and a user uses their email to log in. I want to make a system that user can delete their accounts using generic.DeleteView I'm trying to make it referring to the basic way to delete some items of Django. But in the case of deleting an account, It doesn't work... How could I solve this problem? Here are the codes: app/views.py class UserDeleteView(LoginRequiredMixin, generic.DeleteView): model = CustomUser template_name = 'app/user_delete_confirm.html' success_url = reverse_lazy('app:welcome') def delete(self, request, *args, **kwargs): return super().delete(request, *args, **kwargs) app/urls.py ... path('user_delete/<int:pk>/', views.UserDeleteView.as_view(), name='user_delete'), ... accounts/models.py class CustomUser(AbstractUser): class Meta: verbose_name_plural = 'CustomUser' app/user_delete.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>user_delete</title> </head> <body> <a href="{% url 'app:user_delete_confirm' object.pk %}"> <button type="button" >delete </button> </a> </body> </html> app/user_delete_confirm.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>user_delete_confirm</title> </head> <body> <form action="" method="post"> {% csrf_token %} <h2>Are you sure to delete your account? </h2> <button type="submit">DELETE</button> </form> </body> </html> ・python:3.7.5 ・Django:3.1.2 ・django-allauth:0.43.0 -
Filter and get values using OR and AND conditions in Django
I am querying a set of objects with a condition like this: for filter_for_dates_report in filters_for_dates_report: filter_dict.update({filter_for_dates_report: { filter_for_dates_report + "__range" : [start_date, end_date] }}) list_of_Q = [Q(**{key: val}) for key, val in filter_dict.items()] if list_of_Q: model_details = Model.objects.filter(reduce(operator.or_, list_of_Q)) .values(*values_list_for_dates_report) Now I want to exclude the objects which have null values for filter_for_dates_report attributes. A direct query would be Model.objects.filter( Q(filter_for_dates_report__range=[start_date, end_date] & filter_for_dates_report__isnull=False)) .values(*values_list_for_dates_report) But how can I do this for multiple values wherein I want only the values within that range and also which are not null for multiple filter_for_dates_report attributes. Something like: Model.objects.filter( Q(filter_for_dates_report__range=[start_date, end_date] & filter_for_dates_report__isnull=False) | Q(filter_for_dates_report__range=[start_date, end_date] & filter_for_dates_report__isnull=False) | Q(filter_for_dates_report__range=[start_date, end_date] & filter_for_dates_report__isnull=False) .values(*values_list_for_dates_report) -
Show absolute URL for uploaded file
I implemented a file upload endpoint with DRF the issue is the documents do not show the absolute url of the file as shown below on the screenshot. I expect the absolute url start with http://localhost .... Here is my django settings STATIC_URL = '/static/' # The folder hosting the files STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] ## Serving the STATIC FILES # As declared in NginX conf, it must match /src/static/ STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'static') MEDIA_URL = '/media/' # do the same for media files, it must match /opt/services/djangoapp/media/ MEDIA_ROOT = os.path.join(BASE_DIR, 'media') models.py class Document(models.Model): """This represents document class model.""" file = models.FileField(upload_to='documents/inspections/%Y/%m/%d') timestamp = models.DateTimeField(auto_now_add=True) @property def name(self): name = self.file.name[33:] return name -
Django AWS S3 - 400 "Bad Request" - Can't access image from bucket
I recently decided to merge the images used in my application from a static folder in my root directory to an AWS S3 bucket. However, I am getting this error when I open my app in a browser: localhost/:65 GET https://django-plantin-bugtracker-files.s3.amazonaws.com/profile_pics/aragorn_SztKYs6.jpg?AWSAccessKeyId=AKIA3KFS7YZNOMSRYG3O&Signature=fYWSQFdzTvtOF9OXAfw9yqfGyQc%3D&E I unblocked all public access on my S3 bucket and added these lines of codes to the following files: In my app's settings.py I added: AWS_STORAGE_BUCKET_NAME=config('AWS_S3_BUCKET_NAME') AWS_ACCESS_KEY_ID = config('AWS_S3_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_S3_SECRET_ACCESS_KEY') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' In my S3 bucket's Bucket Policy: { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::django-plantin-bugtracker-files/*" } ] } In my S3 bucket's CORS: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "PUT", "POST", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Does anyone know why my images won't appear? The webpage loads fine and there is no error from Django. The images look like this: -
Why is my Django login not getting authenticated?
I do know that this is a repeated question. I did refer those answers but still I couldn't get my issue fixed. Kindly do help. Registration works just fine. The registered users gets added to the DB fine. Logout works fine. The issue is with login. Whenever I try logging in , I keep getting the response "Invalid login details". views.py from django.shortcuts import render, redirect from . forms import * from django.http import HttpResponse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required # USER LOGIN def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user =authenticate( username=username, password=password) if user is not None: if user.is_active: login(request,user) return redirect('home') else: return HttpResponse("Account not active") else: return HttpResponse("Invalid login details") #whenever I try to login, I always gets this response. else: return render(request, 'basic_app/login.html') #USER LOGOUT @login_required def user_logout(request): logout(request) return redirect('login') urls.py(application). from django.urls import path from . import views urlpatterns = [ path('',views.index, name='home'), path('register/',views.register, name='register'), path('login/',views.user_login, name='login'), path('logout/',views.user_logout, name='logout'), ] login.html {% extends 'basic_app/base.html' %} {% block body_block %} <div class='jumbotron'> <h2>User Login</h2> <form action="{% url 'login' %}" method="post"> {% csrf_token %} <label for="username">Username:</label> <input id="username" type="text" placeholder="Enter Username"> <label for="password">Password</label> <input id="password" … -
What is the most efficient way to compare a string to Enums?
I have the following Enum class: class LabelEnum(str, Enum): ENUM_ONE = "Enum One" ENUM_TWO = "Enum Two" ENUM_THREE = "Enum Three" FOUR = "FOUR" FIVE = "FIVE" SIX = "SIX" I want to compare a string with all of the members of this enum and see if the string exists in the enum class or not. I can do this by following snippet: if string in LabelEnum.__members__: pass But I want to compare the lower case of the string (string.lower()) with the lower case of the enum members. I can't do this in the above way I think. Another way is to loop through the members but that will slow the execution and I don't want that. Is there any way I can compare the lowercase of these in a single line and more efficiently than looping? -
Is it possible to develop rasa chatbot inside django as an app and managing through manage.py
I’m new to RASA platform. I wanted to develop RASA chatbot as an app inside django instead of creating rasa init and running separate servers like action and core nlu servers. Is it possible and if yes please guide me through.