Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to log in with email in django
I have created custom user model but unable to login with valid email id and password models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser objects = UserManager() # notice the absence of a "Password field", that is built in. USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] methods like has_perm,has_module_perm are written. forms.py class AuthenticationForm(forms.Form): email = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'email','placeholder':'Email'}), label='Email') password = forms.CharField(widget=forms.PasswordInput( attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':'Password'}), label='Password') class Meta: fields = ['email', 'password'] views.py def loginEmployeeView(request): if request.method == 'POST': form = AuthenticationForm(data = request.POST) if form.is_valid(): print("1") email = request.POST.get('email') password = request.POST.get('password') print("2") user = authenticate(email=email, password=password) print("3") if user is not None: if user.is_active: print("4") login(request,user) messages.success(request,'Logged in successfully') return redirect('dashboard') else: messages.error(request,'user is not active') return redirect('login-employee') else: messages.error(request,'invalid username or password') return redirect('login-employee') else: print("5") form = AuthenticationForm() return render(request,'accounts/login.html',{'form':form,}) I tried to logged in with valid information still it shows invalid username or password. Thank you. -
Test django sqlite3 database with pytest in CI
I have an updater class which updates database tables (modifies, removes, adds). I need to write a tests for this updater. These tests will be called in gitlab CI. python3.9 project/manage.py makemigrations python3.9 project/manage.py migrate pytest -s -v --cov --cov-config .coveragerc -ra --tb=short {posargs:} "Test" database does not contain required tables until migrations call. I feel like there is existing "pytest mechanism" which allow to create fake sqlite3 database instance with performed migrations, which I do not know :D. Django database config: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), "TEST": { "MIRROR": "default" } }, } I have already installed pytest-django and marked test with pytest.mark.django_db. Is it appropriate way of testing? -
How to toggle class for clicked button in for loop?
trying to add post to bookmark. posts are on home page with in for loop. I have trouble getting toggle class while clicking on add bookmark button for individual post. Django view @login_required def add_post_bookmark(request): ''' add post to bookmark ''' if request.POST.get('action') == 'post': result = '' is_bookmark = False id_ = request.POST.get('id') post = Post.objects.get(id=id_) if post.bookmarks.filter(id=request.user.id).exists(): post.bookmarks.remove(request.user) is_bookmark = False post.save() result = post.get_bookmarks_count() else: post.bookmarks.add(request.user) is_bookmark = True post.save() result = post.get_bookmarks_count() return JsonResponse({'result': result, 'bookmark_count': post.bookmarks.all().count(), 'post_id': id_, 'is_bookmark': is_bookmark}) Ajax // bookmarks posts $(document).on('click', '#bookmark_add', function (e) { e.preventDefault(); var bookmarkCount; var id = $(this).data("id"); $.ajax ({ type: 'POST', url: '{% url "users:add-post-bookmark" %}', data: { 'id': id, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function (response) { $('#'+id).empty().append(response['bookmark_count']); console.log(response); this_id = $(this).data("data-id"); //("id") console.log(this_id); // undefined $(this).find('i').toggleClass("fad fa-bookmark far fa-bookmark"); }, error: function (xhr, errmsg, err) { console.log("Error bookmarking post!"); } }); }) index.Html <span id="{{post.id}}" class="bookmark_coun text-muted">{{ post.get_bookmarks_count }}</span> {% if request.user.is_authenticated %} {% if request.user not in post.bookmarks.all %} <button id="bookmark_add" class="bookmark" name="bookmark" data-id="{{post.id}}"><i class="far fa-bookmark fa-lg"></i></button> {% else %} <button id="bookmark_add" class="bookmark" name="bookmark" data-id="{{post.id}}"><i class="fad fa-bookmark fa-lg"></i></button> {% endif %} {% else %} <a href="{% url 'users:register' %}" id="bookmark_add" … -
how to iterate through list inside another list - json + js
I'm trying to iterate over a list inside another list , here is my data : (3) [{…}, {…}, {…}] 0: {id: 9, check_in: '2021-10-02T15:58:00', check_out: '2021-10-05T10:17', visitors: Array(4)} 1: {id: 10, check_in: '2021-10-06T21:12:00', check_out: '2021-10-09T15:00', visitors: Array(4)} 2: {id: 11, check_in: '2021-10-27T21:34:00', check_out: '2021-10-29T21:34', visitors: Array(4)} length: 3 my visitors array looks like this : visitors: Array(4) 0: {full_name: 'name1'} 1: {full_name: 'name2'} length: 2 and so on , and here is my js code with html $.ajax({ url:'my_url', type:'json', method:'GET', success:function(data){ let booking = data.lists let visitors = data.lists.visitors console.log(visitors) let content=''; for(j=0; j< booking.visitors;j++){ console.log(j) } for(i=0;i<booking.length;i++){ content+='<div class="border border-purple-900 rounded-xl p-1 text-sm text-center">'; content+='<p>'+booking[i]['visitors']['full_name']['full_name']+'</p>'; content+='</div>'; content+='<div class="mt-1">'; let check_in= new Date(booking[i]["check_in"]).toLocaleDateString([], { day: '2-digit',month: '2-digit',year: 'numeric' ,hour: '2-digit', minute:'2-digit'}); if(booking[i]['check_out']){ check_out = new Date(booking[i]['check_out']).toLocaleDateString([], { day: '2-digit',month: '2-digit',year: 'numeric' ,hour: '2-digit', minute:'2-digit'}); }else{ check_out = 'not mentioned' } content+='<p>'+check_in+' to ' +check_out+ '</p>' content+='</div>' } content+='</div>' $("#current-booking").html(content); }}); and console.log(visitors) return undefined ! , now i dont know how to return back list of full names from ajax ? is there something i have to change please ? and here is my views.py current_booking = Booking.objects.filter(leave=False,room_no__room_no=room_no) visitors_booking = BookingVisitor.objects.filter(booking__room_no__room_no=room_no,booking__leave=False) lists = [] visitors = [] for … -
In production bad url shows Internal Server Error instead of customized 404
I've created a simple handler404 according to documentation. In local it works fine, for example when user tries to access an url that does not exist the handler of 404 error is called. But in production it shows a classic "Internal Server Error" and I can't understan why. The handler are these: view.py: def handler500(request): context = {} return render(request, "maintenance/error500.html", status=500) def handler404(request, exception): context = {} return render(request, "maintenance/error404.html", status=404) In urls.py I addes following rows to call the correct handler: urls.handler500 = views.handler500 urls.handler404 = views.handler404 (I set DEBUG=False) I thought that the error raised before handler404 called, but why in local it works and in production not? Thanks in advance for suggestions! -
Django allauth redirects back to sign up page after email verification (which also fails)
I have a weird issue using Django allauth. The sign up works and sends an email verification email, after I click the verification link sent via email I am redirected to the email confirmation page. The problem is once I click "confirm" to confirm my email I am redirected back to the sign up page and the verification appears to fail as well (no error is thrown). When I go to login as the newly created user another verification email is sent and the cycle repeats itself. I have tried to configure my settings to redirect to http://127.0.0.1:8000/ Settings.py #django-allauth registraion settings ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS =1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = False LOGIN_REDIRECT_URL = '/' # Or whatever you want to redirect to after email verification # 1 day ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('testingland.urls')), path('api/', include('api.urls')), #all_auth_package url(r'^accounts/', include('allauth.urls')), ] -
How to enable image uploading option to django-ckeditor in forms.py
I am working with django-ckeditor for creating rich text editor for my django app. I have enabled image upload option in admin panel for ckeditor. But I can not enable image upload option in forms.py Here is the code: In settings.py: INSTALLED_APPS = [ ... # ckeditor 'ckeditor', 'ckeditor_uploader', ] # ckeditor Settings CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', }, } CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' In models.py: from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): ... content = RichTextUploadingField(verbose_name='Post Content') With this I can see the image upload option in the Admin Panel: This is the code in forms.py: from Blog import models from ckeditor_uploader.widgets import CKEditorUploadingWidget class PostForm(forms.ModelForm): content = forms.CharField(widget=CKEditorUploadingWidget()) # This widget not enabling upload option in templates class Meta: model = models.Post fields = ['content', ] In the template.html: {{ forms.media }} {{ forms|crispy }} But the above code doesn't enabling upload option in template. It is showing like this: How can I enable upload option in forms? Thanks -
TypeError: '>=' not supported between instances of 'str' and 'int' error happening while Django wagtail querying
Working fine from django templates but from postman it's giving this error. The main query is given below - query = reduce( or_, ( Q(path__startswith=page.path) & Q(depth=page.depth + 1) & Q(primary_category__in=list_categories) | Q(additional_categories__category__in=list_categories) for page in BlogPage.objects.filter(pk__in=blog_ids) ) ) -
How to display an image from the DB using folium
I'm trying to pull out an image inside the DB that's on my computer. And display it inside the folium object popup. I searched the internet but did not find a solution I would be happy to help def search_on_map(request): loc_list = [] img_list = [] for i in Add_Item.objects.all(): city = str(i.city) street = str(i.street) home = str(i.home_number) loc_list.append(city +" "+ street +" "+ home) img = i.header_img img_list.append(img) geolocator = Nominatim(user_agent="Your_Name") m = folium.Map(width=800, height=500, location=['32.078225', '34.768516'], zoom_start=15) for index, place in enumerate(loc_list): try: loc = loc_list[index] location = geolocator.geocode(loc) lat = location.latitude long =location.longitude # Add Marker folium.Marker([lat,long], tooltip= ,popup=img_list[index] , icon=folium.Icon(color='purple')).add_to(m) except Exception as e: print(e) return render(request, 'search_on_map.html', {"loc":m._repr_html_(),}) -
How to dynamically define and generate serializers in django
I am working on an event driven service which receives a lot of events and these events have payload. I want to validate all payloads with serializers. Since the events types and huge in numbers, I don't want to define serializers in code for every event as that would require a new release every time a new event is added or an existing one is changed. So, is there a way I can define these serializers dynamically for each event in a table instead of code and use it to validate the event payload ? Any new additions/changes can be done in the table itself. -
link MCO number to Reception number
I have a web page where the user is supposed to enter the reception number and the MCO number, so whatever reception number and MCO number is enter, it is supposed to be tag together like reception number: 123 and MCO number: 456, in the database it is supposed to show 123/456, how do I make it do that? This is how my webpage looks like (when the user click the submit button the reception number and the mco number will be tag together: But as shown in the picture below, the mco number will appear in another new row and not next to the reception number. views.py @login_required() def verifydetails(request): if request.method == 'POST': form = verifyForm(request.POST) if form.is_valid(): Datetime = datetime.now() status = 'Launching' mcoNum = form.cleaned_data['mcoNum'] if Photo.objects.filter(reception=form.cleaned_data['reception']): form = Photo(Datetime=Datetime, mcoNum=mcoNum, status=status) form.save() return redirect('ViewMCO') else: messages.success(request, 'The reception number you have enter is incorrect') return redirect('verifydetails') else: form = verifyForm() return render(request, 'verifydetails.html', {'form': form, }) forms.py class verifyForm(forms.Form): reception = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter Reception number'})) mcoNum = forms.CharField(label='', widget=forms.TextInput(attrs={"class": 'form-control', 'Placeholder': 'Enter MCO Number'})) class Meta: model = Photo fields = ("mcoNum", "status") ViewMCO.html {% extends "customerbase.html" %} {% block content … -
Django: Approach on how to realize IPC with other server/process
I have a Django App for user interaction which works perfectly fine. Now I want to have a communication channel with another primitive server a colleague of mine wrote. Probably will go for multiprocessing listeners via AF_UNIX. I don't know where to open a process that listens on the other servers messages and adds information to the database (also, I request information from the server but that shouldn't be much of a problem once the channel is open) Upon searching the web I found the suggestion to add a new command to the manage.py but I couldn't find out if I can execute two commands in parallel, also the GUI won't be executed as development server forever. If you have any suggestions on what tricks/technology/terms I should search for, I really appreciate the help! Still kind of a newbie to Django, so I might have missed something essential. -
How to add or remove objects in nested serializers Django using update function
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them. While updating the modules field using a put request, I don't want to update any rooms in it, I just want to add/remove rooms in the module. Here are my files - module/models.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() rooms = models.ManyToManyField(Rooms) rooms/models.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) is_deleted = models.BooleanField(default=False) module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(read_only=True, many=True) class Meta: model = Module fields = "__all__" def create(self, validated_data): rooms_data = validated_data.pop('rooms') module = Module.objects.create(**validated_data) for data in rooms_data: room, created = Rooms.objects.get_or_create(**data) module.rooms.add(room) return module rooms/serialier.py - class RoomSerializerWrite(serializers.ModelSerializer): room_id = serializers.IntegerField() class Meta: model = Rooms fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): module_serializer = ModuleSerializer(data=request.data) if module_serializer.is_valid(): module_serializer.save() return Response(module_serializer.data['module_id'], status = status.HTTP_201_CREATED) return Response(module_serializer.errors, status = status.HTTP_400_BAD_REQUEST) POST request body for updating a module in POSTMAN - { "module_id": 2, "rooms": [ { "room_id": 2, "title": "4", "desc": "22", "level": "2", … -
Django Rest Framework - Masking response values
I was wondering what the best way would be to mask a certain response parts. I will use an example to explain. Let's say I have a Person model with first_name, last_name and email. I use PersonSerializer to return that data. An example response can be { "first_name": "John", "last_name": "Doe", "email": "johndoe@gmail.com" } I want to "hide" an email when presenting it as response. I still want it to be present as the key, I just want to mask the value. So I want to achieve this response { "first_name": "John", "last_name": "Doe", "email": "__MSK__" // so it get's masked } So this should not impact the serialization when creating a new patient with same serializer class as well. Anyone has idea what the best way would be? Maybe overriding to_representation method or? -
Django: filter the logs which are coming from the front end
I had implemented the logging in my Django project, at Debug level. There is a whole lot of information coming to logger which make my system hang up. I want to filter the logs before going to save the logs. there are like useless logs that are unnecessarily getting saved to file. Like i have front end information from templates, i don't want frontend logs saved in the logger file. LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR + '/logs/debug.log'), 'formatter': 'verbose' }, 'info': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR + '/logs/info.log'), 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers': ['file','info','console'], 'level': 'DEBUG', 'propagate': True, }, }, } Kindly Suggest -
can't connect to my database which i have in hiox india wit my django
just a week we brought a hosting service in hioxindia ,they provided the databaseso i'm trying to connect my django with that database but i can't.i'm seeking solutions for that .I need to know how to connect my django with that database -
Django REST framework on primary key
I am currently trying to display multiple models with a primary key to find that specific data but I am encounter the following error: selected() got an unexpected keyword argument 'pk' Heres the code: views.py from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import DeviceSerializers, DeviceDetailSerializers @api_view(['GET']) def selected(request,pk): devices = Device.objects.all(pk=pk) devicedetail = DeviceDetail.objects.all(DD2DKEY=pk) devserializer = DeviceSerializers(devices, many = True) devdserializer = DeviceDetailSerializers(devicedetail, many = True) results = devserializer.data + devdserializer.data return Response(results) serializers.py from rest_framework import serializers from .models import Device, DeviceDetail class DeviceSerializers(serializers.ModelSerializer): class Meta: model=Device fields = '__all__' class DeviceDetailSerializers(serializers.ModelSerializer): class Meta: model = DeviceDetail fields = '__all__' models.py SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname urls.py (In app) from django.urls import path from .views import DeviceListView from . import views from .views … -
Django - Have function inside of a view function automatically return a response to user if error?
So I have this post request below that gets a video upload then validates it. I'd ideally like validate_video_upload() to return a 400 response if the video is larger than the allowed size rather than raise a validation error, because I'd like to notify the user that the video is too large. How do I set it up so that if validate_video_upload() returns a Response, it'll just return the call with the status and message, if there's no response returned then it just proceeds normally? View.py def post(self, request): if 'video' in request.FILES.keys(): vid = request.FILES.get('video') validate_video_upload(vid) function.py def validate_video_upload(file): if not is_valid_file_of_format(file._name, VALID_VIDEO_EXTENSIONS): raise ValidationError("Video file format is invalid") if file.size>2296000000: raise ValidationError("Maximum size allowed for a video is 287 mb") -
Invoking Django-river manually for workflow management
Our application uses Django_river for workflow management. And currently, the river is being invoked based on the post save signal created by Django. But for performance-related issues, we had to use the bulk option for inserting data that does not support signals by default. We have generated signals manually, but this is slowing down our system. Is there any way to manually invoke the river from our code based on the business conditions? -
Django apps communication in abstraction layer
We are starting a new Django project which will consist of many different applications inside it. At first I was thinking of looking at some of these applications as individual services but department heads told us that at this stage we do not need scaling, distributing and balancing, so just keep them inside the same project. However, I was also asked to keep my design clean and move application communications into an abstract layer. So the idea is to have a well defined interface for each service (django apps), and in order for services to talk to each other they will read the implementation of these interfaces from a factory and call the methods. All sounded good to me till I was starting to implement this. I was told that one day we may extract these django apps and put them in a different project and run them in multiple machines so we can distribute and balance the load between them. So I have had to find an implementation of the "well defined interface" which would be very easy to change when applications get extracted from the project. Approach A I could not come up with a lot of ideas … -
Check if Many to Many exists in django?
I have two models, Model University: name = models.CharField(max_length=120) Model Students: name = models.CharField(max_length=120) wishlist = models.ManyToManyField(University, blank=True) Basically this is wishlist, user can add university to their wishlist and if the reclick on the heart icon i need to remove the wishlist: Here is my code: student = request.user.student university = University.objects.get(id=pk) if university.student_set.exists(): student.wishlist.remove(university) else: student.wishlist.add(university) So when, user1 added university1 to wishlist, then user2 couldnt able to add university1 to the wishlist, i dont know where is the mistake !Pleas guide, any students can add any university to their wishlist (its the requirement) I think the problem is with the if statment -
how to make paginations to this views
I can't do pagination to this get request! Can anyone help me ps Django Rest framework @api_view(["GET"]) def school_titul_list(request): if request.method == 'GET': try: data = {} user = request.user schools = user_utils.user_schools(user) data['warning'] = False if user.is_superuser: snippets = models.SchoolTitulHead.objects.filter(school__nash=True) if 'school' in request.query_params: snippets = snippets.filter(school_id__in=request.query_params['school'].split(',')) else: snippets = snippets.filter(school_id__in=[]) else: snippets = models.SchoolTitulHead.objects.filter(school__in=schools.values_list('school', flat=True), deleted=False) snippets = snippets.order_by('deleted', '-year', 'klass', 'liter_id').select_related('school', 'kurator', 'kurator__portfolio') work_places = p_models.PortfolioWorkTimeLine.objects.filter(current=True, portfolio__deleted=False, deleted=False, checked=True, ) # if not request.user.is_superuser: work_places = work_places.filter(school__in=schools.values_list('school', flat=True)) work_places = work_places.values_list('portfolio', flat=True) portfolios = p_models.Portfolio.objects.filter(pk__in=work_places).distinct().order_by('name_ru') data['users'] = serializers.PortfolioSerializers(portfolios, many=True).data data['liters'] = serializers.LiterSerializers(Liter.objects.filter(deleted=False), many=True).data data['data'] = serializers.GetHeadSchoolTitulSerializer(snippets, many=True).data data['languages'] = serializers.LanguageSerializer(p_models.Language.objects.filter(deleted=False), many=True).data data['studyDirections'] = serializers.StudyDirectionsSerializer( StudyDirections.objects.filter(deleted=False), many=True).data data['klasss'] = serializers.KlassSerializersID(p_models.Klass.objects.filter(deleted=False, klass_type=2), many=True).data data['datas'] = serializers.DateObjectsSerializer( p_models.DateObjects.objects.filter(deleted=False, id=9).order_by('id'), many=True).data return JsonResponse(data) except AccessToEdit.DoesNotExist: return JsonResponse({'errors': 'Нет доступа', 'warning': 0}, status=400) I can't do pagination to this views! Can anyone help me psI can't do pagination to this views! Can anyone help me psI can't do pagination to this views! Can anyone help me psI can't do pagination to this views! Can anyone help me psI can't do pagination to this views! Can anyone help me ps -
How can I integrate google calendar in django?
I am creating schedule management website and I want to show the user calendar in my website. If any user login into website, I would like to ask a permission to access the google calendar. my website does not have authentication using google and I am using MySql to store all the user information. if Any user edit the calendar and users google calendar will be updated. How will I achieve this. -
display picutre in grid layout djang-admin
first, I am having issues with displaying thumbnails in Django-admin, I tried the code below but it is not working it seems, class Pictures(models.Model): image = models.ImageField(null=True) date_added = models.DateField(auto_now_add=True) organization = models.ForeignKey(Organisation,on_delete=models.CASCADE) def __unicode__(self): return f"{self}" @mark_safe def image_img(self): if self.image: return format_html('<img src="{0}" style="width: 60px; height:65px;" />'.format(self.image.url)) else: return format_html('<img src="" alt={0} style="width: 60px; height:65px;" />'.format("noimagefound")) image_img.short_description = 'Image' image_img.allow_tags = True class PicturesAdmin(admin.ModelAdmin): list_display = ('image', 'date_added','image_img') autocomplete_fields = ['organization'] list_display_links = ('date_added',) I also want to display these thumbnails in the grid layout, how can I achieve that any simple approach -
Django filter ListViews
I am still rookie.. This is my first experience with CBV. My goal is to create one template with list that i can filter by my models field, like Date, Category, and more. My first try was to create more than one ListView, each for category but it's just doesn't look and feel right and I can't find anything to solve that on Google or django documentation.. What am I missing? This is the code: class TaskListView(ListView): context_object_name='list' model=models.Task_app class TaskWorkListView(ListView): context_object_name='work' template_name='Tasks/Task_app_work.html' model=models.Task_app def get_queryset(self): return Task_app.objects.filter(Q(Category__exact='Work')) template: <table class="table"> <tr> <th scope="col">Task:</th> <th scope="col">Content: </th> <th scope="col">Hour:</th> </tr> {% for task in list %} <tr> <td scope="row"><a href="{{ task.id }}">{{task.Task_Name}}</a></td> <td scope="row">{{task.Content}}</td> <td scope="row">{{task.Start_Time|time:"G:i"}}</td> </tr> {% endfor %} </table>``` Thanks