Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Downloading the 'attachment' from the 'content-disposition'
Here are the items from the FileResponse object that was returned when I called the API to download the file. sample = c.get(<URL>) print(sample.items()) ('Content-Type', 'application/json') ('Content-Length', '2') ('Content-Disposition', 'attachment; filename="Example File.json"') ('X-Frame-Options', 'DENY') ('Vary', 'Cookie') ('X-Content-Type-Options', 'nosniff') ('Referrer-Policy', 'same-origin') ('Cross-Origin-Opener-Policy', 'same-origin') -
How can i limit results of a For Tag link array?
I have a DB query that pulls users order details and lists them as "Transactions" On our main user content dashboard i want to limit these query to only show 5 results. `{% for order in user.userordertokens %} <tr> <td>Order Description</td> <td>{{ order.createdat|date('m/d/Y')}}</td> <td>{{ order.tokenamount|number_format(0, '.', ',')}} GLN</td> <td><span class="fw-bold text-success">{{ order.status}}</span></td> <td> <a href="{{path('dashboard_purchase_details', { transactionId: order.idencoded })}}" class='btn btn-primary'>View Details</a> </td> </tr> {% endfor %}` This is the code im using to pull the data. Can i use a limit [5] type code to limit how many results are shown? `[:5] 0, 5` I have tried the following but both are not working, What am i doing wrong? -
Media images not displaying from AWS S3 in django app
It seems that I've configured all right, and in the dev tools or terminal no errors. Even the file crash icon disappeared. settings.py (i removed the name and other data that shouldn't be public STATIC_URL = "staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" # amazon s3 MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % os.environ.get('') AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_DEFAULT_ACL = 'public-read' AWS_S3_REGION_NAME = '' AWS_S3_VERIFY = True # config/settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images/') MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) models.py index.html {% for auction in allAuctions %} <div class="col"> <div class="card shadow-sm"> <img src="{{ auction.image.url }}" class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false" style="object-fit: cover;"> {% endfor %} my s3 policy also the s3 bucket and how it looks like -
Django - cannot pass error message to context
I have a view responsible for inviting users to note: def invite_user(request, pk): note = get_object_or_404(Note, pk=pk) form = InviteUser() err = False if request.method == 'POST': form = InviteUser(request.POST) if form.is_valid(): username = form.cleaned_data['username'] if User.objects.filter(username=username).exists() and username != request.user.username and not Note.objects.filter(members__contains = [username], id=note.id): notification = Notification(message=f"Do you want to join to {User.objects.get(username=note.user)}'s note: {note.title}?", user=User.objects.get(username=username), note_id=note.id) notification.save() else: print('Error') err = True return redirect('show', pk=note.id) if err: context = { 'form': form, 'error': 'You cannot invite this user!' } return render(request, context) else: context = { 'form': form, } return render(request, context) Template: {% if error %} <h1>{{ error }}</h1> {% endif %} When I pass correct user invitation is sent, but when there is error I see print in console, but there is not h1 with error in templete. What I am doing wrong? -
react-redux Place Order api/orders/add/ 500(internal server error)
I am building an ecommerce project with django and react. this is my django order views: from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from base.models import Product, Order, OrderItem, ShippingAddress from base.serializers import ProductSerializer, OrderSerializer from rest_framework import status @api_view(['POST']) @permission_classes([IsAuthenticated]) def addOrderItems(request): user = request.user data = request.data orderItems = data['orderItems'] if orderItems and len(orderItems) == 0: return Response({'detail': 'No Order Items'}, status=status.HTTP_400_BAD_REQUEST) else: order = Order.objects.create( user=user, paymentMethod=data['paymentMethod'], shippingPrice=data['shippingPrice'], taxPrice=data['taxPrice'], totalPrice=data['totalPrice'] ) shipping = ShippingAddress.objects.create( order=order, address=data['shippingAddress']['address'], city=data['shippingAddress']['city'], postalCode=data['shippingAddress']['postalCode'], country=data['shippingAddress']['country'], ) for i in orderItems: product = Product.objects.get(_id=i['product']) item = OrderItem.objects.create( product=product, order=order, name=product.name, qty=i['qty'], price=i['price'], image=product.image.url, ) product.countInStock -= item.qty product.save() serializer = OrderSerializer(order, many=False) return Response(serializer.data) order_urls.py: from django.urls import path from base.views import order_views as views urlpatterns = [ path('add/', views.addOrderItems, name='orders-add'), ] now, backend. orderReducers.js: import { ORDER_CREATE_REQUEST, ORDER_CREATE_SUCCESS, ORDER_CREATE_FAIL } from "../constants/orderConstants" export const orderCreateReducer = (state={}, action) =>{ switch(action.type){ case ORDER_CREATE_REQUEST: return{ loading: true, } case ORDER_CREATE_SUCCESS: return{ loading: false, success: true, order: action.payload, } case ORDER_CREATE_FAIL: return{ loading: false, error: action.payload, } default: return{ state } } } orderActions.js: import axios from 'axios' import { ORDER_CREATE_REQUEST, ORDER_CREATE_SUCCESS, ORDER_CREATE_FAIL } from … -
Django - can login only as admin
i've lost possibility to login to page as non-admin user. For Admin credentials everything works. Can't figure out what happend. I was searching for the issue commenting out admin custom things, adding full permissions from admin site and nothing. Views: def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/home') else: messages.success(request, ("Invalid credentials")) return redirect('login') else: return render(request, 'authenticate/login.html', {}) HTML: <form action="" method=POST class="login"> {% csrf_token %} <input type="text" name="username" placeholder="login"> <br> <input type="text" name="password" placeholder="password"> <br> <button type="submit">Login</button> </form> Admin: class Supplier_Admin(admin.ModelAdmin): fields = ('id','company_name','currency', 'legal_form', 'accounting_standards', 'owner_structure', 'industry_sector', 'date_of_establishment', 'start_up', 'email_address', 'web') admin.site.register(Supplier, Supplier_Admin) class CustomUserAdmin(admin.ModelAdmin): list_display = ('username', 'email', 'user_id') def user_id(self, obj): return obj.id user_id.short_description = 'ID' admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) Model: class Supplier(models.Model): id = models.IntegerField(primary_key=True) company_name = models.OneToOneField(User, max_length=120, on_delete=models.CASCADE) currency = models.CharField('Currency', max_length=4, blank=True) legal_form = models.CharField('Legal form', max_length=100, choices=legal_form_options, default='Sole proprietorship', blank=True) accounting_standards = models.CharField('Accounting standards', max_length=100, blank=True) owner_structure = models.CharField('Owner structure', max_length=100, blank=True) industry_sector = models.CharField('Industry sector', max_length=100, choices=industry_sector_options, default='Advertising', blank=True) date_of_establishment = models.DateField('Date of establishment', default=date.today, blank=True) start_up = models.CharField('Start-up', choices=start_up_options, default='No', max_length=4, blank=True) email_address = models.EmailField('Email address', blank=True) web = models.URLField('Website address', … -
Which must be html templates for that Django view?
I don't know how to create valid html templates for that Django views with forms, I don't understand how it works, please explain me it. view.py: from django.shortcuts import redirect, get_object_or_404 from .models import Test, Question, Answer from .forms import QuestionForm, AnswerForm, QuestionSetForm, QuestionFormset from django.views.generic import CreateView, UpdateView from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy, reverse from django.forms.formsets import formset_factory class QuestionsAddView(LoginRequiredMixin, CreateView): question_form_class = QuestionForm answer_form_class = AnswerForm template_name = 'tests/questions_add.html' def get_object(self): id_test = self.kwargs['id_test'] test = Test.objects.filter(pk = self.kwargs['id_test']).first() question = Question.objects.all().last().id+1 return question def count(self): return Test.objects.filter(pk = self.kwargs['id_test']).first().questions_count def get_formset(self, form): return formset_factory(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['id_test'] = self.kwargs['id_test'] context['test'] = Test.objects.filter(pk = self.kwargs['id_test']).first() context['question_form'] = self.question_form_class context['answer_form'] = self.answer_form_class return context def form_question_valid(self, form_question, form_answer): num_q = 0 y = 0 z = 0 for f in form_question: num_q+=1 self.object = f.save(commit = False) self.object.test = Test.objects.filter(pk = self.kwargs['id_test']).first() self.object.num = num_q f.save() count = self.object.answer_count num_a = 0 for z in range(count): num_a += 1 print(count) self.object = form_answer[y].save(commit = False) self.object.question = Question.objects.all().last() self.object.num = num_a form_answer[y].save() y += 1 return form_question, form_answer def get(self, request, *args, **kwargs): self.object = None FormsetQuestion = self.get_formset(QuestionForm) FormsetAnswer = self.get_formset(AnswerForm) … -
The carousel does not work, when I click the left or right button it does not do anything, assuming I'm not a Frontend engineer, what am I doing wrong
The carousel does not work, when I click the left or right button it does not do anything, assuming I'm not a Frontend engineer, what am I doing wrong here. The carousel does not work, when I click the left or right button it does not do anything, assuming I'm not a Frontend engineer, what am I doing wrong here. I used ChatGPT to fix it but it could not fix it, I hoped that the carousel moves and displayed the products -
Unable to login to Django admin website after setting SESSION_COOKIE_NAME="__Host-Session"
I have a Django application running locally. I wanted to change the SESSION_COOKIE_NAME to something with the prefix "__Host", so cookies are only sent to the host that initially set the cookie. However, I am unable to login into the admin page or the application after I do that. Setting SESSION_COOKIE_NAME to any other name works well, just not with prefix "__Host ". Any idea what might be causing this? Could the fact that I am running it locally(so HTTP instead of HTTPS) have something to do with it? -
How cam I count current active users on the site in Django or DRF
I have tried too many ways but still not found any solutions yet I have tried for current active user in my site. -
Login function not working in Django Python project
Description: I am working on a Django project which is a virtual wallet with admin and multi user login with interchangeable amounts. I am having issues with the login functionality. I have cloned the repository from GitHub (https://github.com/btmstage3/virtual-wallet-with-admin-and-multi-user-login-with-interchangeble-amounts-in-python.git) and followed the installation instructions in the README file. However, when I try to login with the default superuser credentials (username: admin, password: password), I get an error message saying "Invalid login credentials". I have checked my code and compared it to the code in the repository, but I cannot figure out what is causing the issue. I am new to Django and would appreciate any help or advice on how to fix this issue. Here is the code for my login view function: python from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Invalid login credentials') return redirect('login') return render(request, 'login.html') I would appreciate any suggestions or guidance on what could be causing this issue. Thank you in advance for your help. I've also checked that the … -
he server responded with a status of 404 (Not Found)
django template rendering i was try to inter the log into the web Failed to load resource: the server responded with a status of 404 (Not Found) what are the possible senarioes for thise problem ? django template rendering i try that if the problems is Missing file Incorrect file path -
Display image in template based on ID of image in Django
I'm building a small page in Django. For this page I have a model that stores images for the webpage. These can be updated in the future. I'm struggling to display the images properly. My model looks like this: def image_upload_handler(instance, filename): fpath = pathlib.Path(filename) new_fname = str(uuid.uuid1()) return f"{instance.imgLocation}/{new_fname}{fpath.suffix}" #models class coreImage(models.Model): imageName = models.CharField(max_length=255, blank=False) image = models.ImageField(upload_to=image_upload_handler) imgLocation='headerImages' def __str__(self): return f"{self.imageName} in {self.imgLocation}" The view looks like this: def core_view(request): context = { 'image' : coreImage.objects.all(), 'drinks' : DrinkRecipe.objects.all(), 'ingredients' : Ingredient.objects.all() } return render(request,'rhumSite/home.html',context=context) How do i get image with id=1 to show up in my template? I've tried this: <img class='page-img' src={{image.image(id=1).url}}> As you have guessed, this doesnt work. What am I doing wrong? Thanks in advance. -
how to pass dynamic url values into the context dictionary?
blog_confirm_delete.html <form method="POST" action=""> {% csrf_token %} <h2>Are you sure you would like to delete this post?</h2> <button type="submit" value="send" class="btn btn-danger">Yes, Delete</button> <button class="btn btn-info mb-8"> <a class="text-white" href="{% url 'blog-detail' post.id %}">Cancel</a> </button> </form> views.py class BlogDeleteView(SuccessMessageMixin,LoginRequiredMixin,TeacherOwnerPassesTestMixin,DeleteView): model = Post template_name = "postings/blog_confirm_delete.html" success_url = reverse_lazy('blog-list') success_message = "Your post has been deleted!" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['list_title'] = "Our Blog" context['list_url'] = "blog-list" context['detail_title'] = "Delete Post" context['cancel'] = ??? return context So currently I have to hard code the "Cancel" button's url for every "X_confirm_delete.html" template that I have. Now I would like to pass in a dynamic url value for each DeleteView so that I can reduce all DeleteView into using one simple template. How can I do this? Thank you for helping me in advance! -
Affichage de données MYSQL sur une template django [closed]
Bonjour, je suis en train de réaliser une application avec le framework django pour créer un gestionnaire d'emploi du temps pour des techniciens. J'arrive à afficher mon calendrier en utilisant full calendar mais j'aimerai récupérer les données stockées dans ma BD (pour l'instant local) MySQL et les afficher directement dans mon calendrier. Voici ma template : {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Calendrier</title> <!-- Inclure les fichiers CSS et JS nécessaires --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.js"></script> <script> $(document).ready(function() { // Initialisation du calendrier $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, defaultDate: moment(), editable: true, eventLimit: true, // Permet d'afficher "plus" lorsqu'il y a trop d'événements pour un jour events: [ {{ tache_list|safe }} ], }); }); </script> <style> body { margin-top: 40px; text-align: center; font-size: 14px; font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif; } #calendar { max-width: 900px; margin: 0 auto; } </style> </head> <body> <nav class="navMenu"> <ul> <li><a href="{% url 'home' %}" class="highlight">Calendrier</a></li> </ul> </nav> <div id="calendar"></div> </body> </html> Voici ma vue : def calendrier(request): events = [] for evenement in Tache.objects.all(): event = { 'id': evenement.id, 'title': evenement.pn, 'start': evenement.dateD.strftime('%Y-%m-%d'), 'end': evenement.dateF.strftime('%Y-%m-%d') } events.append(event) … -
My django project down when the SSH session is closed (running in the supervisor, gunicorn and nginx)
I've running my jdango project (name:A below) in the AWS EC2 with the Gunicorn and Nginx. I also installed Supervisor as to keep the A running. All running status(supervisor, gunicorn, nginx) are "active (running)" But I found the supervisor does not achieve that. I will attaach the conf info below, plz help me to find out how to set the supervisor. THX EC-2 Linux version 5.10.167-147.601.amzn2.x86_64 PATH: 1 Virtual environment: `/home/myname/phpdao/bin` 2 Django project: `/home/myname/project/phpdao (where manage.py located)` 3 Supervisor: `/home/etc (where supervisor.conf & supervisord.conf located)` 4 Gunicorn: `/home/myname/phpdao/bin` `/home/ec2-user/conf (where gunicorn_config.py located)` 5 Nginx: `/etc/nginx (where nginx.conf located)` Configuration: 1 Supervisor [unix_http_server] file=/home/ec2-user/etc/supervisor/var/supervisor.sock port =127.0.0.1:9001 [program:A] command=/home/ec2-user/phpdao/bin/gunicorn phpdao.wsgi:application --bind 0.0.0.0:8000 directory=/home/ec2-user/project/phpdao user=myname autostart=true autorestart=true redirect_stderr=true stout_logfile=/home/ec2-user/supervisor/phpdao.stdout.log steer_logfile=/home/ec2-user/supervisor/phpdao.stderr.log 2 Gunicorn command = '/home/ec2-user/phpdao/bin/gunicorn' pythonpath = '/home/ec2-user/project/phpdao' bing = 'public IP:8000' workers = 3 raw_env = 'DJANGO_SETTINGS_MODULE=phpdao.settings' errorlog = '/var/log/gunicorn/error.log' accesslog = '/var/log/gunicorn/access.log' loglevel = 'debug' timeout = 60 keepalive = 2 worker_class = 'gevent' 3 Nginx server { listen 80; listen [::]:80; server_name www.A.com; access_log /home/ec2-user/nginx/phpdao.access.log; root /home/ec2-user/project/phpdao/phpdao1/templates; location /static/ { alias /home/ec2-user/project/phpdao/phpdao1/static; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; error_page … -
Override result_list templatetag in Django
I have custom change_list.html and change_list_results.html and would like to pass data from model admin. I can get the data on change_list.html but not in change_list_results.html. After researching on the internet the problem is in change_list_results.html, it's using templatetag result_list, by default take_context is set to False. Below is the code of my model admin: class HistoryAdmin(UpdateUserAdminMixin, admin.ModelAdmin): list_filter = ( ('created_date', DateRangeFilter), ) list_per_page = sys.maxsize actions = None list_display_links = None list_display = ('created_date', 'patient', 'price', 'payment') readonly_fields = ('created_date', 'updated_date') def get_rangefilter_created_date_default(self, request): return (datetime.date.today, datetime.date.today) def changelist_view(self, request, extra_context=None): start_date = datetime.datetime.strptime(request.GET.get('created_date__range__gte'), "%d-%m-%Y").date() end_date = datetime.datetime.strptime(request.GET.get('created_date__range__lte'), "%d-%m-%Y").date() default_start_date = History.objects.first().created_date.date default_end_date = History.objects.latest('created_date').created_date.date results = History.objects.filter(created_date__range=(start_date, end_date)) total_payment = str(results.aggregate(Sum('payment'))['payment__sum']) total_price = str(results.aggregate(Sum('price'))['price__sum']) extra_context = {'title': CONSTANTS.MODEL_SINGLE_HISTORY, 'total_payment': total_payment, 'total_price': total_price} print(f'{results.values} {total_payment} {total_price}') return super(HistoryAdmin, self).changelist_view(request, extra_context=extra_context) I can access total_payment and total_price in change_list.html like this: {{ total_payment }} {{ total_price }} Can anyone please help on how to access it in change_list_results.html? Thanks in advance. -
'ordering' must be a tuple or list (even if you want to order by only one field)
class Product(models.Model): publishDate = models.DateTimeField(max_length=20,default=timezone.now,verbose_name='time') views = models.PositiveIntegerField('view', default=0) class Meta: verbose_name = 're' verbose_name_plural = 're' ordering = ('-publishDate',) it says: 'ordering' must be a tuple or list (even if you want to order by only one field). -
How to redirect login to a home page whose template is inside app not at project level :python django
Normally using inbuilt login system in django the login page is set inside the projects setting.py LOGIN_REDIRECT_URL = "home" The above code works if the template is at a project level directory i.e 'django_project/templates'. What if the templates are inside app i.e 'django_project/app_name/templates' ? -
sudo : The term 'sudo' is not recognized as the name of a cmdlet, function, script file, or operable program
docker-compose.yml version: '3' services: build: . command: python manage.py runserver 0.0.0.0.:8000 volumes: - .:/app ports: - "8000:8000" Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ requirements.txt Django>=2.2 I am getting the error on vs code. I don't know how to solve it. -
Adding an element to a ManyToManyField in Django not saved?
While I was making one of my first projects on Django, I had to create two models. One of them, Image, has a field tags which is a ManyToManyField referring to the other model, Tag. I wanted to add elements to the tags field with a post_save signal. No problem occur during this process (in particular, the elements I want to add exist), but at the end no element is added. Here is a snipplet of the models.py I've written so far : # (Importing the modules ...) class Image(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="media/") tags = models.ManyToManyField("Tag", related_name="images", blank=True) class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) def __str__(self): return self.name @receiver(post_save, sender=Image) def create_tags(sender, instance, created, **kwargs): if created: print(f"Before : {instance.tags.all()}") tag = Tag.objects.first() instance.tags.add(tag) instance.save() print(f"After : {instance.tags.all()}") When I add an element through the admin panel, the following is printed : Before : <QuerySet []> After : <QuerySet [<Tag: myfirsttag>]> But if I check the freshly added element, no tag is selected. Could you please help me figuring out what I am doing wrong ? Thanks in advance and have a nice day ! -
Aborting the task is not stopping the sub process created by celery task
From Django, I'm starting the celery task which will trigger the sub process @app.task(bind=True, base=AbortableTask) def execute_script(self, data: dict): script = data.get("input") if script and script in get_scripts(): # Executing related script script_path = os.path.join(settings.CELERY_SCRIPTS_DIR, script) process = subprocess.Popen( f"python {script_path}", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) time.sleep(8) error = False if process.wait() == 0: # If script execution successful logs = process.stdout.read().decode() else: logs = process.stderr.read().decode() error = True return {"logs": logs, "input": script, "error": error, "output": ""} To abort the task, I use below code def cancel_task(request, task_id): result = TaskResult.objects.get(task_id=task_id) abortable_result = AbortableAsyncResult(result.task_id, task_name=result.task_name, app=app) if not abortable_result.is_aborted(): abortable_result.revoke(terminate=True) time.sleep(1) return redirect("home") After aborting the task, celery task is stopped by Subprocess is still running. Can you guide to solve this problem. -
django post mehod while insert data
in an django project, I want to insert a title, category, image to the backend. On that thing the if statement is not working in while run the program. This is my form <form action="" enctype="multipart/form-data" method="POST" class="p-4"> {% csrf_token %} <div class="row"> <div class="col-md-12 mb-3"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control p-3" placeholder="title" name="title"> </div> </div> <div class="col-md-12 mb-3"> <div class="form-group"> <label for="category">Category</label> <select id="category" class="form-control form-select p-3" name="category"> <option value="none">Select a category</option> {% for opt in category %} <option value="{{ opt }}">{{ opt }}</option> {% endfor %} </select> </div> </div> <div class="col-md-12 mb-3"> <div class="form-group"> <input type="file" class="form-control p-3" name="image"> </div> </div> <div class="mt-3 col-md-12"> <button class="btn btn-primary" style="width: 100%;">Upload</button> </div> </div> </form> and This is my view def add(request): if request.method == 'POST': print("POST request received") title = request.POST.get('title') cat = request.POST.get('category') image = request.FILES.get('image') print(title, cat, image) else: print("GET request received") categories = addcategory.objects.all() context = { 'category': categories, } return render(request, 'add.html', context) The terminal output will be GET request received [07/Apr/2023 05:49:28] "GET /add/?csrfmiddlewaretoken=il3U1rnxUl5217Wud9i1kX6TfMNk7uOoQDfUYxYb8UlYZIczG4Uz4OgR6nib4yrF&title=veg&category=Food&image=food.jpeg HTTP/1.1" 200 4672 I want to print the "POST request received". -
How can i auto fill a field and make it readonly in django admin
I want the created_by field to be filled automatically with the email of the current admin who is logged in and it should be read only field I tried this: admin.py from django.contrib import admin from support.models import Ticket class TicketAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields['created_by'].initial = request.user return form def save_model(self, request, obj, form, change): if not obj.created_by: obj.created_by = request.user super().save_model(request, obj, form, change) admin.site.register(Ticket, TicketAdmin) I'm still able to edit the field and able to select other email addresses from a dropdown model.py class Ticket(models.Model): PRIORITY = ( ("High", "high"), ("Medium", "medium"), ("Low", "low") ) subject = models.CharField(max_length=255) body = models.TextField() priority = models.CharField(max_length=10,choices=PRIORITY) created_by = models.ForeignKey(Users, on_delete=models.CASCADE) How can I implement it? -
Can I use set operation in django template(3.x)?
Here's the code I am trying to shorten: {% url 'accounts:signup' as signup %} {% url 'accounts:login' as login %} {% url 'accounts:update' as update %} {% url 'accounts:password' as change_password %} {% if request.path == signup or request.path == login or request.path == update or request.path == change_password %} document.querySelector('h6').textContent = '' {% endif %} But can I use set operation as in Python, such as: {% url 'accounts:signup' as signup %} {% url 'accounts:login' as login %} {% url 'accounts:update' as update %} {% url 'accounts:password' as change_password %} {% if request.path in {signup, login, update, change_password} %} document.querySelector('h6').textContent = '' {% endif %} The code above gives me TemplateSyntaxError. So does {% if request.path in signup, login, update, change_password %} and {% if request.path in "signup, login, update, change_password" %} doesn't work. Passing boolean value True from view functions and using it in the if tag works, but it seems inefficient: it is hard to maintain. {% if my_var %} document.querySelector('h6').textContent = '' {% endif %} How can I make it more efficient? Either in template or view level.