Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot import Django
During an online course, I came across this error! According to the error, Django isn't available on my machine. Tried reinstalling the same, but got the same error! Was checking for errors when I came across this error in VS code. Tried various solutions found online but to no avail. Please help! -
Set Apache to prompt a password for a Django site?
I have a Django wsgi site that I would put online soon. I would rather the site to not be accessible except through an Apache login prompt until it is ready. I investigated and found limited or outdated information about how to do it (which I tried anyway). There is more information to make it work with a plain Apache served webpage and I was able to made it work on my default Apache welcome page, but Django seems less documented in that regard. For example I added something like this in my .conf file: <Directory "/path/to/djangosite"> AuthType Basic AuthName "Restricted Content" AuthUserFile /etc/apache2/.htpasswd Require valid-user </Directory> where /path/to/djangosite is where wsgi.py resides. Password was set in .htpasswd successfully. How are you all doing this? -
Unwanted glassy border outside of background images
I'm using Django, HTML and CSS to build a website to post some pictures, but I'm fairly new. I'm using a <div> with backgound-image style to load picture on a website. For some reason, every picture is loaded with some border radius (even though I don't have any in my CSS) and it has this weird glassy-looking border, some of the pictures also have a black line among some of the borders. Here is how it looks like. My html file: <div class="container"> <div class="photo-grid"> {% for i in image|dictsort:'pub_date' %} {% if i.is_tall == True and i.is_wide == False %} <div class="card" style="background-image:url('{{i.image.url}}')"> {{i.title}} </div> My CSS file: .container { display: flex; justify-content: center; justify-items: center; } .photo-grid { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); grid-auto-rows: 240px; margin-top: 75px; margin-bottom: 3vw; width: 1500px; } .card { display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%; width: 100%; overflow: hidden; background-size: cover; background-position: center; background-repeat: no-repeat; } I have no idea what could be wrong with it. I tried deleting random lines of CSS, but nothing seemed to be working. -
Django no reverse match at
I have a problem with my code I'm trying to create an edit button to modify the employees subsequently displayed and make the changes but I can't display with dynamic url in django. views.py def editerEmploye(request, pk): editer = Employe.objects.get(id=pk) context = {'editer':editer} return render(request, 'accounts/editer_form.html', context) url.py urlpatterns = [ path('', views.home), path('dashboard/', views.home, name="dashboard"), path('employe/', views.employe, name="employe"), path('disciplinaire/', views.disciplinaire, name="disciplinaire"), path('employe_form/', views.createEmploye, name="employe_form"), path('editer_form/<str:pk>/', views.editerEmploye, name="editer_form"), employe.html <td><a href="{% url 'editer_form' employe.id %}">Editer </a> models.py class Employe(models.Model): Matricule = models.CharField(max_length=10, null=False) Prenom = models.CharField(max_length=40, null=True) Nom = models.CharField(max_length=40, null=True) Tel = models.CharField(max_length=20, null=True) Adresse = models.CharField(max_length=100, null=True) Courriel = models.CharField(max_length=100, null=True) Horaire = models.CharField(max_length=50, null=True) Date_embauche = models.CharField(max_length=100, null=True) data_created = models.DateTimeField(auto_now_add=True, null=True) screenShot of the page -
Django templating for loop working for the first item
Can't really find out what am doing wrongly !! I created a template that has a view and in that view I created a context dictionary which contain filtered orders for a specific user but for some reason in the template I created a loop for order details with a button which allows the user to see more order details but its working only for the first order item my order model class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) total = models.FloatField(max_length=15,null=True, blank=True) shipping = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=15, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) delivery = models.CharField(max_length=200, default="3-20 business days", blank=True, null=True) def __str__(self): return str(self.id) my view: @login_required(login_url="login") def user_Orders(request): user = request.user.customer orders = Order.objects.filter(customer=user).filter(complete=True) return render(request, 'shop/orders.html', {'orders':orders, "user":user}) my template <h3 style="color: #0457ae;padding-left: 40px;"><u>YOUR ORDERS</u></h3> {% for order in orders %} <p>Order total: ${{order.total}}</p> <p>Status: Paid</p> <p>Transaction id/tracking number :<span id="trans_id">&nbsp;{{order.transaction_id}}</span></p> <button id="myBtn" class="btn btn-outline-primary">more details</button> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> <center><u>More order details</u></center> <p>shipping to :{{order.shipping}}</p> <p>Estimated delivery: {{order.delivery}}</p> <p>phone: {{order.phone}}</p> </div> </div> {% endfor %} </div> the images below shows the output ... I want … -
When setting use multiple databases getting error settings.DATABASES is improperly configured
I am trying to setup multiple databases in django and I am getting error message when trying to submit information using website form. The web form still submits data but shows error message. Also I am able to access the django admin page successfully. error: ImproperlyConfigured at /signup settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Here is the code of my settings.DATABASES DATABASES = { 'default': { }, 'users_db':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'users.db.sqlite3', } } here is DATABASE_ROUTERS=['routers.db_routers.AuthRouter',] below is code for Auth Router: class AuthRouter: router_app_labels={'auth','user','contenttypes','sessions','admin' } def db_for_read(self, model, **hints): if model._meta.app_label in self.router_app_labels: return 'users_db' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.router_app_labels: return 'users_db' return None def allow_relation(self, obj1, obj2, **hints): if( obj1._meta.app_label in self.router_app_labels or obj2._meta.app_label in self.router_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.router_app_labels: return db == 'users_db' return None Would like to see the reason for this error and resolution. I have already done data migration for users_db A simple successfull example of implementation of github code would also help if solutions don't work. -
What is the most Django-appropriate way to combine multiple database columns into one model field?
I have several times come across a want to have a Django model field that comprises multiple database columns, and am wondering what the most Django way to do it would be. Three use cases come specifically to mind. I want to provide a field that wraps another field, keeping record of whether the wrapped field has been set or not. A use case for this particular field would be for dynamic configuration. A new configuration value is introduced, and a view marks itself as dependent upon a configuration value, redirecting if the value isn't set. Storing whether it's been set yet or not allows for easy indefinite caching of the state. This also lets the configuration value itself be not-nullable, and the application can ignore any value it might have when unset. I want to provide a money field that combines a decimal (or integer) value, and a currency. I want to provide a file field with a link to some manner of access rule to determine whether the request should include it/a request for it should succeed. For each of the use cases, there exists a workaround, that in each case seems less elegant. Define the configuration fields … -
How make buttons in all cards clickable?
Hi I created a web app with Django. In this app there are 6 cards with a button for increase and a button for decrease the quantity of food to buy. I have a problem: only the buttons in the first card work. Here's the HTML code <div class="container"> <div class="row"> {% for roll in rolls %} <div class="col-4"> <div class="card" style="width: 16rem;"> <img src="{{ roll.immagine.url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ roll.nome }} Roll</h5> <p class="card-text">€ {{ roll.prezzo }}</p> <button id="incrementBtn" style="border-radius: 8px; background-color:orange;">+</button> <span id="counter">0</span> <button id="decrementBtn" style="border-radius: 8px; background-color: lightsalmon;">-</button> <a href="{% url 'ordina' %}" class="btn btn-primary">Acquista</a> </div> </div> </div> {% endfor %} </div> </div> Here's the Javascript code: document.addEventListener("DOMContentLoaded", function() { let idCounter = "counter1, counter2, counter3, counter4, counter5, counter6"; let arrIdCounter = idCounter.split(", "); console.log(arrIdCounter); let valueCounter = document.getElementById('counter').innerHTML; const incrementBtn = document.getElementById('incrementBtn'); const decrementBtn = document.getElementById('decrementBtn'); incrementBtn.addEventListener('click', () => { console.log(valueCounter); valueCounter++; document.getElementById('counter').innerHTML = valueCounter; console.log(valueCounter); }); decrementBtn.addEventListener('click', () => { if (valueCounter > 0) { valueCounter--; } document.getElementById('counter').innerHTML = valueCounter; }); }); -
How to write custom validation on django rest framework?
How to write custom validations on drf. I have validate function on serializer. Can someone help whats wrong with my code? my views: class MyCustomView(ListCreateAPIView): def create(self, request, *args, **kwargs): serializer = MyCustomSerializer(data=request.data) serializer.is_valid(raise_exception=True) my serializer: class MyCustomView(serializers.Serializer): name = serializers.CharField(required=True, max_length=64) address = serializers.CharField(required=True, max_length=64) def validate(self, attrs): if not attrs.get('name'): raise serializers.ValidationError('Name field is required.') when i request with blank name and address it shows default drf error. How to override this function? -
Why my form isn't valid in view whatever I type in?
I am trying to create authentication app with form and it isn't working. I have put some print functions in my view and it prints post and than not valid. I want to click submit button which would trigger post request and view would create new user. view.py def index(request): form = forms.RegisterForm() context = { 'form': form } if request.POST: print('post') if form.is_valid(): print('valid') form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password') account = authenticate(email=email, password=raw_password) print('authenticate') login(request, account) return redirect('home') else: print('not valid') context['registration_form'] = form else: form = forms.RegisterForm() context['registration_form'] = form return render(request, 'index.html', context) html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </body> </html> forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import ReadOnlyPasswordHashField User = get_user_model() class RegisterForm(forms.ModelForm): """ The default """ full_name = forms.CharField(max_length=30) password = forms.CharField(widget=forms.PasswordInput) password_2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput) class Meta: model = User fields = ['email'] def clean_email(self): ''' Verify email is available. ''' email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean(self): ''' Verify both passwords match. ''' … -
PyCharm doesn't recognize user instance when using custom user model in Django
I have a custom user model in my Django project and when I create an instance of request.user in my views PyCharm doesn't seem to recognize the user instance correctly. The available methods/attributes suggested by PyCharm still point to the built-in Django user model but not to my new one. Is there any way to set this up properly? Example: # settings.py AUTH_USER_MODEL = 'user.UserProfile' # models.py custom user model class UserProfile(AbstractBaseUser, PermissionsMixin): # Email and name of the user email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) # Privilege and security booleans is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) email_confirmed = models.BooleanField(default=False) # Company on whose behalf the user acts on company = models.ForeignKey('company.Company', on_delete=models.CASCADE, blank=True, null=True) objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def email_user(self, subject, message, from_email=None, **kwargs): """Send mail to user - Copied from original class""" send_mail(subject, message, from_email, [self.email], **kwargs) def __str__(self): return self.email # views.py def render_dashboard_benefits(request): # Get current user instance current_user = request.user # Typing... current_user.company # Pycharm suggests 'first_name' and 'last_name' depending on the initial user model # but not e.g. "email" or "company" according to the new user model return render(request, 'test.html') I'm using the paid PyCharm … -
how i can show django proxy model to a virtual app
I create a proxy model from orginal model Product. How I can show this proxy model to another virtual app called "Store2" class ProductProxy(models.Product): class Meta: proxy = True @admin.register(ProductProxy) class HeroProxyAdmin(admin.ModelAdmin): list_display = ['id'] @admin.register(models.Product) class ProductProxyAdmin(admin.ModelAdmin): list_display = ['id', 'title' -
How to delete all records which is 24 hours old using django ORM?
Model class Question(models.Model): question_text = models.CharField(max_length=100) option1 = models.CharField(max_length=50,null=False) option1_vote = models.IntegerField(default=0) option2 = models.CharField(max_length=50,null=False) option2_vote = models.IntegerField(default=0) option3 = models.CharField(max_length=50,null=False) option3_vote = models.IntegerField(default=0) option4 = models.CharField(max_length=50,null=False) option4_vote = models.IntegerField(default=0) date_time = models.DateTimeField(auto_now=True) user = models.ForeignKey(User,on_delete=models.CASCADE) We have the date_time field here. Question.objects.filter(condition).delete() what condition should I put there? -
How to fix delete record after some date in django not working?
I am trying to delete records after expiry_date_time is less than or equal to current date time but it was not working properly. Also giving this error RuntimeWarning: DateTimeField Question.date_time received a naive datetime (2022-08-28 10:15:19) while time zone support is active. API deleting wrong records. def delete(self, request): count = 0 count, _ = Question.objects.filter( expiry_date_time__lte=datetime.now(timezone.utc).today() .strftime('%Y-%m-%d %H:%M:%S')).delete() print(now().today() .strftime('%Y-%m-%d %H:%M:%S')) resp = {'Total question deleted': count} print(resp) return Response(resp) -
Deploy django restframeworkapi on server
i want to set post req to my api application. in postman when I send the post in the object program, it returns the following text as a response and the data is not saved in the database. i got in browser: Employee List POST /employees/ HTTP 403 Forbidden Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "CSRF Failed: CSRF token missing or incorrect." } but i got different error in postman: Server Error (500) is set: DEBUG = False ALLOWED_HOSTS = ['*'] in settings.py But the problem is still not solved and the error remains. What should I do to fix this error? -
Can't display object properties when retrieving an Item List
sorry if this is a simple mistake but I couldn't figure it out. I am trying to display the watchlisted items of the logged in user. I am able to display a list but the item details such as title, price etc. don't show up. models.py: class Watchlist(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, name = "user") item = models.ForeignKey(AuctionItem, on_delete = models.CASCADE, name = "item") def __str__(self): return f"Username: {self.user} / {self.item} " views.py: @login_required def watchlist(request,user): user = request.user item_list = Watchlist.objects.filter(user_id=user) return render(request, "auctions/watchlist.html",{ "item_list" : item_list }) watchlist.html: {% extends "auctions/layout.html" %} {% block body %} {% for item in item_list %} <div class = "frame"> {% if item.image %} <img src="{{item.image}}" style= "width: 30vw;"> {% endif %} <h4><a href="{% url 'listing' item.id %}">{{item.title}}</a></h4> <div id="text"><strong>Price:</strong> ${{item.price}}</div> <div id="text"><strong>Description:</strong> {{item.description}}</div> <div id="text"><strong>Category:</strong> {{item.category}}</div><br> <div id="date">Created {{item.date}}</div> </div> {% endfor %} {% endblock %} urls.py: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create_listing, name="create"), path("listing/<int:listing_id>", views.listing, name = "listing"), path("<str:user>/watchlist", views.watchlist, name= "watchlist") ] and here is what I'm getting as a result: -
why django returns me a template Error for this case {% if user.is_authenticated %}?
i would like to add on my django template main page interface a condition but it return me this error : ProgrammingError at / relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... ther is the Template code : ... {% extends '_base.html' %} {% block title %}Home Page{% endblock title %} {% block content %} <h2>Homepage</h2> {% if user.is_authenticated %} <p>Hi {{ user.email }}</p> {% else %} <p>You are not Loged</p> <p><a href="{% url 'login' %}">Log In</a> </p> {% endif %} {% endblock content %} ... thamk you for your answers -
Error with queryset get_absolute_urls Django
django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with keyword arguments '{'slug': 'test'}' not found. 1 pattern(s) tried: ['detail<slug:slug/\\Z'] I'm trying to create a product detail, filtering it by slug(maybe it can be ID), so I decided to send the slug trough an URL and then filter the product by the specifiedslug, but im getting troubles to implement it(my other get_absolute_url its working but this one I cant fix). models.py: class Product(models.Model): name = models.CharField(max_length=255, unique=False, blank=True) slug = models.SlugField(unique=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, unique=False) subcategory = models.ForeignKey( SubCategory, on_delete=models.CASCADE, unique=False, blank=True, null=True) short_description = models.CharField( max_length=255, unique=False, blank=True, null=True) long_description = models.TextField(unique=False, blank=True, null=False) image = models.ImageField(blank=True, null=True, unique=False) on_promotion = models.BooleanField(default=False) def __str__(self): return self.slug def get_absolute_url(self): return reverse("product:detail", kwargs={"slug": self.slug}) urls.py: urlpatterns = [ path('', views.index, name="index"), path('detail<slug:slug/', views.ProductDetail.as_view(), name="detail"), path('category-<int:category_id>/', views.category, name="category"), path('category-<int:category_id>/subcategory-<int:subcategory_id>', views.subcategory, name="subcategory") ] views.py """ def detail(request, product_id): product = Product.objects.get(product_id) return render(request, 'product/detail.html', {'product_id': product}) """ class ProductDetail(DetailView): template_name = 'product/detail.html' # queryset = Product.available.all() def get_queryset(self): queryset = Product.available.filter(slug=self.kwargs.get("slug")) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context template: <a href="{{product.get_absolute_url}}">aaa</a> -
How can I create a form and view from forms.py?
I have model with AbstractBaseUser and BaseUserManager. I have also build admin.py and forms.py. That all works just fine I checked in admin, so now I want to actually create a form in which user could type in and view which will take that data and create new user. Since there aren't many good tutorials on AbstractBaseUser I don't know how to do that myself. If you want me to post anything else just write in comments:) models.py from multiprocessing.managers import BaseManager from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', … -
Document for django project
How can I write a Document for my project? Does anyone know the correct tutorial? I want to write a document for my Django project. Does anyone know a suitable road map? -
Display ManyToManyField of User which are in request.user profile in drf
I am building a Blog App and with React and Django Rest Framework, and I am trying to display liked field which is ManyToManyField in Profile model, In Django Rest Framework. But the problem is It is showing request.user's username in every item of the response list (in axios data). like :- [{"likes": ["user_1"]},{"likes": ["user_1"]}] models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='likes') serialiers.py class LikesSerializer(serializers.ModelSerializer): likes = serializers.StringRelatedField(many=True) class Meta: model = Profile fields = ( "likes", ) views.py class LikesUserApiView(viewsets.ModelViewSet): serialier_class = LikesSerializer def get_queryset(self, *args, **kwargs): return self.request.user.profile.likes.all() I have also by using filter in view, like return Profile.objects.filter(likes=self.request.user) But is showed []. What I am trying to do ? I am trying to get users which are in ManyToManyField of request.user. also tried by using likes__in=self.request.user but it showed TypeError: 'User' object is not iterable. -
Encrypt data in file txt using AES in django
so i want to encrypt data what's in the file i was upload. but when i read the data, the plaintext says it's none (i called that func at func encrypt) but when i called that func at homepage, its works well (can read the data). i don't know what's wrong. please help me to encrypt data in the file txt what i was upload. here's my code: def read_file(f): f = open('media/txt/'+f, 'r') f.read() f.tell() f.seek(0) file_content = f.read() f.close() print(file_content) key_bytes = 16 # here's a rudimentary change that accepts bytes or # str def encrypt(key, pt): plaintext = read_file(pt) # plaintext = plaintext[0] # if isinstance(plaintext, str): # pt= plaintext.encode("utf-8") print(plaintext) assert len(key) == key_bytes # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(plaintext) print(ciphertext) return (iv, ciphertext) -
Django + Celery - How to send Django's password reset email using Celery?
This question has been answered previously here, but this solution didn't help me, my email is not sent by Celery. I use Celery 5.1.2 My code: forms.py from django.contrib.auth import forms as admin_forms from django.utils.translation import gettext_lazy as _ from users.tasks import reset_password class PwdResetForm(admin_forms.PasswordResetForm): email = forms.EmailField(max_length=150, widget=forms.TextInput()) def clean_email(self): email = self.cleaned_data['email'] test = User.objects.filter(email=email) if not test: raise forms.ValidationError( _('Unfortunately we can not find that email address')) return email def send_mail( self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None, ): context['user'] = context['user'].id reset_password.delay(subject_template_name=subject_template_name, email_template_name=email_template_name, context=context, from_email=from_email, to_email=to_email, html_email_template_name=html_email_template_name) tasks.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import PasswordResetForm from celery import shared_task from config.celery_app import app User = get_user_model() @shared_task # I also tried using @app.task def reset_password(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name): context['user'] = User.objects.get(pk=context['user']) PasswordResetForm.send_mail( None, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name ) celery_app.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "auto_store.settings") app = Celery("auto_store") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() Maybe this is due to the fact that I also have tasks.py in another app? If it's possible, I want to solve this problem without third-party package. Thanks for the help. -
How to get value from jinja for loop in django
I have a form which contains table where list of students from data base is listed I want to get the value of every student from table on submit button and also there status if they are present or not Html Code <div class="container"> <form method="POST" action="takeattendance"> {% csrf_token %} <div class="form-group"> <h4 style="color:white;"> Select Subject For Attendance</h4> <select class="btn btn-success" name="subject"> <option selected disabled="true">Subject</option> {% for sub in subjects%} <option value="{{ sub.id }}">{{sub.subject_name}}</option> {%endfor%} </select> </div> <table class="table" > <thead> <tr> <th scope="col" style="color:white;"><b>Email</b></th> <th scope="col" style="color:white;"><b>Roll No.</b></th> <th scope="col" style="color:white;"><b>First Name</b></th> <th scope="col" style="color:white;"><b>Last Name</b></th> <th scope="col" style="color:white;"><b>Year</b></th> <th scope="col" style="color:white;"><b>Division</b></th> <th scope="col" style="color:white;"><b>Batch</b></th> <th scope="col" style="color:white;"><b>Attendance</b></th> </tr> </thead> <tbody> {%for student in students%} {%if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year%} <tr> <td style="color:white;" name="student_name" value="{{student.id}}">{{student.user}}</td> <td style="color:white;">{{student.roll_no}}</td> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> <td style="color:white;">{{student.year}}</td> <td style="color:white;">{{student.division}}</td> <td style="color:white;">{{student.batch}}</td> <td> <div class="form-group"> <select class="btn btn-success" name="status" id="status"> <option selected value="Present">Present</option> <option value="Absent">Absent</option> </select> </div> </td> </tr> {% endif %} {%endfor%} </tbody> </table> <div class="form-group"> <button type="submit" class="btn btn-info btn-lg ">Add</button> </div> </form> </div> views.py def staffattendance(request): if request.user.is_authenticated and request.user.user_type==3: subjects = Subject.objects.all() students=Student.objects.all() return render (request, 'ms/staff/attendance.html',{'subjects':subjects, 'students':students}) else: return render(request,'ms/login/login.html') def takeattendance(request): if request.method == "POST": … -
How to send ImageFieldFile objects fetched from the database by django to the front-end and display them
When using django as a backend, I have an image saved in the database in ImageField format, and in the view layer I get the object via orm, how can I return it to my vue frontend. I turned the ImageField object into a string to return a JsonResponse, but the front-end only gets the name of the image when it's read def getContent(request): mtitle=request.GET.get('title') row_obj=models.content.objects.filter(title=mtitle).first() res={ "pic":str(row_obj.img), } print(type(row_obj.img)) return JsonResponse(res, json_dumps_params={"ensure_ascii": False}) How do I request the image to be displayed on the front end?