Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what are differences between Generics and Views and Viewsets and Mixins in Django
I am new in Django and Django-Rest and I am studying books and video tutorials about it . but I am confused when can I use of these? what are their advantages and disadvantages ? i just see this http://www.cdrf.co and the only thing I know is there are a lot of ways to do 1 thing . but this is totally unclear for me . -
Writting 'Accept' and 'Reject' function Django
Need a help with CarSupplyChain app, which repeats the car business in short. Got a blocker with writing the 'Accept' and 'Reject' function, do not know how to write it. I have 3 type of users: Manufacturer Admin(MA), Dealership Admin(DA) and Customer(C). DA has the ability to Initiate the Wholesale Deal to MA. Here is the model for Wholesale deal: class WholesaleDeal(models.Model): DEAL_STATUS = ( ('Y', 'Accept'), ('N', 'Reject'), ('W', 'Waiting') ) car_name = models.ForeignKey(WholesaleCar, on_delete=models.CASCADE) car_amount = models.IntegerField() total_price = models.IntegerField() status = models.CharField(max_length=2, choices=DEAL_STATUS, default='W') def __str__(self): return self.car_name MA can see the list of Wholesale Deals and he shall have function rather 'Accept' or 'Reject' that deal. If accepted: An amount of Wholesale Cars equal to the amount specified in the Deal application and have the same specifications as mentioned in the application would be removed from the Manufacturer’s Inventory and added to the Dealership’s Inventory as Retail Cars Total cost would be deducted from the Dealership’s Balance and added to the Manufacturer’s Balance Else if the Manufacturer Admin refuses, the application shows up to the Dealership Admin as “Rejected”. WholesaleCar model: class WholesaleCar(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) blueprint = models.ForeignKey(Blueprint, on_delete=models.CASCADE, … -
Repeat a Django template block with different contents, sometimes
I'm working on a website that has a list of steps on the left and a main content block in the middle/right. I want the list to appear once on all pages with the current step highlighted, while the main content block contains content specific to the current step. My template code for this is: base.html <html><body> <!-- Style, headers, etc. --> <ul style="float: left"> {% for listItem in listItems %} <li>{{ listItem }}</li> {% endfor %} </ul> <div style="float: right"> {% block content %}{% endblock content %} </div></body></html> step1.html {% extends "base.html" %} {% block content %} <!-- Step 1 details --> {% endblock content %} step2.html {% extends "base.html" %} {% block content %} <!-- Step 2 details --> {% endblock content %} So far, so good. However, I then want the user to be able to print all these steps without having to navigate to each step and click File -> Print. So what I want is a single webpage that contains all the steps and their details in one long webpage, so the user can print all steps and their details by simply printing this one page. This means I want to repeat both the list … -
django - need help in building a car supply app
I'm building a car supply management app to get experience in django . I have created user signup and login sytem but now I need help for further functionalities mentioned below A user can signup either as buyer or dealer or manufacturer The attributes and permissions of these roles are described below: Manufacturer Admin: a Manufacturer representative in the system whose role is to maintain his/her Manufacturer’s data. A Manufacturer Admin can do the following: Initiate a Manufacturing Order Accept/Refuse a Wholesale Deal Create/Edit/Delete a Blueprint Modify/Remove Cars from his/her Manufacturer’s Inventory Add Balance to his/her Manufacturer’s account However, he/she cannot do the following: - Contact a Customer in any way Initiate Wholesale Deals Initiate Retail Deals Dealership Admin: A Dealership representative in the system whose role is to maintain his/her Dealership’s data. A Dealership Admin can do the following: Initiate a Wholesale Deal Accept/Refuse a Retail Deal Modify /Remove Cars from his/her Dealership’s Inventory Add Balance to his/her Dealership’s account Customer: An interested buyer willing to conduct Retail Deals with Dealerships. A Customer can do the following: View Cars showcased by Dealerships Offer a Retail Deal to a Dealership Add Balance to his/her account It would … -
Does Django REST Framework works normally with Amazon Lightsail? (CORS error)
I have a Django application deployed on Amazon Lightsail but when I try to do a request to our endpoints using Angular I get HTTP 0 error. I have django-cors-headers installed. settings.py INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True I am using Apache web server so I also added this to 000-default.conf Header set Access-Control-Allow-Origin "*" -
Django Query Set to get Row value as column name
class Build(models.Model): name = models.CharField(db_index=True, max_length=56) description = models.TextField(max_length=512, null=True, blank=True) class Case(models.Model): name = models.CharField(db_index=True, max_length=255) description = models.TextField(max_length=1024, null=True, blank=True) class Result(models.Model): status = models.CharField(max_length=12) result_build = models.ForeignKey(Build, related_name='result_build', on_delete=models.CASCADE) result_case = models.ForeignKey(Case, related_name='result_case', on_delete=models.CASCADE) Here is my model i need django query set to get data like below .................................................... : case_name : case_description : build_X : build_Y : :...........:..................:.........:.........: : test1 : case1 : PASS : FAIL : : test2 : case2 : FAIL : PASS : :...........:..................:.........:.........: Where case_name and case_description are fields from Case model build_X and build_Y are the two build names avaialble in build model and PASS and Fail are the status for different case and build from result model -
Django CreateView inline formset instance and queryset
So I have a view to make customer payments. When the page is first rendered there's an empty form. I'm using ajax to choose a customer then return an html string of all the outstanding invoices for that customer and inserting it into the empty form. When the form is submitted in order for the outstanding invoices formset to be valid I need to pass it the matching instance and queryset as the ajax generated formset. The problem I'm running into is passing the customer instance into get_context_data(). Right now I have customer hard-coded to pk=1 and can confirm that the formset is valid. There's also a hidden field with the value for customer in the form but I'm not sure how to pass that into get_context_data(). Anyone have any idea how to accomplish this? class PaymentCreate(CreateView): template_name = 'payment_create.html' model = Pay_hdr success_url = reverse_lazy('payments') form_class = PaymentHeadForm def get_context_data(self, **kwargs): context = super(PaymentCreate, self).get_context_data(**kwargs) context['customers'] = Customer.objects.all().order_by('name') if self.request.POST: customer = Customer.objects.get(pk=1) # need to replace this line queryset = Accounts_receivable.objects.filter(customer=customer).exclude(balance=0).order_by('-date_trans') context['user'] = self.request.user context['formset'] = ARLineFormset(self.request.POST, instance=customer, queryset=queryset) else: context['formset'] = ARLineFormset() return context def form_valid(self, form): context = self.get_context_data() user = context['user'] formset = context['formset'] if … -
ModelForm set instance file input change text
I have the following code: advertisement = Advertisement.objects.get(id=advertisementid) form = AdvertisementForm(request.POST or None, request.FILES or None, instance=advertisement) I'd like to change the text Currently, Change which is initially set by Django in my HTML-View where a image or file can be chosen. Thanks for your help. -
Heroku + Django, can't make migration to postgres
I'm trying to put a django based app on Heroku with Docker. I'm using one container for postgres and another one for my app locally. In production, I only push my app and use heroku postgres add-on. Locally it works fine. But when I try to upload it to Heroku, my app seems able to connect to postgres database, but can't find any tables. I have no idea where the problem is, except maybe migrate fail because of some restricted authorisation (but I didn't see any error outputs through the Heroku logs): here my docker-compose: web: build: . command: bash -c "python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db And here the postgres conf: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) Here is my problem: 1) I can't connect directly to the heroku dyno because this is a lot of painful configuration and I didn't succeed (the documentation is a little blurry about how to achieve this) 2) I have no idea if the postgres is actually linked. All i did is put db_from_env = dj_database_url.config(conn_max_age=500) as … -
Django url patterns, redirect from root to other url
This should be an easy enough problem to solve for you guys: I just started working with Django, and I'm doing some routing. This is my urls.py in the root of the project: urlpatterns = [ path('admin/', admin.site.urls), path('', include('dashboard.urls')), ] This is the routing in my dashboard app: urlpatterns = [ path('dashboard', views.index, name='index'), path('', views.index, name='index'), ] Now let's say I want my users to be redirected to /dashboard if they go to the root of the website. So I would use '' as a route in the urls.py in the root, and then have everyone sent to /dashboard from the urls.py in the dashboard app. But when I do this I get the following warning: ?: (urls.W002) Your URL pattern '/dashboard' [name='index'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. So I tried to use '/' instead of '', but since a trailing / is automatically removed from an url, the url wouldn't match the pattern. Should I ignore/mute this warning or is there another way to go about it? -
Access Data from Angular JS http.POST with Django Python HTML to Views.py
I am new to Python with django. I need to process the data from Angular js http.post in Views.py. My data got posted but i am unable to use/process the data in views.py. Plz help. i like to get data in list or dict. `enter code here` <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> <html lang="en"> {% load staticfiles %} <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> </head> <form action="/your-name/" method="POST"> {% csrf_token %} <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" value="{{ current_name }}"> {% csrf_token %} {{name.customer_gid}} {{name.customer_name}} <input type="submit" value="OK"> </form> <body> <a href="{% url 'stock' %}">Stock </a> <div ng-app="Appemployee" ng-controller="CustomerController"> {% csrf_token %} <p> Name : <input type="text" ng-model="name"> </p> {% verbatim %} U Typed : {{name}} <div> <input type="text" name="txt_post" value="" ng-model="txt_db_post" > <input type="submit" value="Post To DB" ng-click="POST_script_DB()"> </div> {% endverbatim %} </div> <script> var myApp = angular.module('Appemployee', []).config(function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }); myApp.controller('CustomerController', ['$scope','testService', function($scope,testService) { $scope.POST_script_DB = function() { var posteddata = testService.getcusomter($scope.txt_db_post); posteddata.then(function (result){ alert(result.data); }),function(){ alert('no data'); }; <!--alert($scope.txt_db_post)--> }; }]); myApp.service("testService", function ($http) { this.getcusomter = function (e) { var response = $http.post("/stock_post/",{parms:{"stock_post":e}}); alert(response) return response; } }); </script> </body> </html> The above html and service will post data to views … -
Django_permissions, how to template my menu item based on the permissions? in the view.py
I want to display menu item based on my given permissions, for example users who are not a Project manager thex dont see item project in the menu and so on.. I have a separated Client dashboard from admin dashboard which is not so good and pro. Here my code: views.py class UsersListView(PermissionRequiredMixin, LoginRequiredMixin, ListView): login_url = 'accounts/login/' permission_required = 'can_view_user' template_name = "user_list.html" model = User def dispatch(self, request, *args, **kwargs): if check_permission_BM_or_AM(request): if request.user.is_authenticated(): return super(UsersListView, self).dispatch(request, *args, **kwargs) return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) permission.py def check_permission_BM_or_AM(request): customer= Customer.objects.get(auth_user_id=request.user.id) marolle = MaRolle.objects.filter(ma=customer.id) rollen = Rollen.objects.get(id=1) rollens = Rollen.objects.get(id=4) for ma in marolle: if str(ma.rolle) == rollen.rolle or str(ma.rolle) == rollens.rolle: return True menuitem.html <ul><li class="dropdown-submenu "> {% if perms.user %} <a tabindex="-1" href="/administrator/de/projekt/"><span class="fa fa-fw fa-book "></span> Projekte</a> {% endif %}</li></ul> how to use the template to get my class view to work based on the given permission_required = 'can_view_user'permission? -
delete date range from DateTime field in Django
I have the following function that takes a csv file, reads the unique dates, and then deletes them. def delete_dates(self, lines): try: #read csv file file = csv.DictReader(lines.splitlines(), delimiter=',') #holds the dates that will be deleted from the DB dates = [] for row in file: #append every date in the file dates.append(self.get_date_only(row['date/time'])) #print unique dates in dates list print set(dates) #prints MAX AND MIN print max(set(dates)) print min(set(dates)) #if there are dates delete all objects from that date with the same country and company if set(dates) > 0: for date in set(dates): try: objects_to_delete = Payments.objects.filter( date_time=date ).filter( Account=self.company ).filter( Country=self.country ).delete() except Exception as e: print (e) except Exception as e: print (e) return False return True It seems like it is looking for objects with the same date and 0:00 for the time. I would like the same logic as: delete from Table where Account = 'account' and Country = 'country' and date_time between min(set(dates)) and max(set(dates)) This way all data from the dates in dates list are deleted. -
django - authenthicate - missing required potential argument 'self'
I have a custom auth backend and I am trying to connect users with it. This is the backend import logging from .models import Users class OwnAuthBackend(object): def authenticate(self, email, password): try: user = Users.objects.get(email=email) if user.check_password(password): return user else: return None except Users.DoesNotExist: logging.getLogger("error_logger").error("user with login %s does not exists " % login) return None except Exception as e: logging.getLogger("error_logger").error(repr(e)) return None def get_user(self, user_id): try: user = Users.objects.get(sys_id=user_id) if user.is_active: return user return None except Users.DoesNotExist: logging.getLogger("error_logger").error("user with %(user_id)d not found") return None And this is in the view.py email = form.cleaned_data['email_field'] password = form.cleaned_data['password'] user = OwnAuthBackend.authenticate(email=email, password=password) if user is not None: messages.success(request, 'You logged in successfully!') return redirect('index') else: messages.warning(request, 'Credentials were wrong. Failed to log in!') return redirect('index') message.error(request, 'Something went wrong while logging you in..') return redirect('index') The import: from main.backends import OwnAuthBackend Error is in the title I really have no idea what self I have to make, tried placing the request there but that didn't work. According to: users.is_authenticated - custom user model, the user is logged in if I use user = OwnAuthBackend.authenticate(request, email=email, password=password) But the problem is, if I go to control panel, the user isn't logged in … -
Issue with Django Paginator
I'm trying to use Django Paginator according to my CBV process but I don't overcome to display pages with my array. My class looks like : class IdentityIndividuResearchingView(LoginRequiredMixin, ListView) : template_name = 'Identity_Individu_Recherche.html' model = Individu context_object_name = 'queryset' def get_object(self) : queryset = Individu.objects.order_by("-id") return queryset def get_context_data(self, **kwargs) : context_data = super(IdentityIndividuResearchingView, self).get_context_data(**kwargs) person_France = Individu.objects.filter(Pays='FR') context_data['person_France'] = person_France if 'recherche' in self.request.GET: query_lastname_ID = self.request.GET.get('q1ID') query_firstname_ID = self.request.GET.get('q1bisID') query_naissance_ID = self.request.GET.get('q1terID') sort_params = {} lib.Individu_Recherche.set_if_not_none(sort_params, 'Nom__icontains', query_lastname_ID) lib.Individu_Recherche.set_if_not_none(sort_params, 'Prenom__icontains', query_firstname_ID) lib.Individu_Recherche.set_if_not_none(sort_params, 'VilleNaissance__icontains', query_naissance_ID) query_ID_list = Individu.objects.filter(**sort_params) context_data['query_ID_list'] = query_ID_list paginator = Paginator(query_ID_list, 3) page = self.request.GET.get('page', 1) try: query_ID_list = paginator.page(page) except PageNotAnInteger: query_ID_list = paginator.page(1) except EmptyPage: query_ID_list = paginator.page(paginator.num_pages) And my template looks like this : <table class="tableform" style="width:85%"> <tbody> <tr> <th>ID</th> <th>État</th> <th>N° Identification</th> <th>Civilité</th> <th>Nom</th> <th>Prénom</th> <th>Date de Naissance</th> <th>Ville de Naissance</th> <th>Pays de Naissance</th> <th>Institution</th> </tr> {% for item in query_ID_list %} <tr> <td>{{ item.id}}</td> <td>{{ item.Etat}}</td> <td>{{ item.NumeroIdentification}}</td> <td>{{ item.Civilite }}</td> <td>{{ item.Nom }}</td> <td>{{ item.Prenom }}</td> <td>{{ item.DateNaissance }}</td> <td>{{ item.VilleNaissance }}</td> <td>{{ item.PaysNaissance }}</td> <td>{{ item.InformationsInstitution }}</td> </tr> {% endfor %} </tbody> </table> {% if query_ID_list.has_previous %} <a href="?page={{ query_ID_list.previous_page_number }}&q1ID={{ request.GET.q1ID }}">Page précédente</a> {% endif %} <span class="current"> … -
Django rest api post data from browser
I am a newbie in Django so forgive if the question is silly but I didn't find the answer of it. I am making an API which goes GET and POST request of in the products table. views.py rom rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . models import products from . serializers import productSerializer from django.db.models import Q class productList(APIView): def get(self, request): product_list = products.objects.all() serializer = productSerializer(product_list, many=True) query = self.request.GET.get("item_id") if query: product_list = product_list.filter( Q(item_id=query)).distinct() serializer = productSerializer(product_list, many=True) return Response(serializer.data) def post(self): serializer = productSerializer(self.request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py from django.contrib import admin from django.urls import path from webshop import views urlpatterns = [ path('admin/', admin.site.urls), path('products', views.productList.as_view()), ] models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class products(models.Model): item_id = models.CharField(max_length=20) item_name = models.CharField(max_length=255) item_price = models.FloatField(validators = [MinValueValidator(0.0)]) def __str__(self): return self.item_name I can use the get request in the browser easily with the following urls in the browser and the get the required JSON data. # Get all the products http://localhost:8000/products # Get the product with id=2 http://localhost:8000/products?id=2 Now I want to do the POST request using … -
Wagtail OpenCV with Python3
Looking at this page http://docs.wagtail.io/en/v1.13.1/advanced_topics/images/feature_detection.html What would be the equivalent to sudo apt-get install python-opencv python-numpy for python3 I've found python3-numpy but can't seem to find a version of opencv for python3, I've ended removing that from our Dockerfile and installing opencv-python==3.4.0.12 in our requirements file. This seems to work but is this a non standard way to handle this or is this ok? Thanks Joss -
Django - Using signals to make changes to other models
say I have two models like so... class Product(models.Model): ... overall_rating = models.IntegerField() ... class Review(models.Model): ... product = models.ForeignKey(Product, related_name='review', on_delete=models.CASCADE) rating = models.IntegerField() ... I want to use the ratings from all of the child Review objects to build an average overall_rating for the parent Product. Question: I'm wondering how I may be able to achieve something like this using Django signals? I am a bit of a newbie to this part of Django; have never really understood the signals part before. This overall_rating value needs to be stored in the database instead of calculated using a method since I plan on ordering the Product objects based on their overall_rating which is done on a DB level. The method may look something like this if I were to implement it (just for reference): def overall_rating(self): review_count=self.review.count() if review_count >= 1: ratings=self.review.all().values_list('rating',flat=True) rating_sum = 0 for i in ratings: rating_sum += int(i) return rating_sum / review_count else: return 0 Thank you -
How to use django admin to automatically select the model ??
For example, there are 3 models, task, car, driver. task has two foreign keys, car and driver. Car OneToOneField driver. After the task select the car, how to automatically correspond to the driver, in the admin interface?? thank you all -
Filtering results using Javascript and Django model not working
I have a model for events which are in different cities. When on the site you choose a city that you're in. What I want to do is that you only ever see available events of the city you're in. My problem is that in rendering the html results I seem to have a problem regarding the views and interaction between javascript in getting the city and the django models and having the results filter. When I try to get the city stated within the view using 'GET' I keep getting an error regarding global variables not being declared that is I use this following construction: def IndexPage(request): def GetCitySession(request): if request.method == "GET": global cityName cityName = request.session['city-name'] cityId = request.session['city-id'] context = { "cityName": cityName, "cityId": cityId } return JsonResponse(cityName) venues = ProfileVenue.objects.all().filter() oc_list = [] for venue in venues: if Occurrence.objects.filter(date__gte=timezone.now()).filter(event__location=venue).exists() and venue.city.name==cityName: or I get 'Key error' error with exception value 'city-name' if I use this construction: if Occurrence.objects.filter(date__gte=timezone.now()).filter(event__location=venue).exists() and venue.city.name==request.session['city-name']: So how would one go about making sure it filters correctly? I've looked around and I haven't yet found something suitable to my needs. Javascript that sets city values /* Ciudades */ if(localStorage.getItem("cities") == null){ … -
Creating django model with foreignkey field
Suppose I have the following models: class Room(models.Model): title = models.CharField(max_length=255) room_log = models.ForeignKey("Log", on_delete=models.CASCADE, blank=True, null=True) ... class Log(): fs = FileSystemStorage(location=LOG_PATH) name = models.CharField(max_length=255) log = models.FileField(storage=fs, blank=True, null=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not os.path.exists(LOG_PATH): os.makedirs(LOG_PATH) self.log.save(self.name + '.log', ContentFile('start of log!')) return super(Log, self).save(force_insert, force_update, using, update_fields) else: if not os.path.isfile(LOG_PATH + self.name + ".log"): self.log.save(self.name + '.log', ContentFile("start of log!")) else: pass return super(Log, self).save(force_insert, force_update, using, update_fields) I want for each Room model I create to have assigned a new Log model with the same name of the room. I've tried editing the save() function of the Room model like this: def save(self, *args, **kwargs): if not self.pk: Log.objects.create(name=self.title) return super(Room, self).save(*args, **kwargs) But it just returns the error UNIQUE constraint failed: chat_log.id when creating a new Room model (The creation of Log model works great). How would I do that? -
pyrqlite/rqlite Insert statement has no effect
My python insert statement seems to have no effect on my rqlite database. I tried to change the insert statement several times with no success, I also read the DOC 3 times now and couldn't find any solution. Python doesn't catch any exceptions neither, so I have no idea what the error could be. I started the first node like so: ./rqlited -http-addr 192.168.88.106:4001 -raft-addr 192.168.88.106:4002 ~/node and the second to join: ./rqlited -http-addr 192.168.88.12:4001 -raft-addr 192.168.88.12:4002 -join http://192.168.88.106:4001 ~/node when I then execute my script: with connection.cursor() as cursor: cursor.execute("INSERT INTO t_card(uuid, prim, active, id_person) VALUES(?, ?, ?, ?)", (nfc, 1, 1, pk)) connection.commit() no entry is made to the db the connection I establish like so: import pyrqlite.dbapi2 as dbapi2 IP = environ['IPTM'] connection = dbapi2.connect( host=IP, port=4001, ) the IPTM I set in bash, and it defenitely reads it in python export IPTM=192.168.88.106 any help is highly appreciated! -
How do I host my Django app on a intranet?
I have successfully developed a Django app. The requirement is to deploy the app over an on-premise server. The application is accessible on the intranet using the development environment. Is any web server is preferred to deploy this application locally (or) Should I leave the terminal running the server as it is so that the users can access the application as they are already doing it? Any suggestions appreciated. PS: I am using Unix server. -
POSTing foreign keys to Django Rest Framework, using Postman
So I've made a simple REST API for the company I work for. This is a side project, so I'm still learning a lot. So far it works nicely for GET requests. The problem I'm facing now is trying to do POST requests (Using Postman for now, the idea is to connect the API straight to a sensor that broadcasts JSON data and upload all that data to our DB through the API). The way we have set up the models, there are several ForeignKey relationships in our DB (we are using PostgreSQL if that makes a difference). I'm trying to POST one of our most basic bits of information, but arguably the most important which is measurement data. The model for a data point has a ForeignKey to a parameter, and a sensor. A parameter would be a model that has a parameter name, type, position, and a sensor would be another model that itself has a ForeignKey to a Chamber (another model that also includes it's own ForeignKeys, to Customers), and another ForeignKey to SensorType. In short, for relationships, data relates to parameter, and sensor (which relates to SensorType, and to Chamber which itself relates to Customer which … -
Django How can I render Images through a for loop
I uploaded images with admin, but cannot render them in the template. I've been looking at other questions but nothing is working. What am I missing? Settings.py STATIC_URL = '/static/' STATIC_DIRS = { os.path.join(BASE_DIR, "static"), } MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Models.py class Function(models.Model): name = models.CharField(max_length=50) fimage = models.ImageField(upload_to="images") def __unicode__(self): return "name{},id{}".format(self.name, self.id) HTML {% for function in functions %} <a href="function_page/{{function.id}}"> <img id=function_menu_pic src="{{MEDIA_URL}}{{function.fimage.url}}"></a> {% endfor %}