Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't Assign Tags To Correct Post Through Serialization Using Django Rest Framework
I'm trying to serialize a Tag model for my DRF (Django Rest Framework) project - but somehow I couldn't assign tags to a specific post's title when sending JSON to the API's endpoint. Instead of seeing the correct post title designated with the proper tags, I see this: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "tag id": "9", "post title": "No post title found!", "slug": "test-999", "post id": [], "tag": "test 999" } ] My tag model: class PostTag(models.Model): tag = models.CharField(max_length=50, blank=True) slug = models.SlugField(max_length=255, unique=True) posts = models.ManyToManyField(Post, related_name='post_tag', through='role') def __str__(self): return self.tag My serializers.py: class TagsieSerializer(serializers.ModelSerializer): # posts = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = PostTag fields = '__all__' def to_representation(self, instance): """ Customizing how serialization of each tag should be displayed. This is possible due to overriding to_representation method. :param instance: :return: """ data = super(TagsieSerializer, self).to_representation(instance) for val in [data]: tag_id = str(val['id']) tag = val['tag'] slug = val['slug'] post_id = val['posts'] post_title_list = [] new_post_title_list = [] try: # Getting post title - but for some strange reason ValueError occurs and yet result returns # fine if I catch it and append it inside a list. … -
AssertionError: 200 != 302. Trying to test a redirect from a successful form entry
I'm trying to test redirect from a form using POST. I'm following the mdn web doc tutorial for Django and thought I would see if I could do some of my own test which are not in the tutorial. I'm try to test the book creation form in the tutorial to see if it redirects to book details page which it should do automatically because it's a class based generic view. It works correctly when I test locally but I cannot get the testcase to pass. Thanks for the help in advance. This is the error: > ===================================================================== FAIL: test_redirects_to_book_details_on_success (catalog.tests.test_views.BookCreateView) > ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\makor\mypythonscripts\django_projects\locallibrary\catalog\tests\test_views.py", line 399, in test_redirects_to_book_details_on_success self.assertRedirects(response, reverse('book-detail', kwargs={'pk': 1})) File "C:\Users\makor\mypythonscripts\django_projects\venv\lib\site-packages\django\test\testcases.py", line 512, in assertRedirects self.assertEqual( AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302) ---------------------------------------------------------------------- Ran 1 test in 0.341s FAILED (failures=1) Destroying test database for alias 'default'... models.py from django.db import models from django.urls import reverse # Used to generate URLs by reversing the URL pattern. from django.contrib.auth.models import User from datetime import date import uuid # Required for unique book instances class Genre(models.Model): """Model representing book genre.""" name = models.CharField(max_length=200, help_text='Enter … -
Get Absolute URL of image using django-treebeard tree responce
Hello currently i implemanted django-treebeard package for archive tree struture for categories. Here i faced problem in responce with URL of image. i can't see Absolute URL of image categories NOTE - Serializer not working with this recursive tree structure. I already know that you can pass context = {'request':request} in serializer but in my case, it's not working because it is recursive tree structure. views.py class CategoryAPI(APIView): def get(self, request): try: if CategoryModel.objects.count() > 0: categories = CategoryModel.dump_bulk() # serializer = CategorySerializer(instance=categories, many=True) # print(serializer) return Response({"status":True,"categories":categories}, status=status.HTTP_200_OK) else: return Response({'message': 'Categories not found.'}, status=status.HTTP_200_OK) except Exception as e: return Response({'error':str(e)}) APi GET Responce is like this { "status": true, "categories": [ { "data": { "name": "Fruits", "image": "Categories/download_3_Vg6Rv37.jfif" }, "id": 1, "children": [ { "data": { "name": "Apple", "image": "Categories/download_6zbqDvn.jfif" }, "id": 2, "children": [ { "data": { "name": "Green Kasmiri Apple", "image": "Categories/download_2_HaMCXyc.jfif" }, "id": 10 } ] }, { "data": { "name": "Banana", "image": "Categories/download_4_Mn5h9nL.jfif" }, "id": 3 }, { "data": { "name": "Mango", "image": "Categories/download_5_4RkBFcS.jfif" }, "id": 5 }, { "data": { "name": "Orange", "image": "Categories/download_6_vWVEQgm.jfif" }, "id": 4 } ] }, { "data": { "name": "Health", "image": "Categories/images_fwp1mBB.jfif" }, "id": 6 } ] } … -
How do i get the file path from the string
''' txt=r""" AuthorizedCDFPrefix : Comments : Contact : Symantec Corporation DisplayVersion : 7.7.2 HelpLink : http://www.symantec.com/business/support HelpTelephone : 800-342-0652 InstallDate : 20161026 InstallLocation : C:\Program Files\Veritas\ InstallSource : C:\Users\xemukblbexsrv\Desktop\x64\ ModifyPath : "C:\Windows\Installer\{AE93F96C-24C5-4270-AB93-021CA3BD19 9E}\Setup.exe" Publisher : Symantec Corporation Readme : Size : EstimatedSize : 517996 UninstallString : "C:\Windows\Installer\{AE93F96C-24C5-4270-AB93-021CA3BD19 9E}\Setup.exe" -u URLInfoAbout : http://www.symantec.com URLUpdateInfo : http://www.symantec.com/business/support VersionMajor : 7 VersionMinor : 7 WindowsInstaller : 0 Version : 117899266 Language : 1033 DisplayName : Symantec NetBackup Client NoModify : 0 NoRemove : 0 NoRepair : 0 DisplayIcon : "C:\Windows\Installer\{AE93F96C-24C5-4270-AB93-021CA3BD19 9E}\NB_ARP_ICON" PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SO FTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Symante c NetBackup Client PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SO FTWARE\Microsoft\Windows\CurrentVersion\Uninstall PSChildName : Symantec NetBackup Client PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry """ import re pattern = 'DisplayVersion[\s]+:\s(.*)' pattern1 = 'UninstallString[\s]+:\s(.*)\w+' result1 = re.findall(pattern1, txt)[0] print(result1) ''' Need output like this UninstallString : "C:\Windows\Installer{AE93F96C-24C5-4270-AB93-021CA3BD199E}\Setup.exe" -u But i am getting like this "C:\Windows\Installer{AE93F96C-24C5-4270-AB93-021CA3BD1" Not getting entaire line beacause remaining string will be in next line Some one can help in this @python -
Boolean 'Complete' field in my form is not working from UpdateView in Django
This is the code that I have written. I am facing an issue in implementing the boolean checkbox functionality from UpdateView in Django. When I write complete.save() in below code, I am getting the desired result, but the command 'complete.save()' is getting printed on the form. {% extends 'baseapp/main.html' %} {% block content %} <div class="body"> <h3 class="header-bar" id="add-header">Add Your Task</h3> <form method="POST" action=""> {%csrf_token%} <!--This is used to protect forgery requets--> {{form.as_p}} complete.save() <input class="search-button" type="submit" value="Submit"> <a id="cancel-icon" href="{% url 'tasks' %}"> Cancel</a> <!--If we don't want to create an item--> </form> </div> {% endblock content %} Output of the above code: But, if I do not write it, the checkbox functionality doesn't work. And I redirected to the previous page. Can someone please help me out with this? I am trying to implement the boolean field in UpdateView of Django. -
Pytest with django celery
I have celery task which create models entries in database. Celery uses Redis as a broker. Celery config in settings.py: CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'django-db' from .models import Message @shared_task(ignore_result=True) def create_entries(data: list): batch_size = 100 obj_iterator = (Message(**obj) for obj in data) while True: batch = list(islice(obj_iterator, batch_size)) if not batch: break Message.objects.bulk_create(batch, batch_size) In application everything works fine, but tests don't work. Test method code: @pytest.mark.django_db @pytest.mark.celery def test_create_entries(): message_data = [ { text: 'hello bro', client: 'Nick' }, ] assert Message.objects.count() == 0 task = tasks.create_model_entries.delay(message_data) result = AsyncResult(task.task_id) assert result.status == 'SUCCESS' # here is a fail, status = PENDING assert Message.objects.count() == 1 # here is a fail, count = 0 But if run server: python manage.py runserver and run tasks, then entries are created successfully. What could be the reason that tasks don't work in tests? -
Django not recognizing app_label meta data
Problem I have multiple DBs to connect to for different apps on my django server, which only serves datas from the DB. I recently added new DB and ran python3 manage.py inspectdb --database=new_db, then I added app_label for correct DB connection. But somehow django is keep returning programming error with invalid object name error. I double checked, and DB and tables are exactly there. Then I found out that model was trying to connect to its default database, which doesn't have table I am trying to connect to. What should I try to fix this? Summaries django model is trying to connect to its default DB, inspite it has explicitly declared target DB on its Meta part. DB declaration seems to be fine, because inspectdb was done perfectly. There's no typo on db declaration, too. <DB declaration on 'settings.py'> DATABASES = { 'default' : { 'ENGINE' : 'mssql', 'NAME' : 'DEFAULT_DB', 'USER' : env('DB_USER'), 'PASSWORD' : env('DB_PASSWORD'), 'HOST' : env('DB_HOST'), 'PORT' : env('DB_PORT'), }, 'new_db' : { 'ENGINE' : 'mssql', 'NAME' : 'NEW_DB', 'USER' : env('DB_USER'), 'PASSWORD' : env('DB_PASSWORD'), 'HOST' : env('DB_HOST'), 'PORT' : env('DB_PORT'), } } <Meta data of 'models.py'> class Meta: managed = False app_label='new_db' db_table='NEW_TB' -
pythonanywhere - issues with JavaScript files loading in admin console
having issues with js files loding in the admin console, hindering the activities of the admin console. Errors attached. enter image description here enter image description here Tried entering the static file path under the static section on the pythonanywhere. enter image description here home/<username>/<name of the app>/static/js -
How can I get multiple values from a form where each row has the same name attribute for their columns?
I'm rendering a form in Django that is essentially an Excel spreadsheet. Thousands of rows are being dynamically rendered with data from a table in my database, with each having the same number of columns and each column having the same name attribute for their inputs. The idea of the screen is to have a user be able to edit the data in the table and save their changes. Given that each row has the same name attribute for their inputs, I'm running into a problem when trying to retrieve said updated data. Right now, I'm attempting to get all of the data for a particular column upon clicking save. def change(request): j = request.POST["ACCOUNT_NAME"] print(j) return redirect('/') I'm receiving a MultiValueDictKeyError. I have tried the following solution as well: def change(request): j = request.POST.getlist("ACCOUNT_NAME") print(j) return redirect('/') All that this prints to the console is an empty list. Anyone have any ideas on this? Or an easier solution that doesn't require multiple rows with the same name attribute for their input fields? -
page breaks do not work within section tags
I am making a project with django, html,css, and javascript and I am building a page with sections and scroll snapping. I am struggling to go down a line after my tag but before my tag within a section. when I tried using break tags nothing happens, even when I use multiple. My best guess is that the fact that I am trying to do it within a section tag. enter image description here <body> <div class = "nav"> <a href="#1">Home</a> <a href="#2">Education</a> <a href="#3">Projects</a> <a href="#4">Skills</a> <a href="#5">Experience</a> </div> <div class="scroll_container"> <section id = "1" class = "home_section"> <h1>Tyler Olson</h1> <img class="animate__animated animate__bounce" src="/static/down_arrow.png" alt="bouncing dodwn arrow" style="width:50px;height:50px;"> </section> ... </div> </body> My goal is to have the arrow repeatedly bouncing at the bottom center of the section but I am completely unable to move it down rn, I even tried modifying some css values to move the img tag but none of them did anything -
How to invoke the `next()` element constantly in another function?
I am not very well familiar with JS. I am looking for a method of generating NEXT () subsequent array elements, which will be part of the string for the next displayed images in my Django project. For that sake I built a generator in my JS file: function* indexGenerator() { let index = 1; while (index < 78) { yield index++; } if (index = 78) yield* indexGenerator(); }; ...and now I'm trying to figure out how to use it in another function where the goal is to implement next().value as a part of my string's path: var file = "<img src=\"slides/light_" + number.next().value + ".jpg\" />"; I tried several approaches that don't work. Among other things, this: setInterval(function animationslider() { var number = indexGenerator(); var file = "<img src=\"slides/light_" + number.next().value + ".jpg\" />"; document.getElementById("animation-slider").innerHTML = file; }, 5000); I thought that having setInterval() would yield the next element from my generator for each time interval. But it was a misconception. The overall idea is to have 77 images that will be changed every 5 sec having a generator as an engine. How to fix the function animationslider()? -
save check box to Boolean field in django
Hi trying to save checkbox value on submit. The form displays the value correct. When value is True is, its checked and when false its unchecked. However I just can't get it to save on POST. Something wrong with this line. "isa = Customer.objects.update(is_active=request.POST.get('is_active'))" views.py @login_required(login_url='login') def engine(request): eng= Player.objects.filter(customer=request.user.customer) isa= Customer.objects.filter(name=request.user.customer) if request.method == "POST": customer=request.user.customer isa = Customer.objects.update(is_active=request.POST.get('is_active')) return redirect('engine') context= {'eng': eng, 'isa': isa} return render(request, 'base/engine.html', context) engine.html {% csrf_token %} {% for k in isa %} <label>ON/OFF</label> <input type="checkbox" id="is_active" name="is_active" {% if k.is_active == 1 %} checked{% endif %}> <input type="submit" value="save" /> {% endfor %} </form> -
Bootsrap modal don't open
I have some doubts regarding the modal, which I have been using to see the data, my problem is that when it is inside the same HTML it opens the modal, when it is another HTML, it gives an error. urls.py path("modalview/<int:prescription_id>", views.modalview, name="modalview"), Main.html <table class="table table-striped table-bordered border-primary" id="patientTable" > <tbody> {% for appointment in appointments %} <tr> <td><p>Appointment Number: {{ appointment.id }}</p></td> </tr> <tr> <td><p>Doctor Name: {{ appointment.doctor }}</p></td> </tr> <tr> <td><p>Appointment Date: {{appointment.date}}, {{ appointment.time }}</p></td> </tr> {% endfor %} {% for prescription in prescriptions %} <tr> <td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-ajaxurl="{% url 'modalview' prescription.id }}"> Open modal </button></td> </tr> {% endfor %} </tbody> </table> view.py def modalview(request, prescription_id): prescription = Prescription.objects.get(id = prescription_id) context={ 'prescription': prescription } return render(request, "ClinicMan/modalview.html", context) modalview.html {% load static %} {% block body %} <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <div class="mb-3"> <label for="message-text" class="col-form-label"><p>Symptoms: {{ prescription.symptoms }}</p></label> </div> <div class="mb-3"> <label for="recipient-name" class="col-form-label"><p>Prescription: {{ prescription.prescription }}</p></label> </div> <div class="mb-3"> <label for="message-text" class="col-form-label"><p>Appointment Date: {{ prescription.date }}</p></label> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> … -
Django - Divide result of queryset by integer
I'm fairly new to Django and I'm a bit lost by this. I have this view that shows the sum of a decimal field (amount) grouped by the name of the foreign keys (accountplan): def projection(request): divider = int(date.today().strftime('%d')) qs = ManagerialRevenue.objects.values('accountplan__name').annotate(Sum('amount')) return render(request, 'app/pages/planning/projection.html', context={'qs': qs,}) I need to divide each annotated amount field in the qs variable by the divider variable. In the template i can loop trough the qs: {% for item in qs %} {{ item.accountplan__name }} {{ item.amount__sum }} {% endfor %} But when I try do divide the values adding this line in the view: result = qs / divider And loop in the template with: {% for item in result %} {{ item.accountplan__name }} {{ item.amount__sum }} {% endfor %} It shows me an unsupported operand type(s) for /: 'QuerySet' and 'int' error. I understand the error (or at least I think so), and tried to loop in the view like this: for result in qs: result / divider But I'm still getting the result as a dictionary and the same error as above, except that is 'dict' and 'int'. Is there a way to do this? Thanks! -
How to specify permissions of FileBasedCache files
I am using Django 3, Nginx, uWSGI My normal Django Web/HTTP server creates and reads various cache files using FileBasedCache under /var/tmp/django_cache/. So far, this all works great... Nginx and uwsgi run as the www-data user. So the various cache files and sub directories in the django_cache directory are owned by the the www-data user and group. However I also have another user: website, which is what I use to run various manage.py commands, and do things from cron, etc. The website user is in the www-data group, so normally, this has worked totally fine. My problem is now that I am writing a management script (which is run by the website user, not the www-data user) that needs to access some cached files which were created by the www-data user, and because Django creates those files as -rw------- 1 www-data www-data my website user isn't able to read them and it creates an Exception. I have tried: adding session optional pam_umask.so umask=0137 to the common-session and common-session-interactive pam config files. adding umask = 0137 to the site's uWSGI app configuration file I believe that both of these changes/settings "work" in that if I do a test to tell django … -
how do i configure cloudinary key on railway
i'm working on a django project that requires image upload & i'm using cloudinary to handle the image upload, on my local host everything is working perfectly but when i deploy to railway and try uploading image i get this err msg ValueError at /profile/create Must supply api_key Request Method: POST Request URL: http://job-connect-production.up.railway.app/profile/create Django Version: 3.2.8 Exception Type: ValueError Exception Value: Must supply api_key Exception Location: /opt/venv/lib/python3.8/site-packages/cloudinary/utils.py, line 573, in sign_request Python Executable: /opt/venv/bin/python and i've provide my api_key as an environment variable, please can anyone help out -
fetching on frontend is faster than backend database update, how to sync them up?
I am first sending a POST request to add a new position to table ORDER, and after that promise is completed it then sends a post request to a table ORDER_PRODUCT to associate the previous order with some products. The thing is, it happens too fast, and second POST returns an error If i split those two post requests and fire them up manually then its all good. Whats a good way of sorting this out? -
Python MySQL quit working on MacOS – please explain why not
Here's the problem (MacOS environment): ImportError: dlopen(/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so, 0x0002): Library not loaded: '@rpath/libmysqlclient.21.dylib' Reason: tried: '/usr/lib/libmysqlclient.21.dylib' (no such file) The problem, obviously, is @rpath. Previously, I had no problems with this. "It Just Worked.™" Therefore I do not understand the mechanism that has now gone wrong in this (MacOS ...) environment. The libmysqlclient.21.dylib file does exist, just not "here." So, howcum @rpath now finds the apparent value /usr/lib? In the MacOS environment, the "correct location" of MySQL "ought to be something like" /usr/local/mysql-X.Y.Z-osx10.11-x86_64/lib... and somehow the software at some layer is supposed to "know" that. Obviously, it doesn't. However, I guess my real question is that I guess I don't know how it is all supposed to work. -
How can I intergrate my django app to an alredy made database, probably from a PHP app
this is part of the database. The extention is .sql -- phpMyAdmin SQL Dump -- version 3.2.0.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: May 20, 2011 at 05:08 PM -- Server version: 5.1.36 -- PHP Version: 5.2.9-2 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `bincomphptest` -- -- -------------------------------------------------------- -- -- Table structure for table `agentname` -- DROP TABLE IF EXISTS `agentname`; CREATE TABLE IF NOT EXISTS `agentname` ( `name_id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(255) NOT NULL, `lastname` varchar(255) NOT NULL, `email` varchar(255) DEFAULT NULL, `phone` char(13) NOT NULL, `pollingunit_uniqueid` int(11) NOT NULL, PRIMARY KEY (`name_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; I was creating a new database on django with mysqlite but I think I'm inexperience and this maybe possible -
Django list_display does not work at reverse model
Django list_display does not work at reverse model, i want to list_display the title and the production company of two seperated but related tables. here ist my model.py class ProjectBaseModel(models.Model): title = models.CharField("Titel", max_length=100, blank=False, unique=True) former_title = models.CharField("ehemaliger Titel", max_length=100, blank=True) title_international = models.CharField( "Titel, international", max_length=100, blank=True, null=True, unique=True ) program_length = models.PositiveSmallIntegerField( verbose_name="Länge in Min.", blank=True, validators=[MaxValueValidator(300)] ) def __str__(self): return self.title class Meta: abstract = True ordering = ["title"] class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" verbose_name_plural = "Kinofilme" class ProjectCompanySet(models.Model): featurefilm = models.ForeignKey( FeatureFilm, on_delete=models.CASCADE, null=True, blank=True ) tv_movie = models.ForeignKey( TvMovie, on_delete=models.CASCADE, null=True, blank=True ) production_company = models.ForeignKey( CompanyOrBranch, related_name="production_company", verbose_name="Produktionsfirma", on_delete=models.SET_NULL, blank=True, null=True, ) My FeatureFilm table inherits from the ProjectBaseModel table. I want to display the FeatureFilm list in the django backend admin. In the list I want to show the appropriate name, but I also want to show the field production_company which is one row of the ProductionCompanySet table, which is a child table related to the FeatureFilm table. the production_company field ist a foreign key to the CompanyOrBranch Table. Here you can see this table: class CompanyOrBranch(CompanyBaseModel): name = models.CharField( "Firma oder Niederlassung", max_length=60, blank=False, ) and here is my … -
Heroku Django: Looking for wrong GDAL version on new Heroku-22 Stack
I am trying to upgrade from the Heroku-18 to Heroku-22 stack, for my Django web app. In order to use the new stack, I had to upgrade from Python 3.7.2 to Python 3.10.8. From what I've seen on Stack Overflow so far and other sources on the internet, I have already been installing GDAL/GIS the correct way for a Django app on Heroku. Which is to use a buildpack and have it ordered first in the list of buildpacks: remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Using buildpacks: remote: 1. https://github.com/heroku/heroku-geo-buildpack.git remote: 2. heroku/python I expected no issues on the upgrade, but now for some reason it's having trouble finding GDAL. These are the versions that are being installed: remote: -----> Geo Packages (GDAL/GEOS/PROJ) app detected remote: -----> Installing GDAL-2.4.0 remote: -----> Installing GEOS-3.7.2 remote: -----> Installing PROJ-5.2.0 And here is the error I'm getting. Notice that it is not looking for gdal2.4.0, which is what's installed. However, it is looking for gdal which I'd hope would be covered by this install. django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, … -
How to display images from a database row by row
I am trying to create a webpage where i am displaying images of animals as a gallery. I would like the gallery where images are displayed side by side in a row (3 images per row). I tried displaying the images from the database (model) side by side in rows but as a beginner i find this quite difficult and would like help with this. I am coding using the Django framework where the model (animal) contains the following fields: Image_Title, Image_Description, Image_Price. I understand the concept where i would have to loop the Animal objects but i am struggling to put 3 in a row. I am able to put one in a row but that is now what i am looking for. Code for views.py def gallery(request): images = Animal.objects.all() context = { 'images': images, } return render(request, 'AnimalGallery/gallery.html', context) Code for Animal model: class Animal(models.Model): Image = models.ImageField() Image_Title = models.CharField(max_length=50) Image_Description = models.CharField(max_length=500, blank=True) Image_Price = models.FloatField(null=True) def __str__(self): return self.Image_Title Code for the HTML(Displays one image per row): <table> {% for each in images %} <tr> <td>{{each.Image}} </td> <td>{{each.Image_Title}} </td> </tr> {% endfor %} </table> This is a website that has implemented the same concept … -
Django and Africa's Talking API
I am quite new to this and am trying to develop a software system in django which uses the Africa's Talking API for airtime and data topups. I would be very happy to find one who knows how to do this and could help me walk through how to do it. thanks in advance. -
.bg-img not loading on home.html
i've uploaded my live project to heroku, and ever since - the background image in the style.css folder doesn't seem to be working. (trying to showcase directory below) /nooz /nooz2 /static //css ///style.css //images /// background_image.jpg /// generic_pic.png /templates -- home.html settings.py INSTALLED_APPS = [ 'cloudinary_storage', 'django.contrib.staticfiles', 'cloudinary', ] STATIC_URL = 'static/' STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = 'media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') style.css .bg-img { background: url('static/images/background_image.jpg'); height: 550px; width: 100%; background-size: 100% 550px; } home.html <div class="container-fluid bg-img" title="Center Stage Background"></div> I tried the following: Changed pathing Change image collecstatic -
Admin Sorting after applying SimpleListFilter
I want a different ordering to be applied after a SimpleListFilter is being applied. class Store(models.Model): name = models.CharField("name", max_length = 128) state = models.IntegerField("state of store", default = 0) revenue = models.IntegerField("accumulated ...", default = 0) class StoreStateFilter(admin.SimpleListFilter): title = "filter by state" parameter_name = "state" def lookups(self, request, model_admin): return [("on", "on"), ("off", "off")] def queryset(self, request, queryset): ... return queryset The admin looks simple: @admin.register(Store) class StoreAdmin(admin.ModelAdmin): ordering = ["revenue", ...] list_filter = [StoreStateFilter, ...] ... So the normal ordering is after revenue, but after applying StoreStateFilter I want the ordering to be after name. Is there a way to achieve that?