Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Call a function to update queryset on django-filter Choicefielter
I have a working function that populates a dropdown with the emails of all registered tutors. The problem is that when a new Tutor is registered, it gets redirected to the home template (where the form filter is rendered), but the dropdown with the choices is not updated, even if I hit refresh. It gets updated after in VisualStudio I stop the server and run again runserver, or press ctrl + s and the server is reloaded. I figured out that the function get_tutores() is only called once, and what I want to achieve is to call that function from the views every time the page is reloaded. MODEL class Tutor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) nombre = models.CharField(max_length=50, blank=False, null=True) apellido = models.CharField(max_length=50, blank=False, null=True) biografia = models.TextField() curriculum = models.FileField(upload_to="curriculums/", blank=True, null=True) foto = models.ImageField(blank=True, null=True) carrera = models.ManyToManyField(Carrera, blank=True) linea_invest = models.ManyToManyField(Linea_Invest, blank=True) correo = models.EmailField(blank=True, null=True) numero_celular = models.CharField(max_length=20, blank=True, null=True) class Meta: verbose_name_plural = "Tutores" verbose_name = "Tutor" def __str__(self): return '%s %s' % (self.nombre, self.apellido) FILTER: def get_tutores(): tutores = [] for tut in Tutor.objects.all(): tutores.append((tut.user.id,tut.user.email,)) return tutores class TutorFilter(django_filters.FilterSet): nombre = CharFilter(field_name="nombre", label="Nombre",lookup_expr='icontains') apellido = CharFilter(field_name="apellido", label="Apellido",lookup_expr='icontains') carrera = ModelMultipleChoiceFilter(field_name= "carrera", queryset= … -
Django and format_html, getting duplicate text formatted and unformatted
I'm using Django 3 for a simple Book loan app. I'm trying to format the text (change color) using format_html but I get strange results. I've the following class declaration: class Prestamos(models.Model): estado_prestamo = models.CharField(max_length=10, verbose_name='Estado', choices=STATUS_CHOICES) STATUS_CHOICES = ( ('a', format_html('<font color="green">Activo</font>')), ('b', "Archivado"), ('w', format_html('<font color="red"><b>Vencido</b></font>')), ) This is the result in Filter Panel where I get duplicate text, formatted and unformatted. Thanks in advance. PD: Here is the ModelAdmin declaration (thanks Iain): class PrestamosAdmin(admin.ModelAdmin): list_display = ('nombre_prestamo', 'correo_prestamo', 'fecha_alta', 'duracion', 'Material_en_préstamo', 'estado_prestamo', 'Ver_mat',) search_fields = ('numero_prestamo','nombre_prestamo', 'correo_prestamo', 'fecha_alta', 'duracion', 'material__num_com') list_filter = ('estado_prestamo', 'fecha_alta', 'fecha_baja') actions = ['archivar_prestamo','ImprimirPrestamo'] -
How do I make use of Django-Registration-Redux?
I have read the docs of this application but I am unable to create a login page for my website. -
why my added layers are not displayed by leaflet.ajax.js
I am developing a web map app using django, leaflet and postgis. My web app could display the OSM (openstreetmap) as background map but my added layer (from QGIS) and point data model (constructed in geodjango) could not be displayed in the web app. please give me a help. [Ofcourse I can see the text format (as json) in my added layer as follows: https://i.stack.imgur.com/qYnWe.jpg The code of index.html: <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <title>Service Maps for Tourism</title> <style type="text/css"> #gis {width: 80%; height: 800px;} </style> <script type="text/javascript" src= "{% static 'dist/leaflet.ajax.js' %}"> </script> </head> <body> <h1> سامانه نقشه گردشگری</h1> <br/> <script type="text/javascript"> function our_layers(map,options){ var datasets = new L.GeoJSON.AJAX("{% url 'name' %}",{ }); datasets.addTo(map); } </script> {% leaflet_map "gis" callback="window.our_Layers" %} </body> </html> The views.py is as follows: from django.shortcuts import render from django.views.generic import TemplateView from django.core.serializers import serialize from django.http import HttpResponse from .models import Provinces # Create your views here. class HomePageView(TemplateView): template_name= 'index.html' def province_dataSets (request): provinces= serialize('geojson', Provinces.objects.all()) return HttpResponse(provinces, content_type= 'json') The models.py is as follows: from __future__ import unicode_literals from django.db import models from django.contrib.gis.db import models from django.db.models … -
Associate child object with parent object per instance in Django?
I've got two models, an Invoice model and an Expense model. Upon creating invoices, the user should be able to add all expenses for an invoice. Once an invoice has been created - these expenses should somehow be "checked" so a new invoice doesn't add the same expenses. I'd need some form of check on the expense instance saying "has been invoiced" or something. Not entirely sure how to proceed with only a ..set.filter(...) queryset My two models looks like this: Expense model class Expense(Model): cost = DecimalField(blank=True, null=True, max_digits=10, decimal_places=2) project = ForeignKey(Project, on_delete=CASCADE) user = ForeignKey(User, on_delete=CASCADE) billable = BooleanField(default=False) expense_date = DateField() date_created = DateTimeField(auto_now_add=True) invoice = ForeignKey("finances.Invoice", blank=True, null=True, on_delete=SET_NULL, help_text="Optionally link this to an existing invoice") Invoice model class Invoice(Model): issue_date = DateField(default=now) due_date = DateField() project = ForeignKey(Project, on_delete=CASCADE) amount = DecimalField(blank=True, null=True, max_digits=100, decimal_places=2) include_expenses = BooleanField(default=False, help_text='Check this box to include all expenses that are within the invoice billable date range') billable_start = DateField(help_text="Logged hours start date") billable_end = DateField(help_text="Logged hours end date") I tried adding a queryset on the Expense model as such: def get_billable_expenses(self): """Getting all expenses for selected billable period""" start_week = self.get_start_isoweek() end_week = self.get_end_isoweek() return self.project.expense_set.filter( expense_date__gte=self.billable_start, … -
How to retain the state of dropdown after performing a POST request in django
I have a page that contains three dropdowns 1. Select question type, 2. Select Marks, 3. Available Tags which are part of QuestionFilterForm. And then I have another form called QuestionPaperForm on the same page inside the <form>. When I select a question type, a list of questions is visible on the same page after a post request. And then I can select one or many from the list of new questions which is another POST request (to add these questions to another list). After the second POST request when I try to refresh the page, chrome shows an alter of form resubmission. In this case, I thought of doing redirect after POST, but then with redirect, I can't retain the options selected in the dropdown. I have to each time select options and view the list of questions. I am not able to think of a good logic where I can handle the redirect issue. My view is as follows def design_questionpaper(request, course_id, quiz_id, questionpaper_id=None): context = {} user = request.user if quiz_id: quiz = get_object_or_404(Quiz, pk=quiz_id) if questionpaper_id is None: question_paper = QuestionPaper.objects.get_or_create( quiz_id=quiz_id )[0] else: question_paper = get_object_or_404( QuestionPaper, id=questionpaper_id, quiz_id=quiz_id ) questions, state = None, None … -
Python TypeError: list indices must be integers or slices, not str django openweathermap api
city_info = { 'city': city, 'temp': res['main']['temp'], 'weatherDescription': res['weather']['description'], 'icon': res['weather']['icon'], 'windSpeed': res['wind']['speed'], } Why when I call the 'weather' object of the OpenWetherMap API I have an error like: TypeError: list indices must be integers or slices, not str I am using Python 3.8.2 and Django 3.1 Full code, as follows: from django.shortcuts import render import requests def index(request): # This is MINE API key! You can change it to yours, if you need it. apiKey = '8bf70752121d2f2366e66d73f3445966' url = 'https://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=' + apiKey city = 'Washington' res = requests.get(url.format(city)).json() city_info = { 'city': city, 'temp': res['main']['temp'], 'weatherDescription': res['weather']['description'], 'icon': res['weather']['icon'], 'windSpeed': res['wind']['speed'], } context = {'info': city_info} return render(request, 'weather/index.html', context) -
Python Django models distance between coordinates
I have 2 django models with different places types and their coordinates on a map. I want to get all objects from first model and then for each of them get places from second model that are within certain range around them. I thought about making a model function like: from haversine import haversine, Unit def checkRange(self, coords, desired_distance): distance = haversine(self.coords, coords) if distance < desired_distance: return self But i figured that would be a big perfomance problem if i check all of them against each other. What would be an optimal method for that? -
How to organize financial statements in Django models
I want to create a financial a Django app for financials statements and cannot decipher how the models should be organized. To start there will be the ticker OHLC data and financial statements ( balance sheet, income statement, cash flows statement ). Each statements stats will be stored as values rather than the full spreadsheet to be able to take advantage of sql querying on the stat level How should models be organized to represent this ? Should financial statements be separated from the base ticker model ? -
How to set depth in Django serializer to relations depth?
I need to show all content of every related field on the way. If i try to set depth = sys.maxint it receive an error: AssertionError: 'depth' may not be greater than 10. So no values greater then 10. I have relation threads of more than 10 models so need some bigger depth. What is the way to set it bigger or just tell serializer to substitute content in all related fields trough all thread? -
reverse function not working in HitcountDetailView in django?
I am trying to attach newsletter form in my postdetail(HitcountDetailView) page,i tried Formmixin and my newsletter registraion working properly but redirect url its not working Error i am getting: Reverse for 'details' with keyword arguments '{'id': , 'slug': 'jobs-available-96'}' not found. 1 pattern(s) tried: ['blog\/details\/(?P[-a-zA-Z0-9_]+)\/(?P[0-9]+)\/$'] views.py class Blog_Detail(FormMixin,HitCountDetailView): model=BlogPost template_name = 'blog/blogDetail.html' context_object_name = 'posts' slug_field = 'slug' count_hit = True id=id form_class=NewsletterForm def get_success_url(self,id=None): if 'slug' in self.kwargs: slug = self.kwargs['slug'] else: slug = 'demo' return reverse('details', kwargs={"id":self.id,'slug': slug}) def get_context_data(self, **kwargs): instance = super(Blog_Detail, self).get_context_data(**kwargs) instance['form'] = NewsletterForm() instance.update({ 'popular_posts': BlogPost.objects.order_by('-hit_count_generic__hits')[:3], 'recent_posts': BlogPost.objects.filter().order_by('-updated')[:3], }) return instance def post(self,request, *args, **kwargs): form=NewsletterForm(request.POST or None) if form.is_valid(): instanceMail=form.save(commit=False) if NewsletterUser.objects.filter(email=instanceMail.email).exists(): messages.warning(request,"Your Email is aldready exists") self.get_success_url() else: instanceMail.save() messages.success(request,"Your Email" +"\t" +instanceMail.email )) subject="Thank you for Joining in JOBvsJOB" from_email=settings.EMAIL_HOST_USER to_email=[instanceMail.email] d={} html_templatey=get_template("blog/UserSubscribeMail.html").render(d) welcomemessage="Welcome" email=EmailMultiAlternatives(subject,'',from_email,to_email) email.attach_alternative(html_templatey,'text/html') email.send() self.get_success_url() form=NewsletterForm() args={"form":form} return render(request,'blog/blogDetail.html',args) urls.py urlpatterns=[ path('details/<slug:slug>/<int:id>/',views.Blog_Detail.as_view(),name="details"), ] slugfield and reverse methods in models.py def get_absolute_url(self): return reverse('details',kwargs={"id":self.id,"slug":self.slug}) def save(self,*args,**kwargs): self.slug=slugify(self.postTitle) + "-" + str(self.id) super().save(*args,**kwargs) -
Is it possible to use Django template block from one file to another file?
I have one template called skeleton.html <head> </head> <body> <div> Some other code </div> <div> {% block contact_info %} {% endblock contact_info %} </div> </body> And my other view is say home.html {% extends "skeleton.html" %} {% block contact_info %} <div class="overflow-hidden"> <h4>Phone</h4> <p class="lead"> {{ phone }} </p> </div> {% endblock contact_info %} So is this possible that I can use the block (contact_info) to any other template? Is there any way to reuse and render this block to another template file (e.g about.html)? -
How to show customers from logged in users in django?
I have a superuser, a few users and a few customers. I would like for users to see their customers, add, edit and delete them. I did all of that, but now all users see each others customers. I am new in django, so this is all new to me, thank you for all the help :) So here is my code: models.py from django.db import models # Create your models here. class Customer(models.Model): customer_name = models.CharField(max_length=100, null=True) customer_phone = models.CharField(max_length=100, null=True, blank=True) customer_email = models.CharField(max_length=100, null=True) customer_date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.customer_name class Service(models.Model): CATEGORY = ( ('Service 1', 'Service 1'), ('Service 2', 'Service 2'), ('Service 3', 'Service 3'), ) service_customer = models.ForeignKey( Customer, null=True, on_delete=models.SET_NULL, blank=True) service_category = models.CharField( max_length=100, null=True, choices=CATEGORY) service_description = models.CharField( max_length=100, null=True, blank=True) service_date_created = models.DateTimeField(auto_now_add=True) service_date = models.DateField( auto_now=False, auto_now_add=False, null=True) def __str__(self): return f'{self.service_category} {self.service_description} {self.service_date}' Here is forms.py from django import forms from django.forms import ModelForm from . models import Customer, Service from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.forms.widgets import DateInput class UserRegForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class NewCustomerForm(ModelForm): class Meta: model = Customer fields = … -
Using the aws cognito UserInfo endpoint
I'm trying to call this User endpoint from my django rest framework backend server. https://docs.aws.amazon.com/cognito/latest/developerguide/userinfo-endpoint.html According to the documentation I need to make a GET request with an authorization bearer token. so from my backend I have tried: ''' requests.get('https://cognito-idp.us-east-2.amazonaws.com/oauth2/userInfo',headers={'Authorization': 'Bearer '+str(request.auth)[2:-1]}) ''' where the splicing at the end is just getting rid of the b' and the ' around the access token from django rest framework's request.auth. I get nothing back or a 400 bad request, but not the one that the documentation says I should get. I've also tried this from postman in various ways. Here's one of them Any help on the proper formatting of this request would be much appreciated! Thanks. -
Chatterbot in django_example returns random responses
I set up the django-example Chatterbot and it works some of the time. I trained the bot using the chatterbot.corpus.english. For some reason, it cannot tell me its name. I initialize my bot as follows in the view.py. All I added to the example code is the training: chatterbot = ChatBot(**settings.CHATTERBOT) trainer = ChatterBotCorpusTrainer(chatterbot) trainer.train( "chatterbot.corpus.english" ) The parameters passed to the chatterbot: CHATTERBOT = { 'name': 'Django ChatterBot Example', 'django_app_name': 'django_chatterbot', 'read_only': True, } The conversation Q Who Are you? A I am just an artificial intelligence. Q What is your name? A i certainly do at times. The logger output: INFO:chatterbot.chatterbot:Beginning search for close text match INFO:chatterbot.chatterbot:Processing search results INFO:chatterbot.chatterbot:Similar text found: How are you? 0.92 INFO:chatterbot.chatterbot:Similar text found: Who are you? 1.0 INFO:chatterbot.chatterbot:Using "Who are you?" as a close match to "Who are you?" with a confidence of 1.0 INFO:chatterbot.chatterbot:0. Excluding recent repeated response of "Today's date is Tue Aug 4, 2020" INFO:chatterbot.chatterbot:Selecting response from 36 optimal responses. INFO:chatterbot.response_selection:Selecting first response from list of 36 options. INFO:chatterbot.chatterbot:Response selected. Using "I am just an artificial intelligence." INFO:chatterbot.chatterbot:BestMatch selected "I am just an artificial intelligence." as a response with a confidence of 1.0 [05/Aug/2020 10:23:55] "POST /api/chatterbot/ HTTP/1.1" 200 … -
Django: how to link users to request.user?
I'm trying to link users that are signed into my database to add/update and delete their own data. So far, I have successfully displayed their data in the table for each specific user. table However, whenever I click add, it brings me to the page: add mark I'm guessing this dropdown user is here because I sent the fields = 'all' on forms.py However, is there any possible way to automatically direct the user to his/her own data, so I don't need to specify which user to add via the dropdown? Does this have anything to do with request.user? Currently, I have no problem having this user dropdown, since I only have two accounts for this website. However, I want to make this easy for people if, let say 100 people using, without them having to scroll down the dropdown to find their names. Please help me to solve this issue! Thank you so much for your help!! -
Deployment of a Django project on Gandi server
While trying to deploy my django project on my Gandy hosting server, while starting running uwsgi, the uwsgi.log shows an error ModuleNotFoundError: No module named 'django' while executing the following line from my wsgi.py file from django.core.wsgi import get_wsgi_application here is the full wsgi file: import sys import os import os.path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'projectname'))) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from what I understand, django is not installed in my virtual environment, but it is listed in my requirements.txt file Django==3.0.6 django-background-tasks==1.2.5 django-compat==1.0.15 django-extensions==3.0.3 django-mathfilters==1.0.0 Can anyone pin point where I am missing something? -
Graphql django Authentication with JWT doesn't work
Description I'm trying to implement JWT_authentication in django using graphene_django and django-graphql-jwt. I followed all the instructions in this link and applied changes in settings.py. I have created an inheritance relationship between the different kind of users in the users app model file. As it obvious I have 4 different type of users: (Administrator, Driver, Authorizer and Customer) model.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Usermodel(AbstractUser, models.Model): phone_no = models.CharField( max_length=11, blank=True, verbose_name="Phone Number" ) USERNAME_FIELD = "username" # e.g: "username", "email" EMAIL_FIELD = "email" # e.g: "email", "primary_email" def __str__(self): return self.username class Driver(Usermodel, models.Model): is_verified = models.BooleanField( default=False, verbose_name="Is Verified" ) national_id = models.CharField( max_length=10, blank=True, verbose_name="National ID" ) profile_picture = models.ImageField( blank=True, null=True, upload_to="./static/profile_pictures", verbose_name="Profile Picture" ) STATUS_CHOICES = [ ('1', 'Free'), ('2', 'Busy') ] driver_status = models.CharField( max_length=1, choices=STATUS_CHOICES, default='1', verbose_name="Driver Status" ) rating = models.FloatField( default=-1, verbose_name="Rating" ) ranking = models.IntegerField( default=-1, verbose_name="Ranking" ) latitude = models.FloatField( default=-1, verbose_name="Latitude" ) longitude = models.FloatField( default=-1, verbose_name="Longitude" ) class Meta: verbose_name = 'Driver' verbose_name_plural = 'Drivers' class Authorizer(Usermodel, models.Model): class Meta: verbose_name = 'Authorizer' verbose_name_plural = 'Authorizers' class Customer(Usermodel, models.Model): class Meta: verbose_name = 'Customer' verbose_name_plural = 'Customers' class … -
I am working on a django website and having trouble in calling a function at the correct place
I have a checkout form on my django website:<form class="row contact_form" action="." method="post" id="form">. That form has a submit button at the end:<input id="form-button" class="btnabc btnabc-outline-info btnabc-lg" type="submit" value="Continue to Payment"> On clicking this button I want to redirect the user to the payment gateway and if his transaction is successful I want to save his information that he entered in the form: This is the javascript code for the button: document.getElementById('payment-info').addEventListener('click', function (e) { submitFormData() }) function submitFormData() { console.log('Payment Button Clicked') var userFormData = { 'name': null, } var shippingInfo = { 'address': null, } shippingInfo.address = form.address.value userFormData.name=form.name.value var url = "/process_order/" fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'form': userFormData, 'shipping': shippingInfo }), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction Completed') window.location.href = "{% url 'index' %}" }) } This is my views.py: def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) total=float(data['form']['total']) order.transaction_id=transaction_id if total == order.get_cart_total: order.complete = True order.save() ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], name=data['form']['name'], email=data['form']['email'], mobile=data['form']['mobile'], ) param_dict = { 'MID': 'DIY12386817555501617', 'ORDER_ID': str(order.id), 'TXN_AMOUNT': '4', 'CUST_ID': 'j', 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL':'http://127.0.0.1:8000/handlerequest/', } param_dict['CHECKSUMHASH'] = … -
Mapping entire app to a different database in Django
I have many apps in my django_project. One of them is user_interaction. I am also using 2 databases.(Sqlite and MySQL) I want my user_interaction app to complete work on MySQL database.whereas other apps should work on sqlite3. The things is i want all the reading,writing,saving,authenticating,etc of user_interaction to happen in MYSQL Database. And reading,writing,saving,authenticating,etc of other apps to happen in Sqlite. This is not working. So What should i Do? settings.py file(database part) DATABASE_APPS_MAPPING = {'user_interaction': 'user_interaction_db', } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'user_interaction_db' :{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'FMS_Database', 'USER': 'fmsdbadmin', 'PASSWORD': 'fevmonsys', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { # Tell MySQLdb to connect with 'utf8mb4' character set 'charset': 'utf8mb4', }, }, } Models.py of user_interaction: class StudentAccountManager(BaseUserManager): def create_user(self,username,password=None): # if not email: # raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have an username") user = self.model( username = username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,username,password): user = self.create_user( password=password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class StudentAccount(AbstractBaseUser): username = models.CharField(max_length=50,unique=True) email = models.EmailField(max_length=254,unique=True) joined_date = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) … -
How to deal with dependable dropdowns in Django
I am trying to create a dependable dropdown on Django but since my JavaScript/ajax knowledge is not great, I have hit rock bottom. Note: I have read previous questions on this matter but none of them fully solved my problem. Problem Description: Due to my database size, I am retrieving partial data from the server whenever a view is requested. This makes my job of using forms harder since I am using the username of the user to filter my server. Here is a simplified version of my code. urls.py urlpatterns = [ url(r'^SpecificVessel', views.SpecificVessel, name="goSpecificVessel"), ] views.py @login_required def SpecificVessel(request): #Get the username to filter the tables from SQL Server: username = None if request.user.is_authenticated: username = request.user.username #Get the shipnames. cursor.execute("select distinct SHIPNAME from Table where [GROUP]=" + "'" + username + "'") row = cursor.fetchall() df_listofships = pd.DataFrame(data=row, columns=['SHIPNAME']) shipnames = list(df_listofships['SHIPNAME'].tolist()) # LIST FOR SHIP SELECTION #Get All the data from database. cursor.execute("select * from Table2 where [GROUP]=" + "'" + username + "'") row = cursor.fetchall() df = pd.DataFrame(data=row) colnames = list(dftrans.columns.values.tolist()) #LIST FOR YEAR DROPDOWN SELECTION #getting the dropdown selections: Dropdown_shipname = request.POST.get('Dropdown_shipname') Dropdown = request.POST.getlist('Dropdown') return render(request, 'SpecificVessel.html', {'colnames': colnames, 'Dropdown': Dropdown, 'shipnames': … -
How to create a gdal.Dataset or xarray.Dataset object from a django.contrib.gis.gdal.GDALRaster object?
I am working on a Django project in which I'm trying to get the all the raster data from my Database. Here is my model in models.py from django.contrib.gis.db import models class RasterWithName(models.Model): raster = models.RasterField() name = models.TextField() Here is the method I use to get all the rows from my Database in django's shell. First I have to do a python manage.py shell and then run the below code, one by one: all_objects = RasterWithName.objects.all() first_object_in_database = all_objects[0] print(first_object_in_database) It prints: RasterWithName object (1) Additionally, running the below line, print(type(first_object_in_database)) prints: <class 'geo.models.RasterWithName'> I then run the two lines below: raster = first_object_in_database.raster print(type(raster)) Which prints: <class 'django.contrib.gis.gdal.raster.source.GDALRaster'> How can I convert this GDALRaster object into a more known object like a gdal Dataset( that can be imported like this: from osgeo.gdal import Dataset) or xarray Dataset (that can be downloaded like this: from xarray import Dataset) -
Django hosting on heroku becoming a real trouble
Is there any work-around for this really?? am totally having a huge challenge hosting my django applications. If there is any simpler way of hosting django apps on any server please also suggest for me. Even after what seemed at first as a successful host on heroku, I again got this error ***Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail*** -
EMBED IN DJANGO TEMPLATE PDF MEDIA FILE
The question is that I want to embed a pdf file through or tag or similar in a django template using {{ object.file.url }} which is presumed to be a file saved in the /MEDIA/ folder by a django MODEL. The fact is that, If I embed a PDF file coming from /STATIC/ folder everything goes well but if I try the same with the {{ object.file.url }} does not work. The curious thing is that, if I simply display the {% static 'path/pdf.pdf' %} and {{ object.file.url }} they both give me a valid link like this : /static/img/111.pdf /media/projects/phases-guide/111.pdf If I try to open them separatedly they perfectly work, but in the moment to try embed them in a HTML tag only work the static url file someone can tell me any idea why is happening? Anyway, is there any alternative to "EMBED FILE COMING FROM MEDIA FOLDER ROOT"???? to enable read media files but anyway is not working THANKS IN ADVANCE!!!! -
How do I create a django project on my D: drive?
I'm new to python and django and wanted to create a django project on my D drive. However, in order to create the django project I have to do it through the terminal and it seems to automatically create the django project in my C drive. How can I change that location?