Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why bootstrap carousel and django not workig properly?
I am trying to provide bootstrap carousel backend with django.I have written a simple program view which will pass all images to template.But when i run the program i did't get output as expected, all images are rendered adjecent to one other. There was nothing like forward and backward button and all.And i am posting my view and template. Thanks in advance. Hope to here from you soon. View:- def TaggingView(request): queryset = MyImage.objects.filter(is_tagged=False) return render(request, "taggging.html", {'files': queryset}) Template:- <body> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for file in files %} <div class="carousel-item active"> <img class="d-block w-100" src="{{file.image.url}}" alt="slides"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </body> -
Static files are not loading | Django
Static files are not loading and also does not shows any error. CODE -ADMIN settings.py STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR,"static") STATICFILES_DIRS = [ STATIC_DIR, ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('Welcome.urls')), path('auth/', include('Authentication.urls')), path('ad/', include('Ads.urls')), path('user/', include('UserDashboard.urls')), path('admin/', include('AdminDashboard.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) APPS template <link href="{% static 'css/user/style.css' %}" rel="stylesheet"> Console Console Dirs Structure Project Directory Structure CODE EXPLANATION Simply added static files in the root dir and tried to import them in template but css files are not loading but media files are successfully loaded like this media <link rel="shortcut icon" type="image/jpg" href="{% static 'img/logo.png' %}" />. In dir structure image we can see img and css folder at same place in static folder. -
Why is the Django API returning an empty array
I am developing a web application using Django but I am not getting the desired results, the Django API is return an empty array ([]). This is the serializer class I am trying to get the places data -> from rest_framework import serializers from . import models class PlaceSerializer(serializers.ModelSerializer): class Meta: model = models.Place fields = ('id', 'name', 'image') These are the views -> from rest_framework import generics from .import models, serializers # Create your views here. class PlaceList(generics.ListCreateAPIView): serializer_class = serializers.PlaceSerializer def get_queryset(self): return models.Place.objects.filter(owner_id=self.request.user.id) # Only the owner can create or make changes on the places def perform_create(self, serializer): serializer.save(owner=self.request.user) -
Store who updated Django Model from admin
I have a use case where data is only inserted and updated from django admin. Now, I have multiple users who have access to django admin page. I want to be able to store who exactly updated or created a record in django admin page. Ideally, I want to add a separate column to an existing model. models.py class Links(models.Model): link = models.URLField(unique=True) created_at = models.DateTimeField(auto_now_add=True) created_by = model.ForeignKey(UserModel) updated_at = models.DateTimeField(auto_now=True) updated_by = model.ForeignKey(UserModel) -
Hello everyone. Has anyone used paystack payment gateway for a subscription django project before?
I tried to create models for user to subscribe within my application but that is not the aim. The aim is to make request to paystack within the backend when ever the frontend want to make subscription. -
serializer.is_valid() returns 500 Internal server error
I am new to Django and have trouble making django-rest-framework API for post, inheriting APIView. I'm using a serializer, that inherits djangos ModelSerializer. I see 500 Internal server error whenever I try validating the serializer. color.js posts image using Django rest framework as follows. function PersonalColorScreen({navigation,route}) { const {image} = route.params; console.log('uri is', image.uri); const [userToken, setUserToken] = React.useState(route.params?.userToken); const requestHeaders = { headers: { "Content-Type": "multipart/form-data" } } // helper function: generate a new file from base64 String //convert base64 image data to file object to pass it onto imagefield of serializer. //otherwise, serializer outputs 500 Internal server error code const dataURLtoFile = (dataurl, filename) => { const arr = dataurl.split(',') const mime = arr[0].match(/:(.*?);/)[1] const bstr = atob(arr[1]) let n = bstr.length const u8arr = new Uint8Array(n) while (n) { u8arr[n - 1] = bstr.charCodeAt(n - 1) n -= 1 // to make eslint happy } return new File([u8arr], filename, { type: mime }) } //random number between 0-9 function getRandomInt(max) { return Math.floor(Math.random() * max); } // generate file from base64 string const file = dataURLtoFile(image.uri, `${getRandomInt(10)}.png`) const formData= new FormData(); formData.append('img',file,file.name); console.log(file.name); //axios post request to send data // axios.post('http://localhost:8000/accounts/personalcolor/', formData,requestHeaders) //multipartparser axios.post('http://localhost:8000/accounts/personalcolor/', formData, requestHeaders) .then(res … -
"Anonymoususer" error after success payment and when go to CallbackURL, Django
my request and verify views: from django.http import HttpResponse, request from django.shortcuts import redirect, get_object_or_404, render from zeep import Client from django.conf import settings from accounts.models import Profile from products.models import Product from pay.models import Order, OrderItem import datetime from django.core.mail import BadHeaderError, send_mail from django.template.loader import render_to_string from pay.views import get_user_pending_order MERCHANT = 'xxx...xxxx' client = Client('https://www.zarinpal.com/pg/services/WebGate/wsdl') amount = "" description = "" # Required email = "" # Optional mobile = "" # Optional CallbackURL = 'https://example.com/payment/verify/' def send_request(request): username = request.user amount = get_user_pending_order(request).get_total() + get_user_pending_order(request).transport.transport_price email = username.email # Optional mobile = username.profile.phone_number # Optional result = client.service.PaymentRequest(MERCHANT, amount, description, email, mobile, CallbackURL) order_to_purchase = get_user_pending_order(request) order_to_purchase.save() if result.Status == 100: return redirect('https://www.zarinpal.com/pg/StartPay/' + str(result.Authority)) else: return HttpResponse('Error code: ' + str(result.Status)) def verify(request): amount = get_user_pending_order(request).get_total() + get_user_pending_order(request).transport.transport_price if request.GET.get('Status') == 'OK': result = client.service.PaymentVerification(MERCHANT, request.GET['Authority'], amount) if result.Status == 100: user = request.user order_to_purchase = get_user_pending_order(request) order_to_purchase.is_ordered = True order_to_purchase.date_ordered=datetime.datetime.now() order_to_purchase.created_on_time=datetime.datetime.now() order_to_purchase.save() order_items = order_to_purchase.items.all() for order_item in order_items: order_item.product.quantity = order_item.product.quantity - 1 order_item.product.save() order_items.update(is_ordered=True, date_ordered=datetime.datetime.now()) subject = 'successful' c = { "refid":str(result.RefID), "ref_code":order_to_purchase.ref_code, "owner":order_to_purchase.owner, } email_template_name = "pay/after_pay_confirm_email.html" email_html = render_to_string(email_template_name, c) email_from = settings.EMAIL_HOST_USER send_mail(subject, email_html, email_from, [user.email], html_message=email_html) ctx = … -
every time i try to upload an image from django admin i get this error : "FOREIGN KEY constraint failed''
everytime i try to upload an for the first time ive set the default value to temporary but then i changed it to None and i still see the default=temporary in django admin I dont know what to do please help <3 and I dont know why the error refers to FOREIGN KEY while i only have 1 model this is my model.py : from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser, AbstractBaseUser, PermissionsMixin, BaseUserManager class customMemberManager(BaseUserManager): def create_user(self, email, mobileNumber, name, familyName, password, nationalCode, image, **other_fields): if not email: raise ValueError('YOU MUST ENTER VALID EMAIL') email = self.normalize_email(email) user = self.model(email=email, mobileNumber=mobileNumber, name=name, image=image, familyName=familyName, password=password, nationalCode=nationalCode, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, email, mobileNumber, name, familyName, image, password, nationalCode, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be is_staff set to True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be is_superuser set to True') return self.create_user(email, mobileNumber, name, familyName, password, nationalCode, image, **other_fields) class Members(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = 'Members' name = models.CharField(max_length=50) familyName = models.CharField(max_length=50) email = models.EmailField(max_length=50) nationalCode = models.IntegerField(null=True) mobileNumber = models.IntegerField(null=True, unique=True) image = models.ImageField(upload_to='register_image/', blank=True,default=None) is_staff = models.BooleanField(default=False) is_active … -
Datetimepicker MM/YYYY Format
I'm attempting to implement the datetimepicker with just monthly selection. I've done this, but upon selecting a month, I get an error that indicates 'Enter a valid date.' I'm assuming django doesn't like the format of the date (i.e. MM/YYYY) given the fact that it's looking for something to fit into a DateField. Here is my form. class MonthlyForm(forms.Form): start_month = forms.DateField(required=True) def __init__(self, *args, **kwargs): super(MonthlyForm, self).__init__(*args, **kwargs) self.fields['start_month'].widget = DatePickerInput( options={ "format": "MM/YYYY", # moment date-time format "showClose": False, "showClear": False, "showTodayButton": False, "useCurrent": True, "ignoreReadonly": True, "keepInvalid": True, }, attrs={'autocomplete':'off'} ) Any thoughts on how to get around this would be appreciated. Even if I can somehow bypass the normal form validation for this field would work. I can do the validation inside of def clean. Thanks! -
How to add Series and Episodes in Django Movies website?
I created movies website , now i want to create models where i can select Serial and then add Series and Episodes . Fore example , add Serial Vikings , and then i want to add Season 1 and Episodes 1. What is best idea ? This is my Models class Serial(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) images = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=30) status = models.CharField(choices=STATUS_CHOICES, max_length=100) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) def get_absolute_url(self): return reverse('post', kwargs={"post_slug_serial": self.slug}) def __str__(self): return self.title i think i need Django Many to many relationship , but how ? Can anyone help me ? what is best way to create this task? -
Django how to link Users to Usermodel
Hello I am pretty new to Django and don't get yet fundamental ideas of Users. I was able to create a registration page to create users which are shown on the admin page in the "Authentication and AUthorization -> Users". Now I want the users to logg in and create their profiles. They should add some additional information like name, bio, picture etc. Every user should be able to add and see its own profile. To do that I created a model: class Profile(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) bio = models.TextField() profile_pic = models.ImageField(upload_to="images/") def __str__(self): return self.firstname + ' | ' + self.lastname In my view and the html I am able to add these informations to the model. But HOW exactly can I relate this "Profile"-Model to the individual user? What do I miss here? -
how to pass the value of list indjango to method
I am trying to do something like this, I have a navigation bar with li items. **index.html** <ul class="submenu dropdown-menu"> <li><a class="dropdown-item" name="mis" href="{% url 'pdfNotes'%}">MIS</a></li> <li><a class="dropdown-item" href="{% url 'pdfNotes'%}">MA</a></li> <li><a class="dropdown-item" href="{% url 'pdfNotes'%}">UXD</a></li> <li><a class="dropdown-item" href="{% url 'pdfNotes'%}">OSS</a></li> </ul> here when I navigate to the first list '' i.e for MIS I have to redirect to pdfNotes.html with the name as 'mis' so that I can use this as a parameter in views.py to filter my data and display only 'MIS' details in pdf notes. same for all other li items. **pdfNotes.html** {% if pdfnote %} <table> <tr> <th># </th> <th>NAME</th> <th>DOWNLOAD FILE</th> </tr> {% with counter=1 %} {% for item in pdfnote %} {% with crs=item.course %} <tr> <td id="id">{{crs}}</td> <td id="id">{{pattn}}</td> <td id="id">{{sem}}</td> <td id="id">{{ forloop.counter}}</td> <td id="name">{{item.name}}</td> <td id="downloadBtn"> <a href="{{item.file.url}}" class="btn-outline-success" download >DOWNLOAD</a> </td> </tr> {% endwith %} {% endfor %} {% endwith %} </table> **model.pdf** class PDF_Notes(models.Model): name=models.CharField("File name",max_length=100) subject=models.CharField("Subject",max_length=50) course=models.CharField("Course",max_length=50) semester=models.CharField("Semister",max_length=50) year=models.CharField("Year",max_length=50) source=models.CharField("Source",max_length=100) file=models.FileField(upload_to="media/PdfNotes") def __str__(self): return self.name **view.py** def pdfNotes(request): pdfNotes_file=PDF_Notes.objects.all() #sub=request.GET[] if(request.GET['mis']): pdfNotes_file=PDF_Notes.objects.all().filter(subject="MIS") n=len(pdfNotes_file) print("hello",pdfNotes_file) params={'pdfnote':pdfNotes_file,'total_items':n} return render(request,'pdfNotes.html',params) how can I do that, please... Thanx!! -
AttributeError: module 'signal' has no attribute 'SIGHUP'
I am trying to deploy my Django app using the Apache2.4-Webserver. mod_wsgi has been installed in the project folder. When I try to run the command python manage.py runmodwsgi --reload-on-changes it returns the error: ***\mod_wsgi\server\management\commands\runmodwsgi.py", line 158, in handle signal.signal(signal.SIGHUP, handler) AttributeError: module 'signal' has no attribute 'SIGHUP'. How can I go about this? -
Django/HTML - HTML not showing complete string from the context, rather only part of it
I am working on a Django site. This site has a form with preview button. How I would like it to work: Text entered in the input field on HTML. Preview button pressed. Python script runs in background. Form to retain it's values. What I have done: So far I have managed to a create form, a preview button, run the script and return the values as context to HTML and show it on the form. However the problem is, if the string has spaces. Form only shows first section of the string rather than whole string. Example: If I enter name as "John Smith" and press preview button. Form only shows me "John". Same if I do "London, United Kingdom". It shows me "London," I have looked onto Google and stackoverflow but couldn't find a solution to this, hence thought to ask here. I would appreciate if someone can guide me on this. views.py ''' nname = request.POST['name'] django_run_script() context = {'name': nname} ''' index.html ''' <div class="form-group"> <label class="label" for="name">Full Name</label> <input type="text" class="form-control" name="name" id="name" placeholder="Name" required value={{ name|default:"" }}> </div> ''' Thank you, Kind regards, Shashank -
Django allauth and google recaptcha on login page - any good solutions?
I'm getting this error error Exception Value login() got an unexpected keyword argument 'redirect_url' Exception Location: \allauth\account\views.py, line 159, in form_valid I would have thought there were some good solutions out there, but none work for me, it seems outdated? I'm using django-allauth and django-recaptcha 2.0.6 The login page shows the google recaptcha, but I don't think it's working at all. When I type in an incorrect password it says that it's incorrect even when I don't check the box. I've tried putting {{ form.captcha }} in html and it doesn't show at all. When I do type in the correct password with or without checking the box I get the error above. There must be an easy solution? This is my code: forms.py from allauth.account.forms import LoginForm from captcha.fields import ReCaptchaField class MyCustomLoginForm(LoginForm): def login(self): captcha = ReCaptchaField() # You must return the original result. return super(MyCustomLoginForm, self).login(captcha) login.html <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="xxxx"></div> <button class="primaryAction" type="submit">{% trans "Sign … -
Django: Pass Model objects to context_processors
As a new developer to Django, I am running into an issue of trying to pass a model's object list to a global variable accessible on any template, within any app. settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(PROJECT_ROOT, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'myapp.site_context.site_context_processor', ], }, }, ] site_context.py from .apps.events.models import Event def site_context_processor(request): ctx = {} ctx['current_year'] = time.strftime("%Y") ctx['events'] = Event.objects.active()[0] return ctx I am running into an issue of an app_label missing on the Events model, but when I add this, I get conflicting apps in the settings.py Model class myapp.apps.events.models.Event doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. when settings.py looks like INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'directory', 'events', 'utilities', 'filebrowser', ] but when I add the app via myapp.apps.Events I get RuntimeError: Conflicting 'event' models in application 'events': <class 'events.models.Event'> and <class 'myapp.apps.events.models.Event'>. Not sure where to go from here. Any help would be greatly apperciated. -
How could I translate static data coming from JSon files in Django?
I have a json file with a long list of geographic locations [ { "id": 1, "name": "Afghanistan", "iso3": "AFG", "iso2": "AF", "phone_code": "93", "capital": "Kabul", "currency": "AFN", "currency_symbol": "؋", "tld": ".af", "native": "افغانستان", "region": "Asia", "subregion": "Southern Asia", "timezones": [ { "zoneName": "Asia\/Kabul", "gmtOffset": 16200, "gmtOffsetName": "UTC+04:30", "abbreviation": "AFT", "tzName": "Afghanistan Time" } ], "latitude": "33.00000000", "longitude": "65.00000000", "emoji": "🇦🇫", "emojiU": "U+1F1E6 U+1F1EB", "states": [ { "id": 3901, "name": "Badakhshan", "state_code": "BDS", "cities": [ { "id": 52, "name": "Ashkāsham", "latitude": "36.68333000", "longitude": "71.53333000" }, ....... /* very long list */ This file is loaded in Django forms when country/state/city dropdown lists are needed. The problem is that I want to translate at least the country names to other languages. Even if I was allowed to use {% trans "Country_name" %} in my JSon file it wouldn't be very practical. Is there a faster way to do so? For example making this in forms.py doesn't work: from django.utils.translation import gettext_lazy as _ # ... def get_country(): filepath = 'myproj/static/data/countries_states_cities.json' all_data = readJson(filepath) all_countries = [('----', _("--- Select a Country ---"))] for x in all_data: y = (x['name'], _(x['name'])) all_countries.append(y) return all_countries "--- Select a Country ---" will be translated but … -
Python Raw Recursive Query Convert
cursor.execute("WITH recursive subordinates AS (SELECT 1 as id FROM NODES WHERE node_id ='" + str(document_node_edit) + "' UNION ALL SELECT e.* FROM NODES e INNER JOIN subordinates s ON s.parent_node::text = e.node_id::text)SELECT s.short_code, s.node_type FROM subordinates s where s.location_id='" + str(location) + "' and s.node_type=1") -
How to create one to one field with Django for existing table?
We already have a model, let's say, Product. And we want to extend it into 'one to one relationship', let's say, ProductDetails. How do it in such way, that for each existing row of Product model row ProductDetails is created automatically? with some default vaules. Does Django provide such tool? The task seems pretty regular for me, but I can't find any native solution. -
How to customise message in send_mail in django
I'm trying to customise the message which I want to send to a gmail, like you may have seen some emails having nice layout, buttons and images. I want customise my message like that. But I'm not getting how to do it in django. Can anyone guide me how to do it? I'd appreciate some suggestions. Thank you. -
How do I fix AttributeError: type object 'Book' has no attribute 'published_objects' on django_3.2
I am trying to create a custom model manager by modifying an already existing queryset. After adding the custom manager to my models.py file, models.py from django.db import models from django.db.models.fields import DateField from django.utils import timezone, tree from django.contrib.auth.models import User class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Book(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) author = models.CharField(max_length=100) slug = models.SlugField( max_length=250, unique_for_date='uploaded_on') uploaded_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='book_posts') body = models.TextField() publish = models.DateField() uploaded_on = models.DateTimeField(default=timezone.now) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published_objects = PublishedManager() class Meta: ordering = ('-category', ) def __str__(self): return self.title``` If I use the python manage.py shell to test I was able to retrieve all books using Book.objects.all() >>> Book.objects.all() <QuerySet [<Book: 48 Laws of Power>, <Book: The China Card>, <Book: Rich Dad, Poor Dad>]>``` But when trying to retrieve using my custom model, the is my following result >>> Book.published_objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: type object 'Book' has no attribute 'published_objects'``` How do I fix this error please, since i was following the original Django Documentations? -
Does the sync_to_async decorator really make django requests faster?
asgiref module has sync_to_async and async_to_sync function and decorator. I want to know if using sync_to_async this decorator can really make django requests faster,code like this: @csrf_exempt @sync_to_async def get_data(request): user_obj_qs = User.objects.all() user_list = [{'name': user_obj.first_name} for user_obj in user_obj_qs] return JsonResponse(user_list, safe=False) -
How to implements DataTable in a Django Project?
I'm new in Django framework and I'm trying to implement datatable into my project. I read the documentation of Django and Datatables and implemented exactly as stated, but somehow the datatable does not showing in the template and I don't know why. home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Django Project</title> {% include 'headers.html' %} {% include 'scripts.html' %} </head> <body class="hold-transition sidebar-mini layout-fixed"> <div class="wrapper"> {% include 'header.html' %} {% include 'sidebar.html' %} <div class="content-wrapper"> <section class="content-header"></section> <section class="content"> {% block content %} {% endblock content %} </section> </div> {% block javascript %} {% endblock %} {% include 'footer.html' %} <aside class="control-sidebar control-sidebar-dark"></aside> </div> </body> </html> headers.html {% load static %} <!-- DataTables --> <link rel="stylesheet" href="{% static 'lib/bootstrap-5.1.1-dist/css/bootstrap.min.css' %}" /> <link href="{% static 'lib/datatables-1.11.2/css/jquery.dataTables.min.css' %}" /> <link rel="stylesheet" href="{% static 'lib/datatables-1.11.2/css/dataTables.bootstrap4.min.css' %}" /> <link rel="stylesheet" href="{% static 'lib/datatables-1.11.2/css/responsive.bootstrap4.min.css' %}" /> <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback" /> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'lib/adminlte-3.1.0/plugins/fontawesome-free/css/all.min.css' %}" /> <!-- overlayScrollbars --> <link rel="stylesheet" href="{% static 'lib/adminlte-3.1.0/plugins/overlayScrollbars/css/OverlayScrollbars.min.css' %}" /> <!-- Theme style --> <link rel="stylesheet" href="{% static 'lib/adminlte-3.1.0/css/adminlte.min.css' %}" /> scripts.html {% load static %} <script src="{% static … -
Limit number of images user can upload
I have a blog feature on my site, users can upload a single main image and multiple supporting images. The issue I am facing is I want to be able to limit the number of images a user can upload. I understand that I could use a for loop on it but if the user goes back later and adds more it would make the for loop useless. So I figured the best way to do this would be to add a field to the model that would count the number of images uploaded and then I can use an if statement to check if more than a said number of images have been uploaded. How would i go about getting the number of images and adding them to the post while it is being created. Or should I go about this a different way view @login_required def createPostView(request): currentUser = request.user postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post_id = PostFormID.id instance.images = f instance.save() return HttpResponseRedirect("/") return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) -
Setting up gdal/osgeo Python library on Heroku
On my Windows machine, I have set up GDAL by following these instructions: downloading a wheel from Chris Gohkle's website and installing it using pip. pip install "C:/Users/andre/Downloads/GDAL-3.3.2-cp39-cp39-win_amd64.whl" This then gives me access to gdal like so: from osgeo import gdal How can I now re-create this for my Django App on Heroku? I have already followed the official Heroku instructions on installing GDAL with a buildpack. Although this is successful, I don't know how to install the osgeo library (and its gdal sub-module) on the remote Heroku machine.