Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django printing many to many children not in same order as input
I have a tour model with a many to many relationship with Places both models are defined as : class Tourguide(models.Model): id = models.AutoField(db_column='ID', primary_key=True, unique=True) title = models.CharField(db_column='Title', max_length=255, blank=True) places = models.ManyToManyField(Place, db_column='placesdj') created_on = models.DateTimeField(db_column='Created_On', default = now) class Meta: managed = False db_table = 'tourguide' def __str__(self): return self.title class Place(models.Model): place_id = models.AutoField(db_column='ID', primary_key=True) place_name = models.CharField(db_column='Place_Name', max_length=255) address_line_1 = models.CharField(db_column='Address_Line_1', max_length=255) address_line_2 = models.CharField(db_column='Address_Line_2', max_length=255) area = models.CharField(db_column='Area', max_length=255) class Meta: managed = False db_table = 'Place' def __str__(self): return self.place_name - THE PROBLEM When i try to print the places in a tourguide using : {% for place in tour.places.all %} <tbody> <td>{{ forloop.counter }}</td> <td>id: {{place.place_id}}, {{ place.place_name }} </td> <td> {{ place.description }} </td> </tbody> {% endfor %} The order of the places is all random and not the same as the order i inputed it as. i want to print the places in the same order that i placed them in. My view for listing the tourguides and places within them is as so. def tour_list(request, template_name='tourguides/tour_list.html'): tourguide_list = Tourguide.objects.all() paginator = Paginator(tourguide_list,6) page = request.GET.get('page') tourguides = paginator.get_page(page) data = {} data['tourguides'] = tourguides return render(request, template_name, data) I … -
Hiding fields with Django crispy forms
I have the following in my forms.py : class DocumentsForm(forms.ModelForm): class Meta: model = Documents # Your User model fields = ['EMAIL', 'OWNERFULLNAME', 'OWNERSTREET', 'OWNERCITY', 'OWNERSTATE', 'OWNERZIP', 'DATE'] labels = { 'EMAIL': 'Owner Email', 'OWNERFULLNAME': 'Owner Address', 'OWNERSTREET': 'Owner Street', 'OWNERCITY': 'Owner City ', 'OWNERSTATE': 'Owner State', 'OWNERZIP': 'Owner Zip', 'DATE': 'Is the property in a Home Owners Assoc (HOA)? Annual dues? HOA specific property restrictions?', # 'captcha': "Enter captcha" } helper = FormHelper() helper.form_method = 'POST' helper.form_action = "/contact/" helper.form_id = 'form' # SET THIS OR BOOTSTRAP JS AND VAL.JS WILL NOT WORK helper.add_input(Submit('Submit', 'Submit', css_class='btn-primary')) I want to Hide the date field, In the docs (https://django-crispy-forms.readthedocs.io/en/latest/layouts.html) , this can be handled using the Field('field_name', type="hidden") Can this be done in the format I'm using above? -
Is it possible to have two ManyToMany relationships to the same model on the same admin page?
I modelling a quiz and the associated questions as follows: # models class Question(models.Model): title = models.TextField() category = models.TextField() class Quiz(models.Model): questions = models.ManyToManyField(Question, through='OrderedQuestion') class OrderedQuestion(models.Model): # A through table to allow ordering of questions question = models.ForeignKey(Question, ...) quiz = models.ForeignKey(Quiz, ...) order = models.PositiveIntegerField(default=0) I have two types of questions that are handled by proxy models: # proxy models to handle specific question categories class BoatQuestion(Question): objects = BoatQuestionManager() # handles setting category class Meta: proxy = True and a similar one for CarQuestion. I want to be able to edit BoatQuestions and CarQuestions independently from each other but on the same admin page. The admin setup is: class BoatQuestionInline(admin.TabularInline): model = BoatQuestion.quiz.through class CarQuestionInline(admin.TabularInline): model = CarQuestion.quiz.through class QuizAdmin(admin.ModelAdmin): model = Quiz inlines = (BoatQuestionInline, CarQuestionInline) but whenever I change the questions in the boat question section, the questions in the car section update to match it and vice versa. Is there any way to show these on the same admin page but change them independently? -
Never cache js for development
I am using django runserver for development and I often find that the javascript file that I am using is being cached. It's almost impossible to tell when it's being cached unless I add alert or console.log statements every time I make a change to see if that's actually been "picked up". Is there a setting in django to never cache the static files when running on localhost? Or is this something that has to do with my browser (Chrome) instead? What I am doing now as a hack, is each time I make a javascript change I change v1 in my script tag. <script src="{{ STATIC_URL }}js/settings.js?v1"></script> -
Django: Patch a call in get_context_data of a FormView
I am trying to understand how patching works and I am testing with pytest a Django View: views.py from django.contrib.auth.views import LoginView class MyLoginView(LoginView): pass test_view.py from django.test import RequestFactory from .views import MyLoginView rf = RequestFactory() def test_login(rf): request = rf.get(reverse('myapp:login')) response = MyLoginView.as_view()(request) assert response.status_code == 200 This fails because this View calls the database in order to get the current Site using the function get_current_site(): Failed: Database access not allowed How can I mock get_current_site to avoid the database hit? I got an idea, try to use a factory with pytest-factoryboy: from django.test import RequestFactory from .views import MyLoginView from django.contrib.sites.models import Site from pytest_factoryboy import register from unittest.mock import patch rf = RequestFactory() class SiteFactory(factory.Factory): class Meta: model = Site register(SiteFactory) def test_login_social(rf, site_factory): request = rf.get(reverse('myapp:login')) with patch( 'django.contrib.sites.shortcuts.get_current_site', return_value=site_factory(name='example.com'), ): response = CommunityLoginView.as_view()(request) assert response.status_code == 200 The result is the same: Failed: Database access not allowed How would you do it? -
How to filter objects at django based on related field?
I have models: - Product - Store - ProductStore (additional table with foreign keys to Store and Product, also Boolean 'enabled', and stock(integer) ) The questions: How can I filter Products which has Enabled=True for current store__id (from request)? Also, how can I add an additional field for every objects with stock at current store? -
Django models vs raw SQL queries
I'm working on my senior design project, and I've got some questions about Django that I'm having trouble finding the answers to. If these questions have been answered before, please just point me in the right direction because my searches weren't turning up anything. The general scope of the project is a website that interfaces with a database. I'm personally responsible for developing the DB as well as writing some API to make it easier on my team, who is less familiar with SQL base languages. I've already built a prototype of my database in mysql, but I later found out that Django's implementation of database integration uses models, and it looks it ultimately replaces the mysql implementation. Since I've already built the database, should I redesign it with Django or am I safe to continue only using raw queries? Are there any significant security concerns to be aware of if I decide to forgo the model method of implementation? Thanks in advance for your advice! -
Django Taggit Through Model
Say we have this Django Scenario: We have a model class instantiating home appliances (fridges, tvs, cooktops...) and we need to add classified tags to it. By classified tags, I mean that the tags should be grouped by criteria like "color", "voltage", "technology"... My approach to this using django-taggit required creating a custom tag class like described below. class HomeAppliance(models.Model): name = models.CharField(db_index=True, max_length=100) ## Fridge Bosch Frost Free Inox... ##fields here... tags = TaggableManager(through=TaggedModels) ## inox, frost free... class TaggedHomeAppliance(TaggedItemBase): content_object = models.ForeignKey('HomeAppliance', on_delete=models.CASCADE) filteringCriteria = models.ManyToManyField("FilteringCriteria") class FilteringCriteria(models.Model): name = models.CharField(max_length=100) ##color, voltage, technology My question here is how should I add tags to my model like this: frigde.tags.add('inox', 'frostfree') and have these tags properly assigned to my filtering criteria. In other worlds, how my TaggedHomeAppliance instance can correctly find out which filter criteria my tag should be added to, or how should I pass this information while adding my tags to the model. Thanks in advance, Felipe. -
DRF Router issue with namespace
I am having a hell of a time getting the reverse function to work with my DRF implementation. Here is my urls.py, which i would assume the following reverse to work for: urls.py from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'compressors', views.CompressorViewSet, base_name='compressors') from django.urls import include, path # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls, namespace='router')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] And then reverse('router:compressors', kwargs) What am I missing? I am getting a app_name not provided, which when added to this file does not help. Is there a way for me to put an app_name to the router? -
How to connect Google API with Django?
In a project, I have to retrieve google contacts for each user. Here the user is authenticated with Google social API. Is there a way that whenever the user wants to access his contacts, he would be asked to authorize the app and then the app server can access his contacts. -
How can I migrate after removing model "hidden" in my Django Models?
I created a hidden input in my models.py: hidden = models.BooleanField(default=False) and proceeded to makemigrations and migrate my changes. After doing so, I decided to remove it and so i went and deleted the same line and did makemigrations although this time I got an error ending along the lines of: File "/opt/django/www/local/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/opt/django/www/local/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 205, in execute File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler django.db.utils.OperationalError: (1091, "Can't DROP 'hidden'; check that column/key exists") Did I handle the situation incorrectly? -
django project - timepiece - My "field" not showing up in chrome
Im running my django project, indeed its the timepiece project here: https://github.com/caktus/django-timepiece And when im running it, i dont have access to any field. Insteald of a field, its a string saying "field". See the screenshot: https://i.stack.imgur.com/3C5Pf.png This is the "source code" from chrome: <div class="controls"> field </div> Any help would be appreciate. thanks -
Python3/Django - QuerySet not updating
I'm creating a website that allows for the creation of events, and those events will be shown on both the home page, and on the events list, so that people can click on the events on view the descriptions of them, as well as check in at the event. I'm having an issue getting a query set within a class to update when a new event is added. So this function is for our main home page. The query_set updates every time you go back to the page, so when a new event is added, it is shown on this page. def index(request): num_future_events = Event.objects.filter(date__gte=today).filter(approved=True).count() query_set = Event.objects.filter(date__gte=today).filter(approved=True).order_by('date', 'time')[:3] context = { 'num_future_events': num_future_events, 'query_set': query_set } return render(request, 'index.html', context=context) This is a class for the events list page on my site. It uses a query set but since the class is only ever called once, the query set will only update with the class's initialization. class EventListView(generic.ListView): model = Event query_set = Event.objects.filter(date__gte=today).exclude(approved=False).order_by('date', 'time')[:21] template_name = 'listPage.html' def get_queryset(self): return self.query_set I was hoping to get some help with making it so when a new event is added, the query set in the EventListView class updates automatically … -
combine django user with many-to-many model for display organized by user and other fields
I have a django model that represents a calendar event: class Event(models.Model): title = models.CharField(max_length=120) date = models.DateField(default=default_event_date) category = models.ForeignKey(Category) users = models.ManyToManyField(User, related_name='events', limit_choices_to={'is_staff': True}) ... How can I get a queryset from this model and organize the data so that I can display it (in a template) something like this: Date1 Date2 Date3 Date4 ... User1 CatA (Title1) CatC (Title4) CatB (Title7) - User2 CatD (Title2) CatB (Title5 - CatD (Title9) User3 CatC (Title3) CatC (Title4) CatC (Title8) CatC (Title10) User4 - - - - User5 - CatA (Title6) - CatD (Title9) ... Where DateN is the date field, UserN is the users field, and CatX is the category field, and TitleN is the title. -
Django, JS/JQuery validate inputs and disable submit button
I have a simple input params that are required. I want to disable my submit button until all the required fields are satisfied. Granted I am new to django, and the particular code I am working on is very old. As a result, post like this or this are not helping. Current code that I am trying from one of the posts linked and including my own template <script type="text/javascript"> $(document).ready(function() { validate(); $('input').on('keyup', validate); }); function validate() { var inputsWithValues = 0; // get all input fields except for type='submit' var myInputs = $("input:not([type='submit'])"); myInputs.each(function(e) { // if it has a value, increment the counter if ($(this).val()) { inputsWithValues += 1; } }); if (inputsWithValues == myInputs.length) { $("input[type=submit]").prop("disabled", false); } else { $("input[type=submit]").prop("disabled", true); } } $('#submit').on('click', function() { var zip = $('#zip').val(); var email = $('#email').val(); var name = $('#name').val(); //if inputs are valid, take inputs and do something }); <form class="form-horizontal" action="" method="get" id="dataform"> <div class="form-group"> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-3"> <input class="col-md-12" id="zip" type="text" placeholder="Enter zip code" aria-required="true"> </div> <div class="col-md-3"> <input class="col-md-12" id="name" type="text" placeholder="Enter last name" aria-required="true"> </div> <div class="col-md-3"> <input class="col-md-12" id="email" type="email" placeholder="Enter email address" aria-required="true"> </div> </div> </div> … -
Celery inspect queries hang forever
I have a dockerized celery implementation with redis as broker. Currently I only run one worker instance for celery. To monitor celery, I also added flower docker service but I am unable to monitor as the request times out. Upon looking into things I found that my celery inspect queries are simply non responding. They hang forever. Now, I think there is an underlying issue with my celery-redis setup. I am unable to inspect anything, when I try to add a task for background processing they are getting stuck upon the calling statement itself. Its all behaving weird. Versions: celery 4.0.2 redis 5.0.0 Currently, I am unable to debug in any capacity. Any help is gladly appreciated. -
open edx insights configuration error: No module named mechanize
I am trying to configure open edx insights on my ubuntu instance. I have been following steps from: https://openedx.atlassian.net/wiki/spaces/OpenOPS/pages/43385371/edX+Analytics+Installation Installation works fine till step 5, After that when I tried to run CourseEnrollmentEventsTask, getting below error remote-task --host localhost --user ubuntu --remote-name analyticstack --skip-setup --wait CourseEnrollmentEventsTask --local-scheduler --interval 2018 --verbose --override-config /home/ubuntu/edx-analytics-pipeline/config/devstack.cfg --n-reduce-tasks 8 edx-analytics-pipeline/marker/-4077723021222861505-temp-2018-10-23T16-46-24.874897 2018-10-23 16:46:28,981 INFO 25647 [luigi-interface] hadoop.py:339 - 18/10/23 16:46:28 WARN streaming.StreamJob: -file option is deprecated, please use generic option -files instead. 2018-10-23 16:46:31,823 INFO 25647 [luigi-interface] hadoop.py:339 - 18/10/23 16:46:31 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032 2018-10-23 16:46:32,152 INFO 25647 [luigi-interface] hadoop.py:339 - 18/10/23 16:46:32 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032 2018-10-23 16:46:34,331 INFO 25647 [luigi-interface] hadoop.py:339 - 18/10/23 16:46:34 INFO mapred.FileInputFormat: Total input paths to process : 211 2018-10-23 16:46:35,220 INFO 25647 [luigi-interface] hadoop.py:339 - 18/10/23 16:46:35 INFO mapreduce.JobSubmitter: number of splits:211 2018-10-23 16:46:35,241 INFO 25647 [luigi-interface] hadoop.py:339 - 18/10/23 16:46:35 INFO Configuration.deprecation: mapred.job.name is deprecated. Instead, use mapreduce.job.name 2018-10-23 16:46:35,242 INFO 25647 [luigi-interface] hadoop.py:339 - 18/10/23 16:46:35 INFO Configuration.deprecation: mapred.reduce.tasks is deprecated. Instead, use mapreduce.job.reduces 2018-10-23 16:46:35,401 INFO 25647 [luigi-interface] hadoop.py:339 - 18/10/23 16:46:35 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1540309647275_0006 2018-10-23 16:46:35,720 INFO 25647 [luigi-interface] hadoop.py:339 - 18/10/23 16:46:35 INFO … -
Development vs. Production Media Location in Django
I'm working on user-uploaded files with Django. I often this this in various articles: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^file/', include('file_app.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Which implies that if DEBUG is on and you're developing, then add the MEDIA_URL path to urlpatterns so it's accessible. So what is the appropriate way to store files in a production environment and why isn't this method suitable in production? -
Python requests POST don't contain all sended data
I'm trying to create new order on PayU, via their REST api. I'm sending "get access token", and i have correct answer. Then i send 'create new order', aaaaand i ve got 103 error, error syntax. I was trying on https://webhook.site/ , and realized why syntax is bad - i have no values in list. Code of sending POST, when creating new order: data = { "notifyUrl": "https://your.eshop.com/notify", "customerIp": "127.0.0.1", "merchantPosId": "00000", "description": "RTV market", "currencyCode": "PLN", "totalAmount": "15000", "products": [{ "name": "Wireless mouse", "unitPrice": "15000", "quantity": "1"}]} headers = { "Content-Type": "application/json", "Authorization": str('Bearer ' + access_token).encode()} r = requests.post('https://webhook.site/9046f3b6-87c4-4be3-8544-8a3454412a55', data=payload, headers=headers) return JsonResponse(r.json()) Webhooc show what i have posted: customerIp=127.0.0.1&notifyUrl=https%3A%2F%2Fyour.eshop.com%2Fnotify&currencyCode=PLN&products=name&products=unitPrice&products=quantity&description=RTV+market&merchantPosId=00000&totalAmount=15000 There is no values of 'name', 'unitprice' and 'quantity'. PayU confirmed thats the only problem. Why? What is wrong? Sending simple POST request to get a token is always successful. -
Getting data to a js file from py file
This is my python code.This code is for shuffle players according to their association. The output of this code is a shuffled list of players. players1 =[['1','asso1','name1'],['2','asso1','name2'],['3','asso1','name3'],['4','asso1','name4'],['5','asso1','name5'],['6','asso2','name6'],['7','asso2','name7'],['8','asso2','name8'],['9','asso2','name9']] d = dict() for player in players4: if player[1] in d: d[player[1]].append([player[0],player[2]]) else: d.setdefault(player[1],[]) d[player[1]].append([player[0],player[2]]) newList =[] while (d!={}): for asso in d.keys(): newList.append(d[asso][0]) d[asso].remove(d[asso][0]) if(d[asso]==[]): del d[asso] if(d=={}): break print newList This is my Jquery code. This code use a list named participants and make a draw. var $tournament = $('.tournament'), $bracket = $('<ul class="bracket"><li></li><li></li></ul>'); var participants = ['Jeewantha','Chamoda','Adam', 'Matt', 'Evan', 'Abby', 'Heather', 'Christina', 'Ryan', 'Tyler', 'Steve', 'Steph', 'Jenna', 'Derek', 'Mike', 'Sam']; function buildBracket($el, p1, p2) { if(!p1 && !p2) { $el.append($bracket.clone()); } } buildBracket($tournament); var level = 0, section = 0, $brackets, $previousBrackets; while(level < 4) { $brackets = $('.bracket'); $brackets = $brackets.filter(function(i, el) { if($previousBrackets) { if($.inArray(el, $previousBrackets) >= 0) { return false; } } return true; }); if(!$previousBrackets) { $previousBrackets = $brackets; } else { $previousBrackets = $.merge($previousBrackets, $brackets); } $brackets.each(function() { $(this).find('li:empty').each(function() { buildBracket($(this)); }); }); level++; } function getRivals() { var p1i = Math.floor(participants.length * Math.random()), p1 = participants[p1i]; participants.splice(p1i, 1); var p2i = Math.floor(participants.length * Math.random()), p2 = participants[p2i]; participants.splice(p2i, 1); return [p1, p2]; } function … -
How do I create a filter with AngularJS to show/hide certain items?
I am trying to create a filter to show and hide certain items in my list. I already have two filters set but I can't seem to get this one working. As you can see I had some help with the others but this help is no longer with me. I am running AngularJS. So far, I have the following: 1) To show and hide prices. <h4 class="pl_header">Hidden Prices</h4> <ul class="price_list_filter"> <li> <label> <span>Show</span> <input type="checkbox" class="faChkSqr pull-right" ng-model="filter_hi" value="Hi" ng-change="hidden_show()"> </label> </li> 2)Added it into my body. <tbody ng-repeat="price_level in price_levels | orderBy:propertyName:reverse | filter:filterByCategory | filter:filterByType | filter:searchSKU | filter:filterByHide" ng-style="{ 'background-color' : (price_level.buyer) ? 'lightgray' : 'white' }"> 3) My javascript. $scope.hidden_show = function() { $scope.UIfilterby.hide = []; if($scope.filter_hi == false){ $scope.UIfilterby.hide.push("Hi"); } $scope.UIfilterby.hide = $scope.UIfilterby.hide.join(); } and $scope.filterByHide = function(price_level){ if($scope.UIfilterby.hide){ return ($scope.UIfilterby.hide.indexOf(price_level.hidden) !== false); }else{ return {}; } } I followed similar structures to the other two filters, one was filter by category and the other as by type. Maybe I need to add it to my filters.py in django? I am new to this, any help would be appreciated. Thank you. -
How to track Daily Active Users in Django?
In a simple Django Web App, is there an easy way to track Daily Active Users? Or am I well served by creating a couple of new Models and doing the record keeping on my own? class DailyActivity(models.Model): date = models.DateField() user_active = models.OneToOneField(User) class DailyActiveUsers(models.Model): date = models.DateField() daily_active_users = models.IntegerField() -
ConnectionClosedError when uploading file to Amazon S3 in Django
I am using boto3 and django-storages to perform a file upload to Amazon S3, but I can't get it to work, it always end up with a ConnectionClosedError, but when I upload a file using the django admin interface, it works and I see the file uploaded in my Amazon S3 bucket. I have tried to find a solution to it but no success yet, what can possibly be wrong ? Here is my html <form method="post" action="{% url 'upload-document' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <label for="description">Description</label> <input id="description" type="text" name="description" value="{{ form_details.description }}" required> </div> <input name="document_type" type="hidden" value="{{ document_type|cut:" " }}"> <input name="document_type_id" type="hidden" value="{{ document_type_id }}"> <div style="margin-top: 20px;" class="form-row"> <label for="file">File</label> <input id="file" accept=".pdf" type="file" name="document_file" required> </div> <button style="margin-top: 20px; width: 100%;" class="button primary" type="submit">UPLOAD</button> </form> View code performing upload description = request.POST['description'] document_type = request.POST['document_type'] document_type_id = request.POST['document_type_id'] document = Document.objects.create(description=description, document_type=document_type) document_file = request.FILES['document_file'] document.document_file = document_file if document_type_id != 0: document.document_type_id = document_type_id document.save() and below is my Amazon S3 config file AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = False DEFAULT_FILE_STORAGE = 'app.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'app.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'mybucketname' S3DIRECT_REGION = 'eu-west-2' S3_URL = '//%s.s3.amazonaws.com/' % … -
How to let Django filter one word with two combined words?
The below codes are for the search function in my website. Let's say there is a business name, "Los Angeles", and I want to get the location with the search text, "Losangeles". Since I don't have any criteria to decide "Losangeles" is actually two words, I can't figure out how it can be filtered. With the below codes, if I type "los", "angeles", or "los angeles" as search_text, it finds "Los Angeles", but "losangeles" can't. Is there any way to let me do that in Django views? class SearchListView(ListView): def get_queryset(self): search_text = self.request.GET.get('search_text') if search_text: search_stores = Store.objects.filter(location__icontains=search_text) return search_stores.filter(status='active') -
How to access graph which is present in views.py file into html templates in djangi
I have a views.py file as follows Def showimage(request): # Construct the graph t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) plot(t, s, linewidth=1.0) xlabel('time (s)') ylabel('voltage (mV)') title('About as simple as it gets, folks') grid(True) buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() Could u please me to pass that graph into html page???