Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to reduce size and increase cohesion of views
As my project is becoming bigger and bigger, I am starting to get very large CBVs because they are required to handle a lot of actions especially live responses through AJAX (More single page application style). For example I have class ScheduledBooking. It does everything from showing timelines of bookings, booking appointments and viewing/editing other appointments in one page. I utilise a variety of model managers for complex filtering/aggregation but not sure if it's Pythonic to extend it's role of these managers to handling booking actions such as allocating bookings, checking availability of bookings, broadcasting bookings (Even if they use other models)? To reduce size and cohesion of the view although the model manager then will just take on the workload affecting it's own level of cohesion. Or is there a better way/alternative for this? Another problem is the Live Responses from ajax. I use a large amount due to a single page application style although the action handling clogs up a lot of the view. I was wondering if there is an alternative place or way this can be handled? class ScheduledBooking(TemplateView, BetterFormsChoiceValidationMixin, SessionHandlerMixin, BookingMixin, AJAXFormSerialiserMixin): template_name = 'emissions_dashboard/booking_scheduled.html' def get_context_data(self): [... 20 lines..] return args def get(self, request, … -
How to add pagination to search view in django
could you please support adding pagination to the below search function based view, here is my code def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] search_vector = SearchVector('title', weight='A') + \ SearchVector('body', weight='B') search_query = SearchQuery(query) results = Post.published.annotate( search=search_vector, rank=SearchRank(search_vector, search_query) ).filter(rank__gte=0.1).order_by('-rank') return render(request, 'blog/post/search.html', {'form': form, 'query': query, 'results': results}) -
Custom login using Django's user template
I'm trying to make my custom login form using Django's user template. What i'm trying to do is the authentication of a user using username and password. Register works, every user is registered correctly, but when i'm trying to login using the correct fields, my: user = authenticate(request, username=username, password=password) returns None as value. Here is my def login_view in views.py (i'm using logger to know what is going on) def login_view(request): import logging logging.basicConfig(filename='mylog.log', level=logging.DEBUG) logging.debug('inizio') title = 'LOGIN' form = UserLoginForm() if request.user.is_authenticated: return redirect('board.html') if request.method == 'POST': form = UserLoginForm(request=request, data=request.POST) username= request.POST.get('username') password= request.POST.get('password') print(form.errors) if form.is_valid(): logging.debug('form is valid') logging.debug('called form.save(), result=%s', UserLoginForm) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) user = authenticate(request, username=username, password=password) logging.debug('user, result=%s', user) #### if user is not None: login(request, user) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) messages.info(request, "You are now logged in as {username}") return redirect('board.html') else: messages.error(request, "Invalid username or password.") logging.debug('primo else') return redirect('/') #### else: print(form.errors) logging.debug('errore form: , result=%s', form.errors) messages.error(request, "Invalid username or password.") logging.debug('secondo') username = request.POST.get('username') password = request.POST.get('password') messages.error(request, "Invalid username or password.") logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) return redirect('/') return render(request=request, template_name="login.html", context={"form": form , "title":title}) And that's my … -
Build Succeeds Locally | Succeeds & Fails at CodeBuild AWS | Build Logs Shows App Up and Running | Status In Progress Forever
I have a django app that runs fine locally, when I attempt to send it to CodeBuild, the Build logs shows my app running in the console however the build never completes and the status is "in progress" This is taking from the build logs showing that my build has succeeded: But the Status shows in "in progress" however it never installs: -
How to get anything else that a string with ChoiceField in django forms?
I created a form with some ChoiceField inside. My probleme is that I always get a string even if the value of my ChoiceField is an integer or an array. In my view I try to handle the data of the form and get something like that : formTemplate = QcmForm(request.POST) if(formTemplate.is_valid()): rep1 = formTemplate.cleaned_data['Q1'] print("REPONSE", rep1) print("::", type(rep1)) And this is what I get REPONSE : [('L', 1)] :: <class 'str'> So Here is how I defined my form and a second try I did with TypeChoiceField which wasn't sucessful : Q1_TITLE = "intitule of question" Q2_CHOICES = ( ([("L", 1)], "some item"), ([("W", 0.5)], "other item") ) class QcmForm(forms.Form): Q1 = forms.ChoiceField(choices = Q1_CHOICES, label=Q1_TITLE, initial='', widget=forms.Select(), required=True) So if I choose "some item" I get in my print a string instead of a list or a tuple. Next Try : I changeed with TypeChoiceField class QcmForm(forms.Form): Q1 = forms.TypedChoiceField(coerce=list, choices = Q1_CHOICES, label=Q1_TITLE, initial='', widget=forms.Select(), required=True) And here the result is worst, it consider my reponse as a list of character instead of a list of tuple. REPONSE : ['[', '(', "'", 'L', "'", ',', ' ', '1', ')', ']'] :: <class 'list'> Thank you for reading … -
Django encrypt FileField before saving it
I'm trying to save pdfs in the disk with django which is easy. However I want to encrypt them before saving them. As far as i know i should rewrite the save of the model to encrypt the file content before making the super().save() The problem is that i'm not managing to encryopt the content, i've tried with: self.file.write(f.encrypt(self.file.read())) However it does not modify anything. I'm not seeing with the debuger where the content of the file is to modify it or how should i do it. Thanks! -
Django : how to fix empty slug?
I have a urls : urlpatterns = [ url(r"admin/" , admin.site.urls), url(r"users/" , include(("users.urls", "users") , namespace='users') ), path('bristol/' , include(('bristol.urls', "bristol") , namespace='bristol') ), url(r"" , include('django.contrib.auth.urls')), ] But I can't connect to my server if I don't put any end slug to my url : What should I change in my url patterns to redirect localhost:8000 directly to the login view ? I tried : urlpatterns += [ url(r"/" , reverse("login"))] But It didn't help :-/ -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup in DJANGO even though urls is mapped correctly
Below is the urls.py file of sub-app accounts from django.urls import path from . import views urlpatterns = [ path("signup",views.signup,name='signup') ] This views.py of accounts def signup(request): if request.method == 'POST': firstname = request.POST['first_name'] lastname = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] if password1==password2: user = User.objects.create_user(firstname =first_name ,lastname =last_name ,username =username , email=email, password=password1) user.save(); print("USER CREATED SUCCESSFULLY") return redirect('login.html') else: return redirect('signup.html') I have even mapped the url in main url.py also, but still it is showing error. below is the signup.html The signup.html file <form action="signup" method="POST"> {% csrf_token %} <input type="text" name="first_name" placeholder="FIRST NAME"><br> <input type="text" name="last_name" placeholder="LAST NAME"><br> <input type="text" name="username" placeholder="USERNAME"><br> <input type="email" name="email" placeholder="EMAILID"><br> <input type="password" name="password1" placeholder="PASSWORD"><br> <input type="password" name="password2" placeholder="CONFIRM PASSWORD"><br> <input type="submit"> can anyone please help me out with this problem, i am not getting what went wrong. It is displaying page not found error. -
Is there way to call a Javascript function when a Django Admin Popup (Add, Update, Delete) completes?
Image, I have this situation, where I have bind the change event on Person field. We rely on some JavaScript to be run each time a select value changes. It is currently listening to the change event of said element, which works fine when the user clicks a value directly in the menu proposed by the select. Sadly, when this select is populated through the Admin Popup functionality, it seems the change event is not fired for the select, as our callback is not executed, even though the element's value is actually changed. Is there another event we can listen to to get the same behaviour than when the user clicks a value directly from the list ? -
Problem with Django not finding a module 'learning_logs'
I've been trying to fix this Django issue. I've just started this project and I'm fairly new to this language so I don't know where exactly is the issue. Error: Traceback (most recent call last): File "C:\Users\user\Desktop\Projects Python\Django\manage.py", line 22, in <module> main() File "C:\Users\user\Desktop\Projects Python\Django\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'learning_logs' models.py: from django.db import models # Create your models here. class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learning_logs', ] Any help I would really appreciate it. -
Display Django Templates after sucessfuly posting data
I got a problem with my Django templates: forms.py: class SupportForm(forms.Form): name = forms.CharField() message = forms.CharField() models.py: class Message(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) message = models.CharField(max_length=100) def __str__(self): return self.user.username views.py: class my_view(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): try: messages = Message.objects.filter(user=request.user) context = { 'object': messages, } return render(self.request, 'my.html', context) except: return render(request, "my.html",{}) def post(self, request, *args, **kwargs): form = SupportForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] message = form.cleaned_data['message'] message_model = Message( user=request.user, name = name, message = message, ) message_model.save() return redirect('/my/') my.html: object:{{ objects }}<br> name:{{objects.name.1}}<br> message:{{objects.message.1}}<br> {% for item in objects_list %} {{ item.name }} {% endfor %} I want to post name and message in html and then show it under input. POST works fine. Then i want to display my name and message. The problem is with viewing my objects in html: i can't see anything. What am i doing wrong? -
Sending Serializer data by Request library in Django return (too many values to unpack (expected 2))
I am trying to send a data by Webhook, using Request Library in Django. whatever=Whatever.objects.filter(visibility=True) datas = WhateverSerializer(whatever,many=True).data webhooks = Webhooks.objects.filter(user=request.user,types="webhooks") headers = {'Content-Type': 'application/json;charset=UTF-8'} for wh in webhooks: r = requests.get(wh.data, headers=headers, data=datas) But I have a error 500: too many values to unpack (expected 2) What is the correct way to send it by webhook? -
how to hide html tags in head meta description when i use WYSIWYG - django
i want add meta description in tag for each post from my model so i add this line in head tag in html page <head> <!-- Facebook Meta Tags --> <meta property="og:description" content="{{android_posts.app_contect}}" /> </head> so i tried do that but the problem is when i see my page source it show html tags , also i tried add |safe in meta but nothing changed , any ideas please i'm using django -
Getting the number of comments from a specific post in django
I have a little problem with a query. I work on a blog website with django. For posts I have the first page where i display all the posts as a list, with their details (title, date posted etc.) and I want to display the number of comments for each post along with title, date posted and tags. I'm not sure how to make that, I need to implement something on the model classes or in view function that renders the page ? Here are the model classes. class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=500) content = models.TextField() tags = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment_text = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Comment ' + str(self.id) and the view function def blog(request): context = { 'posts': Post.objects.all(), 'title': 'Blog', 'banner_page_title': 'Blog', 'page_location': 'Home / Blog' } return render(request, 'blog/blog.html', context) -
Django REST API - SerializerMethodField() causes too many queries
I am a bit lost here. I have created a nested relationship that goes as follows: Text -> multiple Sentences-> multiple Words models.py: class Text(models.Model): title = models.CharField(max_length=250) class Sentence(models.Model): text = models.ForeignKey(Text, related_name='sentences', on_delete=models.CASCADE, blank=True, null=True) order = models.IntegerField() class Meta: unique_together = ['text', 'order'] ordering = ['order'] class Word(models.Model): sentence = models.ForeignKey(Sentence, related_name='words', on_delete=models.CASCADE, blank=True, null=True) order = models.IntegerField() word = models.CharField(max_length=50) vocabulary = models.ForeignKey(Vocabulary, on_delete=models.SET_NULL, blank=True, null=True) class Meta: unique_together = ['sentence', 'order'] ordering = ['order'] class Vocabulary(models.Model): vocabulary = models.CharField(max_length=50) class KnownWords(models.Model): vocabulary = models.ForeignKey(Vocabulary, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) The idea is that a text is split into individual words. Each word is associated with a vocabulary and users can know the vocabulary. serializer.py: class WordSerializer(serializers.ModelSerializer): is_known = serializers.SerializerMethodField() class Meta: model = Word fields = ['id', 'order', 'word', 'vocabulary', 'is_known '] def get_is_known(self, obj): if KnownWords.objects.filter(vocabulary=obj.vocabulary).exists(): obj.is_known = True else: obj.is_known = False return obj.is_known class SentenceSerializer(serializers.ModelSerializer): words = WordSerializer(many=True) class Meta: model = Sentence fields = ['id', 'order', 'words'] class TextSerializer(serializers.ModelSerializer): sentences = SentenceSerializer(many=True) vocabulary = serializers.SerializerMethodField() class Meta: model = Text fields = ['id', 'title', 'sentences'] views.py: class TextDetail(generics.RetrieveAPIView): queryset = Text.objects.prefetch_related('sentences', 'sentences__words') serializer_class = TextSerializer The reason why ìs_known is a … -
Unable to create process using
I'm trying to run my django code but I'm presented with this error: Unable to create process using 'C:\Users\My_username\AppData\Local\Programs\Python\Python39\python.exe manage.py runserver', How do I deal with this? -
Is it possible to call a function of __init__.py from views.py in django?
init.py : def abc(): some code views.py: from . import __init__ __init__.abc() This gives error AttributeError: 'method-wrapper' object has no attribute 'abc' Is it possible to call the abc() function from views.py ? -
django password reset does not work on server but works on local machine
I am using gmail password manager to generate password. When I try to send email for password reset on sever I get 500 Error. This same format works when I try to send password reset email locally. These are my settings in 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 = config['EMAIL_USER'] EMAIL_HOST_PASSWORD = config['EMAIL_PASS'] DEFAULT_FROM_EMAIL = config['EMAIL_USER'] I have even tried to hard code email and password, but that still does not work. I am using apache2 and here is my configurations: src => all the project files, recipe_app => project settings src |__recipe_app |__settings.py |__wsgi.py Alias /static /home/<user>/src/static <Directory /home/<user>/src/static> Require all granted </Directory> Alias /media /home/<user>/src/media <Directory /home/<user>/src/media> Require all granted </Directory> <Directory /home/<user>/src/recipe_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/<user>/src/recipe_app/wsgi.py WSGIDaemonProcess recipe_app python-path=/home/<user>/src python-home=/home/<user>/src/venv WSGIProcessGroup recipe_app -
Getting an Not Found: /blogs/like when adding Ajax to like button
I am trying to make the like button in the post_detail.html page clicked without refreshing the page so, I included the like section in a separate HTML called like-section.html. The problem is now I am getting a Not Found: /blogs/like when I click on the like button and it doesn't change anything when I click it except in the terminal I see this error. Here is the model.py class Post(models.Model): ------------------------------ liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') Here is the views.py def like_post(request): user = request.user post_obj = None if request.method == 'POST': post_id = request.POST.get('post_id') try: post_obj = Post.objects.get(id=post_id) except Post.DoesNotExist: return JsonResponse({'detail': 'Not found'}, status=404) else: if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() context = { 'post_id': post_id, } if request.is_ajax: html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) elif request.method == 'GET': post_id = request.GET.get('post_id') try: post_obj = Post.objects.get(id=post_id) except Post.DoesNotExist: return JsonResponse({'detail': 'Not found'}, status=404) Here is the like-section.html <form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> {% if user not in post.liked.all %} <a id="like" class="bwhite sm-button" style="color: … -
Having trouble setting the DIRS url in Django TEMPLATES
have created a folder templates in my project's main folder and am trying to set a url for django to look for templates in and I am getting the following error: 'DIRS': [BASE_DIR / 'templates'], TypeError: unsupported operand type(s) for /: 'str' and 'str' In my settings.py file I have inserted the following code: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] The version of django is 3.1.3 -
SMTPRefused error while trying to send forgot-password emails using Sendinblue SMTP
Im trying to build a blog website using django and configure my email host using sendinblue, but I'm getting an error saying (530, b'Error: authentication Required', 'webmaster@localhost') Settings.py #Email config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-relay.sendinblue.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '########@gmail.com' EMAIL_HOST_PASS = os.environ.get('sendinblue_smtp_pass') Traceback Environment: Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 3.1.2 Python Version: 3.8.6 Installed Applications: ['blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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 "C:\myenv\django\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\myenv\django\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\myenv\django\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\myenv\django\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\myenv\django\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\myenv\django\lib\site-packages\django\contrib\auth\views.py", line 222, in dispatch return super().dispatch(*args, **kwargs) File "C:\myenv\django\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\myenv\django\lib\site-packages\django\views\generic\edit.py", line 142, in post return self.form_valid(form) File "C:\myenv\django\lib\site-packages\django\contrib\auth\views.py", line 235, in form_valid form.save(**opts) File "C:\myenv\django\lib\site-packages\django\contrib\auth\forms.py", line 323, in save self.send_mail( File "C:\myenv\django\lib\site-packages\django\contrib\auth\forms.py", line 273, in send_mail email_message.send() File "C:\myenv\django\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\myenv\django\lib\site-packages\django\core\mail\backends\smtp.py", line 109, in send_messages sent … -
first item adding properly but 2nd item is not adding
I am making a commerce website using django. I used session to fetch all the request in my project, but I am facing an issue. The problem is when I add a product to my cart it added successfully but whenever I try to another in the same time it shows 0 product in cart. I can't even add the amount but when I remove the first product the quantity automatically added to the second product. Really confusing, and for that reason I am providing screenshots. Screenshot Here is my Views.py: class Index(View): def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} products = None cats = Category.get_categories() brands = Brand.get_brands() categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: products = Product.get_products_by_category(categoryID) else: products = Product.get_all_products() if brandID: proucts = Product.get_brands_by_products(brandID) else: products = Product.get_all_products() args = { 'products':products, 'cats': cats, 'brands': brands } return render(request, 'Home/index.html', args) def post(self, request): product = request.POST.get('product') print(product) cart = request.session.get('cart') remove = request.POST.get('remove') if cart: quantity = cart.get(product) if quantity: if remove: if quantity <= 1: cart.pop(product) else: cart[product] = quantity-1 else: cart[product] = quantity+1 else: cart[product] = 1 else: cart = {} cart[product] = 1 request.session['cart'] = cart … -
DJANGO - How to show "Nothing Found for your seach" If no data found
I would like to know if there is a way to show a div, or at least "Nothing found" in django when there is no match for the user search. views.py class TaskSearchView(LoginRequiredMixin, ListView): template_name = 'task_app/task_search.html' model = Task def get_queryset(self): query = self.request.GET.get('q') usr = self.request.user if query: object_list = self.model.objects.filter(Q(title__icontains=query) & Q(is_public = True) | Q(title__icontains=query) & Q(author = usr) | Q(title__icontains=query) & Q(responsable = usr)) else: object_list = self.model.objects.none() return object_list task_search.html <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold text-primary">Seach Results for: {{ request.GET.q }}</h6> </div> .... {% for query in object_list %} </thead> <tbody> <tr> {% if query.importance == "H" %} <th scope="row" data-toggle="tooltip" data-placement="top" title="HIGH"><i style="color: red" class="fas fa-bookmark"></i></th> {% endif %} {% if query.importance == "M" %} <th scope="row" data-toggle="tooltip" data-placement="top" title="Medium"><i style="color: orange" class="fas fa-bookmark"></i></th> {% endif %} ..... </tr> {% endfor %} If the query is empty or there is no result I get this: but I would like to show a new form, or a message "nothing found..", is that possible? I tried with: {% if object_list != None %} show results {%else%} show not found, form, div... {% endif %} But it didn't work Any advice/answer … -
Where to Perform Additional Operations When Using Django Rest Framework
I have a CustomUser model and am using Django Rest Framework. I have several needs before/after saving a user object. For example: Adding the user's email, first/last name to a mailchimp list using mail chimp's API. Hashing a user's password before saving. I successfully do this in the UserSerializer class thus: class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = '__all__' def create(self, validated_data): groups = validated_data.pop('groups', None) password = validated_data.pop('password', None) user_permissions = validated_data.pop('user_permissions') u = CustomUser.objects.create( password=make_password(password), **validated_data) u.groups.set(groups) u.user_permissions.set(user_permissions) return u However, let's say I want to also create a user in the admin tool and not repeat this logic? Doesn't it make more sense to add this logic by overriding the CustomUser's save method, or is that problematic? What's the best solution for this use-case? -
What permissions should be given to socket files or its parent folder?
What permission should be given to a .sock file and the folder containing it ? Is permission 777 mandatory for it to work ? If not, is it still risk free to do so ? If not, what should be the ideal permission [standard practice / best practice] ? BONUS --> Any other good practices associated with socket files [e.g never keep socket file in same folder as app] POSSIBLY REQUIRED INFO: Current Permissions: drwxrwxrwx 2 root root 4096 Nov 15 14:44 folder-containing-socket-files As you can see current permissions given are drwxrwxrwx or 777. Does having permissions set to 777 have any security implications here is my primary concern. Assume Django application - gunicorn - nginx Nginx is serving to a gunicorn socket in my case. My system has the following - USERS --> root , dev1 , dev2 GROUPS --> root , www-root , developers It has folder structure as follows: all_projects ├── all_apps ├── folder-containing-socket-files ├── django_proj_1 └── django_proj_2 {django_proj_1 , django_proj_2 are folders which contain the manage.py file}