Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Writing multiple page pdf from html template using weasy print and django
Hi am generating PDF's from html template containing a table which number of rows vary, problem is when the rows are in excess of certain number(12) the rest of the rows plus the footer are pushed further below and don't appear in the generated pdf.How can I make it dynamic so that extra info is pushed to new page each having atleast a certain number of rows, or is there a way weasy print to move data to another page if the current is full So far I have page breaks on the template but it has worked. {% for record in data %} <tr> <td> {{ record.id}}</td> <td> {{ record.date}}</td> </tr> {% if forloop.counter|divisibleby:12 %} <div style="page-break-after: always;"></div> div style="page-break-before: always;"></div> {% endif %} {% endfor %} -
How to allow page refresh/redirect after Ajax POST submission (of Django form)
I'm a client-side newbie learning the ropes, and need to clarify Ajax concepts. e.preventDefault(); is a typical method of preventing form submission (page refresh) in JS. One use case where the above is handy is Ajax-based form submission. Sample code is: function overwrite_default_submit(e) { // block the default behavior e.preventDefault(); // create and populate the form with data var form_data = new FormData(); form_data.append("reply", text_field.value); // send the form via AJAX var xhr = new XMLHttpRequest(); xhr.open('POST', e.target.action); xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken')); xhr.send(form_data); } I have two questions: 1) Imagine the POST request is being sent to a function that ends with a redirect to a different URL. For example, I use Django to develop web applications; a typical Django view may end up with return redirect("home") where home is the home page of the said app. In such a scenario, how does preventDefault() prevent the redirect statement in server-side code from executing? I'm trying to understand the exact mechanics behind it. 2) What if one wanted page refresh (or redirect) to proceed normally after an Ajax POST request? What tweaks need to be made? Would love to see an illustrative example to clarify my concepts. I'm well-versed in Django (Python) so … -
In ModelSerializer self.context doesn't have request , how to get this
my serialiser class is: class NakshatraDateSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) is_note_present = serializers.SerializerMethodField(read_only=True) def get_is_note_present(self, nakshatra_date ): user = None request = self.context.get("request") print (str(request)) if request and hasattr(request, "user"): user = request.user # user = serializers.SerializerMethodField('_user') if user is None: logging.error("user is none") return False try: nakshatra_date_note = Notes.objects.all().get(nakshatra_date=nakshatra_date, created_by=user) except ObjectDoesNotExist: nakshatra_date_note = None if nakshatra_date_note is None: logging.error("no note present for this nakshatra date") return False logging.error(str(nakshatra_date_note)) return True vewclass is : class NakshatraDateViewSet(viewsets.ModelViewSet): """ Nakshatra dates """ permission_classes = (AllowAny,) queryset = NakshatraDate.objects.all() serializer_class = NakshatraDateSerializer() pagination_class = LargeResultsSetPagination filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) filter_class = NakshatraDateFilter def filter_queryset(self, queryset): queryset = super(NakshatraDateViewSet, self).filter_queryset(queryset) return queryset.order_by('-id') def perform_create(self, serializer): serializer.save() i am trying to set value 'True' in variable is_note_present if a Note is present on a particular date. or else 'False'. But i am not able to get request object in self.context. class Notes(models.Model): date = models.DateField(null=False) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True, editable=False) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notes', on_delete=models.CASCADE) -
Context variables not resolving under template inheritance using global javascript vars
I'm trying to send context variables into my template to be used with javascript. The JS file lives apart from the template, so I'm attempting to declare the global JS vars in the base template first, then use them in the JS file. One of the variables works(myuser), but the other does not(notifications). What's going on? views.py: class NotificationsView(View): def get(self, request, *args, **kwargs): profile = Profile.objects.get(user__username=self.request.user) notifs = profile.notifications.unread() return render(request, 'base.html', {'notifs': notifs}) base.html: ... {% include "landing/notifications.html" %} <script src="{% static 'js/notify.js' %}" type="text/javascript"></script> {% register_notify_callbacks callbacks='fill_notification_list, fill_notification_badge' %} landing/notifications.html: <script type="text/javascript"> var myuser = '{{request.user}}'; var notifications = '{{notifs}}'; </script> notify.js: ... return '<li><a href="/">' + myuser + notifications + '</a></li>'; }).join('') } } -
i am using Centos6.9 and if I run the command$python manage.py runserver in get the below error
(djangoenv)[rapidbox@instance-1 trusource]$ python manage.py runserver Unhandled exception in thread started by <function wrapper at 0x7f86b5afad70> Traceback (most recent call last): File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_las t_exception six.reraise(*_exception) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/opt/rh/python27/root/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 52, in <mod ule> class AbstractBaseUser(models.Model): File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/db/models/base.py", line 330, in add_to_clas s value.contribute_to_class(cls, name) File "/home/rapidbox/djangoenv/lib/python2.7/site-packages/django/db/models/options.py", line 214, in contribu te_to_class -
django RequestFactory loses url kwargs
I am trying to switch from using Django Test Client to RequestFactory to speed up my tests. However, requests generated by RequestFactory do not supply proper kwargs to views. Example: this is my view class SomeView(View): def get(self, request, *args, **kwargs): return JsonResponse({'your kwargs': str(kwargs)}) with urlconf url(r'^some_view/(?P<some_kwarg>[\-0-9a-fA-F]+)/$', views.SomeView.as_view(), name='some_view'), and two tests: def test_different_kwargs(): c = Client() response = c.get( reverse('bots:some_view', kwargs={'some_kwarg': '12345'}), ) print('\n\nResponse for TestClient: ', response.content.decode()) rf = RequestFactory() request = rf.get( reverse('bots:some_view', kwargs={'some_kwarg': '12345'}), ) response = SomeView.as_view()(request) print('\n\nResponse for RequestFactory: ', response.content.decode()) What they produce is: Response for TestClient: {"your kwargs": "{'some_kwarg': '12345'}"} Response for RequestFactory: {"your kwargs": "{}"} So, what's the point of RequestFactory if it loses url kwargs? Or is there a way to put them into the view somehow? -
Is there a way that a Django template include is not silent if it fails for developement
I would like to have the possibility that include templates are not silent when they fail Let me explain.. We have a main template A. We have a template to include B that contains an error. When we include template B, this one will not be displayed because it contains an error even if the template_debug = True, and it looks fine. The fact that fails are silent is convenient for a production environment. However, often on the environment of development this can pose problem insofar we do not see that there is a problem since it does not appear. Even if we can often see the error in the console. Also for the debug it is relatively painful as sometimes we do not know where the error comes from. So my question is: would there be a solution (ex: custom template tag include_noisy, or middleware) for the template include not silentious on local machines, and thus correctly display errors as in a normal template? For sure, the silent is still always present when the template_debug = False Thanks in advance -
Django - displaying images on the page using pyuploadcare
Python, Django, pyuploadcare, html5, jquery, The Django documentations for pyuploadcare are useful for image customization and file uploading and stuff like that, but what they don't tell you is how to display the image in the webpage. For example, i can display the URL where the image is stored, but i cannot display the image itself in the webpage i want to make this as clear as possible to the reader so I'll give another example: To build an image gallery, i would need all the images displayed on one page, i can do that using the for loops for photo in photos Photo and photos are defined in views.py {% extends 'base.html' %} {% for photo in photos %} {{ photo.caption }} {{ photo.photo }} {% endfor %} {% block content %} {% endblock %} photo.caption is an models.CharField() photo.photo is an ImageField() from from pyuploadcare.dj.models import ImageField everything is working properly but i don't know how to display the images on the webpage. Any help would be apreciated -
Django get_model not return parent inheritance
I have the next models: class Parent(models.Model): name = models.CharField() class Child(Parent): number = models.IntegerField() If I do apps.get_model('myapp', 'Child') and for c in Child.objects.all() it will give me the error Cannot resolve keyword 'name' into field. I don't actually need the name field in my migration. How should I use Child without importing it from the model file? -
wagtail 2.0b1 admin static files issue
Updating my wagtail to 2.0b1, I am getting a warning about wagtailadmin static files and no styling is applying to my admin page. ( also when collectstatic command runs no wagtile files are copying ) WARNINGS: ?: (wagtailadmin.W001) CSS for the Wagtail admin is missing HINT: Most likely you are running a development (non-packaged) copy of Wagtail and have not built the static assets - see http://docs.wagtail.io/en/latest/contributing/developing.html File not found: /Users/burakk/BurakWorks/Web/VIRTUAL_ENVIRONMENTS/python3.6.1/src/wagtail/wagtail/admin/static/wagtailadmin/css/normalize.css I have checked the wagtail 2.0b1 folder and there is a 'static_src' folder instead of a folder named 'static'. I have checked the previous stable version's admin folder and there is also a 'static_src' folder so that is not the problem I think? -
django api call from view change time data from get
I have a view where when it call an api, it will save the result get from it. But i want to be able to change the time get from Post method to like +30min or +1hr and save it. In my case, there is a starttime and endtime. But there is only a field time given back. So i will save the time into starttime and time+30min/1hr save into endtime How do i do it ? views @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/makeapp/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/makeapp/', data=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() print(data) # Create a schedule/Save to schedule table user = data['patientId'] userId = MyUser.objects.get(userId=user) # time gettime = data['time'] gettime_add = ??? saveget_attrs2 = { "userId ": userId , "starttime": data["time"], "date": data["date"], } saving2 = Schedule.objects.create(**saveget_attrs2) -
How to show many models in one list in Django Admin?
I have many similar models with different fields, like: # app_one/models.py class AppOne(models.Model): number = models.IntegerField(_('Number'), default=0) ... # app_two/models.py class AppTwo(models.Model): name = models.CharField(_('Name'), max_length=255) ... # app_three/models.py class AppThree(models.Model): is_ready = models.BooleanField(_('Is ready?'), default=False) ... Any way, how to show all of them in Django Admin page into the one list? For example, with model name badge for pretty view. It's would be great solution if you have many similar models, like orders for very different products with different fields, and you want to show and may click to administrate all of them in one place (one list). I use Django 2.x. -
Render Chart from custom template in Django
I am trying to render chart (Echart) from costume template. I have a base where JS librarires included and a block where I want to show my chart. In this block there a many things and I would like to separate my charts via custom templates. According to the Echart example I have to render it. The problem is that I already render my other things that is why i couldn't create an other view which render to the same page. That is why I use custom template.For the simplicity I attach my example code without the base.html. My view: # Source: test/templatetags/test.py from __future__ import unicode_literals import math from django.http import HttpResponse from django.template import loader from pyecharts import Bar from pyecharts.constants import DEFAULT_HOST from monitor.models import Test from django import template register = template.Library() @register.simple_tag def chart(): test_data=Test.objects.all() #Here is my Django query from my databse data=[i['a'] for i in test_data] attr=[i['b'] for i in tropo_data] bar = Bar("Test Chart") bar.add("Test",attr, data, is_stack=True) bar_chart = bar context = dict( myechart=bar_chart.render_embed(), host=DEFAULT_HOST, script_list=bar_chart.get_js_dependencies() ) return context My template: Source test/templates/test/chart.html <!DOCTYPE html> <html> {%load chart%} <head> <meta charset="utf-8"> <title>Proudly presented by PycCharts</title> {% for jsfile_name in script_list %} <script … -
Django form valid even if it doesn't exist in template
I have multiple forms using a single submit button in my template with prefix=name using CrispyForms. Check if a form exists or is rendered in Template. Django I have the following code in my template {% extends BASE_TEMPLATE %} {% load crispy_forms_tags %} {% block title %}<h2>New Thread</h2>{% endblock %} {% block content %} <div class="col-md-6"> <form method="post" accept-charset="utf-8">{% csrf_token %} {{ threadForm|crispy }} {{ postForm|crispy }} {% if SHOW_WIKI %} {{ wikiFrom|crispy }} {% endif %} <input type="submit" class="btn btn-primary btn-sm" value="Submit"/> </form> </div> {% endblock %} The only filed which the WikiForm renders has blank=True. What happens when I do wikiForm.is_valid() in my code is even though it hasn't been shown in template it is valid according to Django. Why does this happen? Is there a way to fix this in a way other than making the field in my wikiForm to blank=False? -
Not able to create table with textField
I have model from cgkapp.validators import validate_number # Create your models here. class Master_Questions(models.Model): Question_Number = models.AutoField(primary_key = True), Question_Text = models.TextField(max_length = 100), Option1 = models.TextField(max_length=50), Option2 = models.TextField(max_length=50), Option3 = models.TextField(max_length=50), Option4 = models.TextField(max_length=50), Answer = models.TextField(max_length=50), Difficulty_Level = models.IntegerField(validators=[validate_number]) and my table is created as below. The textfields are not created. sqlite> .schema cgkapp_master_questions CREATE TABLE "cgkapp_master_questions" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "Difficulty_Level" integer NOT NULL); -
raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet..how to load the apps?
i was trying to run the following command:: python populate_book.py and stuck with this error:: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. The Whole Traceback is as follow:: Traceback (most recent call last): File "populate_book.py", line 6, in <module> from opac.models import Book, BookCopy File "/home/prashant/Desktop/po/opac/models.py", line 6, in <module> from transactions.models import EndUser File "/home/prashant/Desktop/po/transactions/models.py", line 4, in <module> class EndUser(models.Model): File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. settings.py:: # Django settings for cope project. import os DEBUG = True TEMPLATE_DEBUG = DEBUG PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) ADMINS = ( ('pulkit', 'data.pulkit@gmail.com'), ('shashank', 'shashankgrovy@gmail.com'), ('sourabh', 'sourabh.coder@gmail.com'), ('utsav', 'kumaruts@gmail.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'cope.db', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '3306', # Set to empty string for default. } } # Hosts/domain names that are valid … -
react native 0.50.3 authorization header not sent
I am using react-native 0.50.3 to send token authenticated requests to my backend and unfortunately the 'authorization' part of the header is not send by the fetch. My code is the following : async componentDidMount() { var mytoken = await AsyncStorage.getItem('token'); fetch('http://myserver:8000/home', { method: 'GET', headers: { 'Accept': 'application/json', 'Origin': '', 'Content-Type': 'application/json', 'authorization': 'Bearer ' + mytoken } }) .then((response) => response.json()) .then((content) => { this.state.user = content.user; }) .done(); } And on my server side, the wireshark trace shows that the authorization is not in the request header : Hypertext Transfer Protocol GET /home/ HTTP/1.1\r\n Host: 10.150.21.124:8000\r\n Content-Type: application/json\r\n Origin: \r\n Accept: application/json\r\n User-Agent: Expo/2.3.0.1012011 CFNetwork/893.14 Darwin/17.3.0\r\n Accept-Language: en-us\r\n Accept-Encoding: gzip, deflate\r\n Connection: keep-alive\r\n \r\n [Full request URI: http://10.150.21.124:8000/home/] [HTTP request 1/1] [Response in frame: 2326] And of course I get a 401 unhautorized by the server. My backend is a django API with CORS installed and CORS_ORIGIN_ALLOW_ALL = True and ALLOWED_HOSTS = ['*']. The versions of my developments framework elements are the following : npm 4.6.1 node v9.3.0 react-native-cli 2.0.1 Thank you for your help. Alex. -
Binding django and angular 1
I have angular project that binding with django. Angular template has: <script type="text/ng-template" id="document_received_date.html"> <input type="text" ng-model="$parent.model"> </script> Django has domain: class Podgotovka(Activity): fields = [ 'document_recieved_date' ] And model has field "document_recieved_date": document_recieved_date = models.DateField(null=True, default=None) If I edit input the client send http request to django. I don't understand how client send request to django and how model write data to BD. What mechanism do it? Do you have some idea? -
Django - all form select options going to the same page
I have a for loop for select options in my template. The options are displaying correctly, but when I submit they all go to the same page. <div> /* If I take this for loop out then I get a reverse error. I need the dir for the regex. Other methods reverse to the program page using dir. */ {% for function_program in function_programs %} <form action= "{% url 'project:program_page' dir=function_program.program.dir %}" method='post'> {% csrf_token %} {% endfor %} <br> <select id=options name="program"> <option>Choose From List</option> {% for function_program in function_programs %} <option value="{{function_program.program.dir}}"> {{funtion_program_program.name}}</option> {% endfor %} </select><br> <input type="hidden" name="dir" value=" {{function_program.program.dir}}"> <input type="submit" value=" Go to page"> </form><br> </div> urls.py url(r'^program_page/(?P<dir>\d+)$', views.program_page, name='program_page'), url(r'^source/(?P<dir>\d+)$', views.source, name = source') views.py def function_page(request, Function_id): assignments = Function.objects.get(id=Function_id) function_programs = WP.objects.filter(id=Function_id) context = { 'assignments': assignments, 'function_programs' : function_programs, } return render (request, 'project/function.html', context)enter code here def capacity_req(request, dir): info = Program.objects.information(request.POST) return redirect (reverse('project:program_page', kwargs={'dir': dir})) Terminal Using request.POST I get the following in the terminal: <QueryDict: {u'function_program': [u'332456'], u'csrfmiddlewaretoken': [...], u'dir': [u'']}>` /* Page 332456 is the right page for my selection. But the template renders 123408 for all the items on the list. */ Can someone … -
Django Rest Framework import CSV to models
is there any way to import csv file to django rest framework models? Thank You in advance. -
Django segmentation fault
When I try to start 'python manage.py runserver', I endup with 'Segmentation Fault'. I could also notice on repetitive try, sometimes server gets up and running. When I run with 'python -v manage.py runserver', here're the last few lines. `import 'django.core.handlers' # <_frozen_importlib_external.SourceFileLoader object at 0x0000028248BC4C50> # C:\Users\pc\CODE\my_django_env\lib\site-packages\django\core\handlers\__pycache__\wsgi.cpython-36.pyc matches C:\Users\pc\CODE\my_django_env\lib\site-packages\django\core\handlers\wsgi.py # code object from 'C:\\Users\\pc\\CODE\\my_django_env\\lib\\site-packages\\django\\core\\handlers\\__pycache__\\wsgi.cpython-36.pyc' # C:\Users\pc\CODE\my_django_env\lib\site-packages\django\core\handlers\__pycache__\base.cpython-36.pyc matches C:\Users\pc\CODE\my_django_env\lib\site-packages\django\core\handlers\base.pySegmentation fault Please note, I get above error in newly installed Windows 10 machine. With all other same settings, I am able to run this project successfully in another machine running with older windows version. May I know what could be issue in this. -
Rendering validation errors when using Ajax to POST Django form data
How does one generally go about handling validation errors when using Ajax to process POST requests of Django forms? I'm a server-side dev dabbling in a bit of pure JS to learn the ropes. I finished writing AJAX methods to handle the POST request of a Django form, but am now unsure regarding how to render validation errors. For instance, here's a simple Django form: class TextForm(forms.Form): reply = forms.CharField(widget=forms.Textarea(attrs={'cols':30,'class': 'cxl','autocomplete': 'off','autofocus': 'autofocus'})) def __init__(self,*args,**kwargs): super(TextForm, self).__init__(*args,**kwargs) self.fields['reply'].widget.attrs['id'] = 'text_field' def clean(self): data = self.cleaned_data reply = data["reply"].strip() if not reply: raise forms.ValidationError('Write something') elif len(reply) > 1500: raise forms.ValidationError("Can't exceed 1500 chars") return reply And here's how the Ajax request works: function overwrite_default_submit(e) { // block the default behavior e.preventDefault(); // create and populate the form with data var form_data = new FormData(); form_data.append("reply", text_field.value); // send the form via AJAX var xhr = new XMLHttpRequest(); xhr.open('POST', e.target.action); xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken')); xhr.send(form_data); } What's the best pattern to catch and display validation errors under such circumstances? Would love to see an illustrative example of how the experts do it. Note: I prefer pure JS at this point since that's what I'm starting with. JQuery's on my radar, but I'll look … -
django paginator not work well when showing search data
I select datetime to find the data from mysql database,then I use paginator to show my search data. the first page of paginator is right ,but when i click next page ,it will not follow my search data list to show. It shows the second page of whole data list. I have no idea ,please help me ,thanks. The first page of paginator the console shows "GET /blog/create/?csrfmiddlewaretoken=YPVGofXCsTIlZe578CmzzvJ8I5bFQPe3cMniHPQmjugHGNjlz2aVnFZnVvTYPhN8&datetime1=2018-01-16&datetime2=2018-01-31&search= HTTP/1.1" 200 7530" The second page of paginator ,the console shows GET /blog/create/?page=2 HTTP/1.1" 200 7722 I think maybe the wrong url lead the wrong result. but I don't know how to fix it. Here is my views.py from django.template.loader import get_template from django.template import RequestContext from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render,render_to_response from datetime import datetime from .form import DateRangeForm from .models import Post import tkinter.messagebox import logging from tkinter import * from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger # Create your views here. def answer(): showerror("Answer", "Sorry, no answer available") def homepage(request): posts = Post.objects.all() now = datetime.now() context = {'posts':posts,'now':now} return render(request,'jishi.html',context) def showpost(request,times): template=get_template('post.html') ##posts=Post.objects.all().values('customer') posts=Post.objects.filter(pub_date__year=2018) now = datetime.now() html = template.render(locals()) return HttpResponse(html) def foobar(request): if request.method == "GET": posts = Post.objects.all() date_sel1 = request.GET.get('datetime1',None) … -
Can i use DJango web application to connect the SQL database and display the same on Web page?
I have python based script to get emails and transfer it to SQL database and i want to display the same data on we. is it okay to use Django framework to apply the same ? -
Django TypeError when I try to print context in views.py
I use Python 3.6.4. When I try to print the context in a DetailView using this code: class FormularDetailView(DetailView): model = form template_name = "detail.html" def get_context_data(self,**kwargs): print (self.kwargs) context = super().get_context_data(**kwargs) context['formulare'] = form.objects.all() print (context) return context I get this error: File "C:\Victor\Django_CNC\src\formular\views.py", line 44, in get_context_data print (context) File "C:\Victor\Django_CNC\venv\lib\site-packages\django\db\models\base.py", line 513, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) TypeError: __str__ returned non-string (type datetime.date) [02/Feb/2018 09:45:46] "GET /1/ HTTP/1.1" 500 84731 kwargs are printed: print (self.kwargs) {'pk': 1} what am I missing?