Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
views from another app doesnt work in django?
I have two apps 1. posts 2. boards. I need to create url link in boards template to view from posts app. my root urls.py: urlpatterns = [ url(r'^', include('boards.urls')), url(r'^', include('posts.urls', namespace="posts")), ] posts.urls: # -*- coding: utf-8 -*- from django.conf.urls import include, url from views import ( listofposts, create_post, detail, update_post, category, ) urlpatterns = [ url(r'^create/', create_post , name='create_post'), url(r'^category/(?P<slug>[-\w]+)/$', category, name='category'), url(r'^(?P<slug>[-\w]+)/edit/$', update_post, name = 'update_post'), url(r'^(?P<slug>[-\w]+)/$', detail, name = 'detail'), url(r'^$', listofposts , name='listofpost'), ] Boards template link <a class="navbar-brand" href="{% url 'posts:listofposts' %}">Home</a> I got the mistake : Exception Value: Reverse for 'listofposts' not found. 'listofposts' is not a valid view function or pattern name. -
Sum of fields for filtered queryset using django_filters
I have the following view class AuthorList(FilterView): model = Author filterset_class = AuthorFilter context_object_name = 'authors' In the template, one of the field is {{ author.value }}, which is an integer. What I would like to do is to show the sum of all {{ author.value }} in my template, but in a dynamic way (if some filters are used, the sum is updated with the current Queryset). I have tried adding extra context with get_context_data but I couldn't find out how to make it in a dynamic way. -
django + nginx https redirect shows (414 Request-URI Too Large)
I am trying to solve nginx redirect to https but when I use www.ozkandurakoglu.com I am getting 414 Request-URI Too Large error. Here is my settings for nginx: upstream ozkan_server { server unix:/home/ytsejam/public_html/ozkansimple/run/gunicorn.sock fail_timeout=10s; } server { listen 80; server_name ozkandurakoglu.com www.ozkandurakoglu.com; return 301 $scheme:https://ozkandurakoglu.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; ssl on; ssl_certificate /etc/letsencrypt/live/ozkandurakoglu.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/ozkandurakoglu.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/ozkandurakoglu.com/chain.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_prefer_server_ciphers on; add_header Strict-Transport-Security max-age=15768000; ssl_stapling on; ssl_stapling_verify on; server_name www.ozkandurakoglu.com; return 301 $scheme:https://ozkandurakoglu.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; ssl on; ssl_certificate /etc/letsencrypt/live/ozkandurakoglu.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/ozkandurakoglu.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/ozkandurakoglu.com/chain.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_prefer_server_ciphers on; add_header Strict-Transport-Security max-age=15768000; ssl_stapling on; ssl_stapling_verify on; server_name www.ozkandurakoglu.com ozkandurakoglu.com; client_max_body_size 4G; root /home/ytsejam/public_html/ozkansimple/; access_log /home/ytsejam/public_html/ozkansimple/logs/nginx-access.log; error_log /home/ytsejam/public_html/ozkansimple/logs/nginx-error.log warn; large_client_header_buffers 6 16k; ... } can you help me ? Thanks -
request.user is not letting me make changes to the current user?
In my view function, I'm trying to make 2 modifications to the current user; consider him a premium subscriber by marking model field is_premium_subscriber as True and adding him to a group named Premium Agents. However the changes don't seem to be registering in my views.py! Here is my code: def payment_response(request): new_charge = PremiumSubscriptionCharge() if request.method == "POST": ... Some code here try: ... lots of code here new_charge.agent = request.user # This line is working fine, meaning request.user is properly assigned to the current user request.user.is_premium_subscriber = True # This is not working, is_premium_subscriber is still false after the request premium_agent_group = Group.objects.get(name='Premium Agents') premium_agent_group.user_set.add(request.user) # This is not working either, the current user does not get added to the group. request.user.save() # I don't know if this is necessary, but I put it here just in case. except stripe.error.CardError as ce: ... some code else: ... some code My user model for reference. I created a custom User model by inheriting AbstractUser... could this have caused the issue? class Agent(AbstractUser): is_premium_subscriber = models.BooleanField(default=False) -
Get the matched url pattern on Django
I am working on an existing Django application where there are many url patterns with same name. For example these three url patterns have same url name / view method: url(r'^create/type/(?P<negotiation_type>.*)/(?P<infomodel_uuid>.*)/$', 'setup_negotiation', name='setup_negotiation'), url(r'^create/type/(?P<negotiation_type>.*)/$', 'setup_negotiation', name='setup_negotiation'), url(r'^create/(?P<processmodel_uuid>.*)/$', 'setup_negotiation', name='setup_negotiation'), I want to know which pattern current url is matched with. I can get named url from resolve(request.path_info).url_name but what I need is to get the matched pattern string '^create/(?P<processmodel_uuid>.*)/$' or something like that. -
Website not sending any data : ERR_EMPTY_RESPONSE unreliably.
I have a (Https) website running with django 1.17.11, nginx 1.4.6 and gunicorn 19.7.6. Yesterday my website seemed to be running correctly, but since today it's displaying an error. It is inconsistent but this is what appears to be happening. First time, the site will load without problem. Upon refresh, or while navigating to another page on the website, the site will either load or display {my-site} didn’t send any data. ERR_EMPTY_RESPONSE Once a page display ERR_EMPTY_RESPONSE once, it will consistently display this error. Even though the homepage might display the error, a different page could still be working. (E.g. site.com doesn't work, but site.com/a does work) This is happening in Chrome and Firefox (haven't tested in other browsers) This happens on windows 10, Ubuntu 14.04 and Android Oreo (only ones tested) There do not appear to be any additional errors, nor anything related reported in the error logs. Does anybody know what this could be related to? Or any additional tests I could run to try to get at least an consistent error? Any possible fixes? -
Django query join with another query on the same table
I have a model like this: class mymodel(models.Model): user1 = models.CharField(max_length=255, null=True, blank=True) user2 = models.CharField(max_length=255, null=True, blank=True) paid = models.FloatField(default=0) reason = models.CharField(max_length=150, choices=REASON_NAMES, null=True, blank=True) and I have two queries like this: users_trx1 = mymodel.objects.values('user1').annotate(r1_c=Count( Case( When(reason='REASON1', then=1), output_field=IntegerField() ) )).annotate(r2_c=Count( Case( When(reason='REASON2', then=1), output_field=IntegerField() ) )).order_by('user1') The second query gets the sum paid to user2: users_trx2 = mymodel.objects.values('user2').annotate(r1_s=Sum( Case( When(reason='REASON1', then='paid'), default=0.0, output_field=FloatField() ) )).annotate(r2_s=Count( Case( When(reason='REASON2', then='paid'), default=0.0, output_field=FloatField() ) )).order_by('user2') Now I need a way to left join the two queries. Meaning, that I need a new query that will get me in each row: (user1, r1_c, r1_s, r2_c, r2_s). I need the join to get user2 values from users_trx2 query that match user1 from users_trx1 query. I'm using Django 1.11 with mysql backend -
Iterate JSON in a django template
I have a json coming from a view in below format , [ { "model":"booking.bookeditem", "pk":192, "fields":{ "Booking_id":155, "hoarding":9, "date_from":"2017-11-21", "date_until":"2017-12-06", "price_net":"34500", "created":"2017-11-07T11:35:49.675Z" } } ] I need to iterate through this json and print it in the template.Actually, I want to create an invoice email for the user after booking is performed for that I passed bookeditems as context to email templates. Here is the view to create booking, views.py : def create_order(request,checkout): booking = checkout.create_order() if not booking: return None, redirect('cart:index') checkout.clear_storage() checkout.cart.clear() bookingitems = BookedItem.objects.filter(Booking_id=booking.pk) booking.send_invoice_email(booking,user,bookingitems) return booking, redirect('home') Function to send invoice email, def send_invoice_email(self,booking,user,bookingitems): customer_email = self.get_user_current_email() data = serializers.serialize('json',bookingitems) subject ="invoice" ctx = { 'hoardings':data } send_invoice.delay(customer_email, subject, ctx) and i'm using celery&django EmailMessage to sending invoice email. task.py: @shared_task(name="task.send_invoice") def send_invoice(customer_email, subject, ctx): to=[customer_email] from_email = 'example@gmail.com' message = get_template('email/invoice_email.html').render(ctx) msg = EmailMessage(subject,message,to=to,from_email=from_email) msg.content_subtype = 'html' msg.send() I tried this : {% for i in hoardings %} <tr> <td>{{ i.pk }}</td> </tr> {% endfor %} But it is not working , and the loop are iterating for each and every string. Where am i going wrong in the iteration? Please help.. -
django one queryset for two tables ( one to many related )
I have created one to many relationship ( two tables ) in this way that every user has it's own ip connections list - every user has many connections. It looks as shown below: class Conn(models.Model): src_ip = models.CharField(max_length=18, unique=False,default=None,blank=True,null=True) src_port = models.CharField(max_length=6, unique=False,default=None,blank=True,null=True) dst_ip = models.CharField(max_length=18, unique=False,default=None,blank=True,null=True) dst_port = models.CharField(max_length=6, unique=False,default=None,blank=True,null=True) proto = models.CharField(max_length=6, unique=False,default=None,blank=True,null=True) start_data = models.CharField(max_length=18, unique=False,default=None,blank=True,null=True) r_user = models.ForeignKey(User, on_delete=models.CASCADE) class User(models.Model): e_user = models.CharField(max_length=15, unique=False,default=None,blank=True,null=True) e_dev = models.CharField(max_length=15, unique=False,default=None,blank=True,null=True) e_session = models.CharField(max_length=9, unique=False,default=None,blank=True,null=True) e_start = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True) e_stop = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True) e_summary = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True) e_ip = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True) I'm trying to get all Users with their connections ( Conn ) in one queryset and then display everything in template. So far I can display every User without any problems with q=Users.objects.all() and passing queryset to template. The question may be a bit not smart but how can I query all Users table including related connections ( Conn ) as one queryset ant then enumerate this connections in a form ? Thank you in advance -
url pattern matching string parameter with space
I had problem matching URL pattern with a regular expression in Django. urlpattern: url(r'^search/(?P[\w\s ]+)/$',views.specs, name='spec'), url I am trying to match: /search/%20Iphone7%20jet%20black/ the title is something like this " iPhone 7 jet black" Thanks in advance. -
My datatable has a button per row and I want to perform a filter (with the selected data) in another table when I click. How can I do that in Django?
I am testing a application that has 2 datatables. I am using django_tables2 and django_filter The first, has one button per row, and when it is clicked it extracts a content from the second column of its row. I want to use this data to apply a filter request in a second datatable which is displayed in the same page. As it is a large ammount of data it should be a new request instead of load everything and manipulate it using javascript. I am quite lost.. How could I do that??? Please any help?? Table.py class MyColumn(tables.Column): empty_values = list() def render(self, value, record): return mark_safe('<button id="%s" class="btn btn-info">Submit</button>' % escape(record.id)) class AdTable(tables.Table): submit = MyColumn() class Meta: model = Ad attrs = {'class': 'table table-striped table-bordered table- hover','id':'id_ad'} class PtTable(tables.Table): class Meta: model = Pt attrs = {'class': 'table table-striped table-bordered table- hover','id':'id_pt'} HTML <body> <div> <h1> "This is the Table" </h1> </div> <div> <table> {% render_table ad_table %} </table> </div> <div> {% block content %} <div> <form method="get"> {{ form.as_p }} <button type="submit">Search</button> </form> </div> {% endblock %} </div> <div> <table> {% render_table pt_table %} </table> </div> <script> $(document).ready(function(){ $('#id_ad').DataTable(); $('#id_ad').on('click','.btn',function(){ var currow = $(this).closest('tr'); var result … -
want to customise django cms forms using custom styling
I'm following this tutorial (https://pypi.python.org/pypi/djangocms-forms/) to create custom forms with django-forms in this tutorial, Essentially, I want to know how to define my own "FORM TEMPLATE" for this plugin.I want to include my own styling and post requests too. Thank you -
How do i get content_type of a file
I am creating a file. I sent base64 string as an argument. This is my code: def save_file(request_data): """ """ data = base64.b64decode(request_data.get('file')) file_type = imghdr.what('', h=data) if file_type not in ['pdf', 'txt', 'xls', 'xlsx', 'html']: return ({"msg": "Upload a valid file. The file you uploaded is not acceptable"}, 400) file = tempfile.TemporaryFile() file.write(data) file_size = os.fstat(file.fileno()).st_size name = str(file.name)+"."+str(file_type) content_type = magic.from_file(name, mime=True) uploaded_file = InMemoryUploadedFile(file=file, field_name='path', name=name, content_type=content_type, size=file_size, charset='utf-8') UploadedFile.objects.create(path=uploaded_file, name=request_data.get('name'), meta_info=request_data.get('meta_info', '{}'), status=request_data.get('status', 'I')) file.close() return ({"msg": "File created successfully"}, 200) and I am getting this error: File does not exist: 32.jpeg at this line: content_type = magic.from_file(name, mime=True) Does anyone know how to get content type from base64 string? -
Duplicate Data issue for admin inlines with slug field
I have a main model that includes a submodel in the django admin as a TabularInline. The submodel has a slug field that automatically slugifies the name field if left blank. This slugify function is called in the submodel's save(). The problem is if I try to add multiple new submodel entries and leave the slug field blank the form's verification checks deny the submission because the slug field requires unique values. How do I fix the admin so it doesn't throw this duplicate data error for multiple blank slug fields? -
django: custom RelatedManager on GenericForeignKey
Let there be models: class Author(models.Model): name = models.CharField(max_length=100) comments_on_works = ?? class Book(models.Model): title = models.CharField(max_length=100) year_published = models.IntegerField() author = models.ForeignKey('Author', on_delete=models.CASCADE) class Article(models.Model): title = models.CharField(max_length=100) abstract = models.CharField(max_length=500) author = models.ForeignKey('Author', on_delete=models.CASCADE) class Comment(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) body = models.CharField(max_length=500) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') So that: Book and Article cannot be coerced into one model Comment can be made on either Book or Article - thus the GenericForeignKey Comment cannot be divided into BookComment and ArticleComment models Now I would like to have a manager Author.comments_on_works that would get me all comments on author's Books and Articles. How do I do that? -
django migrate error : 'Microsoft OLE DB Provider for SQL Server', "Cannot insert the value NULL into column 'last_login', table
I have installed below versions Django==1.8 django-mssql==1.8 pypiwin32==220 pytz==2017.3 and my setting.py file is as below. ----------------Start of setting.py------------------ INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases """DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }""" DATABASES = { 'default': { 'NAME': 'shetdb', 'ENGINE': 'sqlserver_ado', 'HOST': '127.0.0.1', 'USER': 'sa', 'PASSWORD': 'ppp@123', 'OPTIONS': { 'provider': 'SQLOLEDB', 'use_legacy_date_fields': 'True', 'use_mars': True } } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True -------------------End of setting.py file---------------------------- with these settings , I am not able to create super user/admin for sample application. When i try to createsuperuser using command >python manage,py createsuperuser it asks for username/email and password (2 times) after entering and hitting enter, I am getting below error in console. ---------------------------start----------------------------------------------- Email address: p@123 Error: Enter a valid email address. Email address: p@123.com Password: Password (again): Traceback (most recent call … -
TypeError: array(['cycling'], dtype=object) is not JSON serializable
hi I've made an text classification classifier which i've used in this it is returning me an array and I want to return jsonresponse but the last line of code giving me error 'array(['cycling'], dtype=object) is not JSON serializable' def classify_text(request): if request.method == 'POST' and request.POST.get('text'): test = [] text = request.POST.get('text') text = re.sub('[^a-zA-Z]', ' ', text) text = text.lower() text = text.split() ps = PorterStemmer() text = [ps.stem(word) for word in text if not word in set(stopwords.words('english'))] text = ' '.join(text) test.append(text) pred = cv.transform(test).toarray() pred = svm_model_linear.predict(pred) return JsonResponse(pred, safe=False) -
overriding django form in Forms.modelAdmin
I have a problem overriding a field in my Django form. I have a class for my form: class UserCreationForm(forms.ModelForm): class Meta: model = User fields = ['password', 'services', 'project', 'email', 'name', 'first_name', 'role'] and I want to modify the returned value of services with another value, so I used the get_form function as follows: class UserAdmin(admin.ModelAdmin): exclude = ('uuid',) search_fields = ('email', "project") list_display = ("email", "project", "nb_connexion") form = UserCreationForm def get_form(self, request, obj=None, **kwargs): if obj != None: print(obj.name) print(request) form = super(UserAdmin, self).get_form(request, obj=obj, **kwargs) form.base_fields['services'].initial = Service.objects.filter(projects=obj.project) return form but I'm still getting the original results which is all the services from all the projects. I want to get just the services of one project. I tried all the possible solutions. Need help; thank you. -
Can I use django for object oriented calculations like Java?
I'm coming from Java so I am used to performing calculations I require in separate functions. I would like to know if the below code makes sense in my Django model especially the loop and calling functions from within functions. Thanks. class L3(models.Model): user = models.ForeignKey(User, related_name="L3") MachineID = models.CharField(max_length=256) TimeOnline = models.DateTimeField() Commission = models.IntegerField(default='10') TimeOffline = models.IntegerField(default='0') def indivMachineHoursWorked(self): this_month = datetime.now().month if self.TimeOnline == this_month: x = datetime.now() - self.TimeOnline else: x = datetime.now() - datetime.today().replace(day=1) #need to update hour to 0 too i.e. start of month return x def totalMachineHoursWorked(self): L3_total = L3.objects.all() hrs=0 for l3 in L3_total: hrs =+ l3.indivMachineHoursWorked() return hrs def btcToHour(self): main_api = 'https://api.nicehash.com/api?method=balance&id=513396&key=48730a3c-bfab-bcde-f6c1-1d7750c0e9fe' url = main_api json_data = requests.get(url).json() print(json_data) balance1 = json_data['result']['balance_confirmed'] print(balance1) btc2hour = balance1/self.totalMachineHoursWorked() return btc2hour def indivMachineTurnover(self): return self.indivMachineHoursWorked()*self.btcToHour() def __str__(self): return self.user.get_full_name() -
External Javascript file returning 404 error in django
<head> <!-- Include Google Maps JS API --> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/?key=my-KEY&sensor=true"> Each time I call the view up the other html element show but the google map is not displayed. the console reveals a GET https://maps.googleapis.com/maps/api/?key=KEY&sensor=true 404 () PLS how will I load an external js in django? -
Implementing Django Model for existing MongoDB diagram
can you help me to implement django model for this mongo schema? enter image description here -
Django Python on a Mac via pip and HomeBrew - Getting Started
I am trying to get started with Python Web Programming with Django, so I installed pip first (via HomeBrew) and now the latest version of Django, but the following happens, which I have no idea what is wrong or what I should do next. Could someone please help me understand what is going on + what I need to do + what commands I should issue to resolve this, etc...? $ pip --version pip 9.0.1 from /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg (python 2.7) $ pip install Django==1.11.7 Collecting Django==1.11.7 Downloading Django-1.11.7-py2.py3-none-any.whl (6.9MB) 100% |████████████████████████████████| 7.0MB 184kB/s Requirement already satisfied: pytz in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from Django==1.11.7) Installing collected packages: Django Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/django' -
answering user from dictionary django 1.9
I am a beginner in python programming and I want to answer user's input from my dictionary. This is my views.py file from django.shortcuts import render answer = {'Hi': 'Hello!', 'How are you?': 'I am fine'} def index(request): return render(request, 'answer/index.html', answer) def detail(request): return render(request, 'answer/detail.html') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^answer$', views.detail, name='detail'), ] index.html <form type="get" action="." style="margin: 0"> <input id="search_box" type="text" name="search_box" placeholder="Search..." > <button id="search_submit" type="submit" >Submit</button> {% if question in answer.items %} <a href="{% url 'answer:result' %}"></a> {% endif %} </form> When I put something from the server in submit box, I get the same page but '?search_box=Hi' this is added in the url. How can I respond? I have to add another template 'detail.html' but i don't know what should i put in it. If you answer this question, write an explanation too, please. -
how to read data from one DB and write to another using django router or any other way
i am new to django , here is my settings and i am following this(https://docs.djangoproject.com/en/dev/topics/db/multi-db) routing but this is not for read from other and write in another DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'default', 'USER': 'defaultadmin', 'PASSWORD': 'adminpass' }, 'users': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'users', 'USER': 'usersadmin', 'PASSWORD': 'adminpass' } } DATABASE_ROUTERS = ['DBrouting.default_db_router.default_db_router', 'DBrouting.users_db_router.users_db_router'] -
Convert datetime format within ListView
I attempt to change the displaying format of datetime in template, Here is my Codes in views.py: class RestaurantListView(LoginRequiredMixin, ListView): def get_queryset(self): return RestaurantLocation.objects.filter(owner=self.request.user) Codes in template: <ul> {% for obj in object_list %} <li>{{ obj.city }},{{ obj.location }} {{ obj.category }}</li> <li>FirstVisit: {{ obj.visited }}</li> <br> </ul> Browser displays the datetime: FirstVisit: Sept. 9, 2015, 3:08 p.m. I intend to convert to: FirstVisit: 2015-09-09 3:08 p.m. So I import datetime in views.py and format datetime object in template, <li>FirstVisit: {{ obj.visited.strftime('%Y-%m-%d %I:%M %p') }}</li> It reports error: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '('%Y-%m-%d %I:%M %p')' from 'obj.visited.strftime('%Y-%m-%d %I:%M %p')' How to change the format of datetime in template?