Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'ascii' codec can't encode... while uploading csv file
I've got class for uploading my csv files with holidays to my fullcalendar. It looks like this: class UploadVacationsView(APIView): def put(self, request, *args, **kwargs): try: # check file type mime = MimeTypes() url = urllib.pathname2url(request.FILES['file']._name) mime_type = mime.guess_type(url) if 'text/csv' not in mime_type: raise APIException(code=400, detail='File type must be CSV') vacations_list =[] csv_file = StringIO(request.data.get('file', None).read().decode('utf-8')) user_tz = pytz.timezone(request.user.common_settings.time_zone) schedule_file = ScheduleFile.objects.create(user=request.user) instance_hebcal = HebcalService() events = instance_hebcal.process_csv(csv_file, user_tz) And in the other class HebcalService, I've got a method that works with csv files: def process_csv(self, csv_file, user_tz): events = [] csv_input = csv.reader(csv_file.readlines(), dialect=csv.excel) curr_row = 1 start_date = None end_date = None start_name = None holiday_name = '' last_event = {'subject': '', 'date': '', } for row in list(csv_input)[1:]: subject, date, time, _, _, _, _ = row[:7] curr_row += 1 row = [unicode(cell.strip(), 'utf-8') for cell in row] if 'lighting' in subject and not start_date: start_date = user_tz.localize(format_datetime(date, time)) if date == last_event['date']: start_name = last_event['subject'] Everything is ok when working with english holiday's names but when I encounter hebrew names it shots an error: Traceback (most recent call last): File "/home/stas/work/vacation/vmode/apps/marketplaces/base/api/views.py", line 47, in put events = instance_hebcal.process_csv(csv_file, user_tz) File "/home/stas/work/vacation/vmode/apps/marketplaces/base/services/hebcal.py", line 106, in process_csv for … -
bootstrap link is not correct
My web site is not set bootstrap design correctly.I wrote in index.html, <html lang="ja"> <head> <meta charset="utf-8"> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="/static/index.css"> <link rel="stylesheet" href="/static/bootflat/css/bootflat.min.css"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> </head> ・ ・ in settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'bootflat.github.io'), ] When I click href="/static/css/bootstrap.min.css",404 error happens. Directory structure is like -PythonServer -PythonServer -logic -static -index.css -templates -index.html -boolflat.github.io -bower_components I think I set STATIC_URL correctly so I do not know why bootstrap design is not set.What is wrong in my code?How should I fix this? -
('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'app_poll'. (208) (SQLExecDirectW)")
I am getting following while running python django app(using python-odbc-azure lib) on azure web app. ProgrammingError at / ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'app_poll'. (208) (SQLExecDirectW)") Method: GET Request URL: http://retailgenieredsky.azurewebsites.net/ Django Version: 1.11 Exception Type: ProgrammingError Exception Value: ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'app_poll'. (208) (SQLExecDirectW)") Exception Location: D:\home\python354x64\lib\site- packages\sql_server\pyodbc\base.py in execute, line 545 Python Executable: D:\home\python354x64\python.exe Python Version: 3.5.4 Python Path: ['.', 'D:\\home\\python354x64\\python35.zip', 'D:\\home\\python354x64\\DLLs', 'D:\\home\\python354x64\\lib', 'D:\\home\\python354x64', 'D:\\home\\python354x64\\lib\\site-packages', 'D:\\home\\site\\wwwroot'] Server time: Fri, 22 Dec 2017 13:10:47 +0000 Error during template rendering In template D:\home\site\wwwroot\app\templates\app\layout.html, error at line 5 42S02 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>{{ title }} - Django Polls</title> 7 {% load staticfiles %} 8 <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootstrap.min.css' %}" /> 9 <link rel="stylesheet" type="text/css" href="{% static 'app/content/site.css' %}" /> 10 <script src="{% static 'app/scripts/modernizr-2.6.2.js' %}"></script> 11 </head> 12 13 <body> 14 <div class="navbar navbar-inverse navbar-fixed-top"> 15 <div class="container"> I tried following ways. 1. Remove 5 But it given same error for next line. I tried to remove layout.html its still give same error This is deeper level of exception. chunked_fetch False … -
Django server not making changes to CSS
I'm pretty new to Django. I started an app, made template and static directories, add them to the project settings and ran the server by following this tutorial. Then I wanted to change some settings in my CSS file so I modified some lines. But when I ran the python manage.py runserver again(I ran on Windows), the changes did not take effect. The initial code of CSS is: body { position: relative; padding-bottom: 10px; min-height: 100%; background: #f7f7f7; } I changed the padding resulting like this: body { position: relative; padding-bottom: 50px; min-height: 100%; background: #f7f7f7; } When I ran the django server again, the new code was not taking effect. I checked the code with Chrome Dev Tools and found out the padding value was still 10px. I've been running the server again and again but with no change. Is there something I am missing with the settings? -
Show Django template with a camera stream
I'm trying to build a simple website in Python with Django. I want to load and show a template, and then show, on top of the template's background, the images acquired from the webcam for few seconds. Finally, the last image is saved on hard disk. The problem is that the template is loaded and showed only after the camera code finishes. This is the code: from django.shortcuts import render def takePicture(request): l = render(request,'pepper/picture.html') camstream() return l camstream() is the method that activates the stream from the camera, and it works as expected. It uses pygame, following this tutorial. Any suggestion? -
Django 1.9.2: Remove field from model very long
I have more than 2 million objects for the model. When I added a new field, the migration went fast I created another migration where I delete 4 fields - migration hangs for several hours How can I speed up the process? Does it depend on the number of objects? My migration for delete: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('multisession', '0008_add'), ] operations = [ migrations.RemoveField( model_name='mymodel', name='field1', ), migrations.RemoveField( model_name='mymodel', name='field2', ), migrations.RemoveField( model_name='mymodel', name='field3', ), migrations.RemoveField( model_name='mymodel', name='field4', ), ] -
Python decode unknown character
I'm trying to decode the following: UKLTD� For into utf-8 (or anything really) but I cannot workout how to do it and keep getting errors like 'ascii' codec can't decode byte 0xae in position 8: ordinal not in range(128) I'm reading from a csv and have the following: with open(path_to_file, 'rb') as f: reader = csv.reader(f) for row in reader: order = Order( ... product_name = row[11].encode('utf-8'), ... ) order.save() I would be happy right now to just ignore the character if I have keep the rest of the string. -
Django with nginx and gunicorn
I have deployed django with gunicorn and nginx, and it works fine, if the django app is served on the root url, with this configuration: server { listen 80; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:my_app.sock; } } However when I try to serve the django app on another url, it doesn't work. If I try to access http://domain/my_app/admin/ django tells me it cannot find the view. This is nginx config: server { listen 80; location = /favicon.ico { access_log off; log_not_found off; } location /my_app { include proxy_params; proxy_pass http://unix:/var/my_app/app.sock; } } How could I make this work? I was not able to find any solution to specify something like a "BASE_URL" so far. Thanks -
How should I add django import export on the User Model
I am trying to enable django import export on the django user model. I have tried defining a model admin class, unregistering the user model and then registering the new user admin class. But it doesn't work. my admin.py looks like this - from django.contrib.auth.admin import UserAdmin as BaseAdmin class UserResource(resources.ModelResource): model = User fields = ('first_name', 'last_name', 'email') class UserAdmin(BaseAdmin, ImportExportModelAdmin): resource_class = UserResource admin.site.unregister(User) admin.site.register(User, UserAdmin) I want to know how can I achieve this? Is there some other way I can apply django import export on the user model? -
Step wise django tutorial reference from basic to advance
Actually i've completed basics of python including OOP concepts, can anyone refer me to the best resource to learn django , as i m completely new to it. -
Django Rest Framework ModelSerializer all fields not working properly
I'm trying to get all the fields and functions from my model. It works well with the fields but it doesn't get the functions. models.py snippet: email = models.EmailField(_('Email'), null=True, blank=True) @property def function_name(self): return ... serializers.py snippet: class ModelNameSerializer(serializers.ModelSerializer): class Meta: model = ModelName fields = '__all__' If i call serializers.data from views.py, i get the field email but not the return value of the function. If i do fields = ('function_name',), then i get the return value of the function but not anymore all the other fields. How can i get all fields and functions from my model? I hope that i could explain my problem. -
django mobile number regular expression
I have seen many of the phone example as well as third party package for thie mobile number field. but what i want is this: +country_code , or space (these 3 are optional) phone_number(min range number= 8, max is 13) EG: +65, 98654578 based on one of the example and it work but not to what i wanted. : What's the best way to store Phone number in Django models phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list The one i made is this : mobile_regex = RegexValidator(regex=r'^\+?1?\d{1-3}?\,?\s?\d{8-15}$', message="Phone number must not consist of space and requires country code. eg : +6591258565") But it doesnt work. Did i do something wrong? please help me -
IndentationError: unindent does not match any outer indentation level model.py line 36
I am new in python as well as Django. i got error (IndentationError: unindent does not match any outer indentation level) line 36 model.py below is my code class Load_ProviderRegistration(models.Model): def number(): // i got error in this line no = Load_ProviderRegistration.objects.count() if no == None: return 1 else: return no + 1 Load_Provider_id = models.IntegerField(unique=True,default=number) Load_Provider_name = models.CharField(max_length=50) address = models.CharField(max_length=100) contact = models.CharField(max_length=13) -
django + apscheduler - How to configure APScheduler to use django db connection data in settings.py?
I have a working Django project with its database and model tables.Now, I want to integrate APScheduler and save APScheduler job in the same database as other tables, using the Django database connection. I have read the User Guide which gives examples of hardcoding db connection string into code: from pytz import utc from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.mongodb import MongoDBJobStore from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor jobstores = { 'mongo': MongoDBJobStore(), 'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite') } executors = { 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) } job_defaults = { 'coalesce': False, 'max_instances': 3 } scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc) But the config data I already have it in Django setting file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxxxx', 'USER': "manager", 'PASSWORD': "xxxxxxxx", 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } Can I just use Django connection? I don't want to write these data into another properties file to maintain two files. -
django-celery-beat not using defined time period
I am using django celery beat to define periodic tasks. Everything works well. But I have got this problem. When I turn on the beat, it keeps sending the task to the worker multiple times in a second. Here is the log record, [2017-12-22 14:20:21,950: DEBUG/MainProcess] db.tasks.check_next_service sent. id->d0ac2127-83bd-419a-b345-07630ec6af3d [2017-12-22 14:20:21,956: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:21,963: DEBUG/MainProcess] db.tasks.check_next_service sent. id->952a8f7e-270a-4a0f-8339-bdf7788f97b3 [2017-12-22 14:20:21,970: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:21,982: DEBUG/MainProcess] db.tasks.check_next_service sent. id->07bd7748-7ce9-4bb4-80f3-875482785c02 [2017-12-22 14:20:21,986: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:21,990: DEBUG/MainProcess] db.tasks.check_next_service sent. id->46f5dbf4-552e-4757-805d-c164cee21c1a [2017-12-22 14:20:22,004: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:22,017: DEBUG/MainProcess] db.tasks.check_next_service sent. id->8cb0bb26-88bc-4bf5-acfb-2f7a61338c92 [2017-12-22 14:20:22,022: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:22,031: DEBUG/MainProcess] db.tasks.check_next_service sent. id->d864c19b-b42f-4e18-9f0d-95b5718514b4 [2017-12-22 14:20:22,043: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:22,051: DEBUG/MainProcess] db.tasks.check_next_service sent. id->e4629a95-936b-4c12-8ce8-7368c060a75f [2017-12-22 14:20:22,060: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) See, it sends the task almost 10 times within a second whereas I have declared the interval to be every 1 minute. I have seen this issue, https://github.com/celery/celery/issues/943 and also set CELERY_UTC_ENABLE to TRUE. STill the problem persists. … -
django CBV generic DetailView redirect if object does not exist
I have a DetailView which displays userprofile if the current logged in user has a userprofile created. If the user does not have a profile created, i need an else condition. Since im new to django and python, and even newer to CBV, i cannot figure out my next step. I'm hoping there is a way in def get_object() to redirect to UserProfile. Without a userprofile present it results in Related Object DoesNotExist error. How can i write an else or except condition to redirect to ProfileView (form to create profile) PS: UserProfile is to Create a profile, UserProfileView is to View a created profile, UserProfileUpdate is to Update an existing profile. Models.py class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) phone = models.CharField(max_length=128, unique=True, null=True, validators=[validators.RegexValidator( r'^(?:\+?(\d{2}))?(\d{10})$', _('Enter a valid phone number. Type without space or special charecter.') )]) objects = UserManager() REQUIRED_FIELDS = ['first_name'] USERNAME_FIELD = 'email' def __str__(self): return self.email class UserProfile(models.Model): """User Profile""" user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.CharField(max_length=128) state = models.CharField(max_length=128) city = models.CharField(max_length=128) landmark = models.CharField( max_length=128, help_text='Enter a landmark closest to you') address_line_1 = models.CharField( max_length=128, help_text='House name/Flat No') address_line_2 = models.CharField( max_length=128, help_text='Street Name/No') address_line_3 = models.CharField( … -
How to create Real-time collaborative whiteboard in Django?
I'm implementing a online tutorial website in Django. One option is to implement an interactive whiteboard section. I tried the whiteboard 0.1.1 (Link) . But I was hoping someone could guide me with the best option. Thanks. -
Django 2.0 - test using fixtures from dumpdata gives utf8mb4 encoding errors
I am using utf8mb4 encoding for my mySQL database. All my Django apps work correctly with it even with Cyrillic characters. But when I run ./manage.py test <module> and try to load a fixture dumped from the same database, I get errors regarding the encoding. One of the errors is: Could not load advert.Region(pk=1): (1366, "Incorrect string value: '\\xD0\\x9F\\xD0\\xBB\\xD0\\xBE...' for column 'region_name' at row 1") Then I set DEFAULT_CHARSET in the Django settings and the error changed to LookupError: Problem installing fixture '<path>/test_db_one.xml': unknown encoding: utf8mb4 As you can see I have specified the format of the fixture to be XML as it has better handling of the encoding. My setting module has the following properties: DEFAULT_CHARSET = 'utf8mb4' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'autoplusplus_dev', 'USER': 'autoplusplus_django', 'PASSWORD': '1029', 'HOST': 'localhost', 'PORT': '3306', 'STORAGE_ENGINE': 'INNODB', 'OPTIONS': {'charset': 'utf8mb4'}, 'TEST_CHARSET': 'utf8mb4', } } I have mysqlclient 1.3.12 installed -
Error with list_route: POST methods in Viewset
I am making a function Add Friend which user can Create one Friendship Request object to another user user URL:http://localhost:8000/api/v1/users/{username}/add_friend/ but I get error when making. Hope you guys help me! Code in Urls.py from .views import (AddFriendUserAPIView) urlpatterns = [ url(r'^(?P<username>[\w-]+)/add_friend/$', AddFriendUserAPIView.as_view({'post': 'add_friend'}), name='add_friend'), ] Code in Views.py class AddFriendUserAPIView(ReadOnlyModelViewSet): serializer_class = FriendRequestSerializer queryset = FriendshipRequest.objects.all() @list_route(methods=['POST']) def add_friend(self, request): add_qs = FriendshipRequest.objects.get_or_create(from_user=self.request.user, to_user=self.user, message='') serializer = self.get_serializer(add_qs) return Response(serializer.data) Code in serializers.py class FriendRequestSerializer(ModelSerializer): class Meta: model = FriendshipRequest fields = ( 'id', 'from_user', 'to_user', 'message', ) Error log by Trackback Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\viewsets.py" in view 90. return self.dispatch(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs) Exception Type: TypeError at /api/v1/users/duongnuhabang/add_friend/ Exception Value: add_friend() got an unexpected keyword argument 'username' Request Information -
write persian in slug and use it in address bar in django
i use django and in my models i want to write persian in slugfield (by using utf-8 or something else) and use the slug in address of page i write this class for model class Category(models.Model): name = models.CharField(max_length=20, unique=True) slug = models.SlugField(max_length=20, unique=True) description = models.CharField(max_length=500) is_active = models.BooleanField(default=False) meta_description = models.TextField(max_length=160, null=True, blank=True) meta_keywords = models.TextField(max_length=255, null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) def __str__(self): return self.name def category_posts(self): return Post.objects.filter(category=self).count() but there is nothing in slug column after save and i don't know what am i write in url to show persian can you tell me what do i do? and i use django 1.9 and python 3.6 -
How to create a choice field from many to many connection
In my Django model I have a many to many connection. I would also like to have the option of selecting a primary diagnosis from the connected diagnoses. class Case(models.Model): diagnoses_all_icd_10 = models.ManyToManyField('ICD10') How can I create a choice field that displays only the associated diagnoses for selection? It is important that the solution also works in the Django admin. -
Saving data VS calculating data again and again
As a beginner coder and developer in python and Django I am facing a structure question that will help me and could potentially help other beginner as well. I have a survey application, which ask a user to answer a list of question from 0-100 and then some calculation are made on the background and retrieve scores on charts. My question is do you think I should store each user score in my data base or should it calculate each time the page is loaded ? Thx you -
Getting error `set object is not subscriptable` while trying to add user authenticated via social_django to a Group
I am trying to add a user authenticated by Microsoft Azure Active Directory using social_django to a User Group. Here is my pipleline.py from django.db.models import signals from django.dispatch import Signal from social.pipeline.user import * from django.contrib.auth.models import User, Group from social.utils import module_member def new_users_handler(sender, user, response, details, **kwargs): user.groups.add(Group.objects.get(name='Customer')) user_details.connect(new_users_handler, sender=None) Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', # 'social.apps.django_app.default', ] AUTHENTICATION_BACKENDS = ( 'social.backends.azuread.AzureADOAuth2', ) #settings.py SOCIAL_AUTH_PIPELINE = { 'pipeline.new_users_handler' } Here is the complete output TypeError at /complete/azuread-oauth2/ 'set' object is not subscriptable Request Method: GET Request URL: http://127.0.0.1:8000/complete/azuread-oauth2/?code=&state=&session_state= Django Version: 1.11 Exception Type: TypeError Exception Value: 'set' object is not subscriptable Exception Location: /home/sudheer/self/venv/sso/lib/python3.5/site-packages/social_core/backends/base.py in run_pipeline, line 110 Python Executable: /home/sudheer/self/venv/sso/bin/python Python Version: 3.5.2 Python Path: ['/home/sudheer/self/testsso', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-i386-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/sudheer/self/venv/sso/lib/python3.5/site-packages'] Server time: Fri, 22 Dec 2017 08:40:23 +00 -
Django:name 'Post' is not defined in InteractiveConsole
I am very new to Django, and was trying to develop a blog based on it. After the commands of python manage.py makemigrations and python manage.py migrate worked well, I got into the InteractiveConsole to execute Post.objects.all() and got a NameError. >>> Post.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'Post' is not defined Besides, when running localhost:8000, Server gave another NameError. NameError at / name 'Post' is not defined Request Method: GET Request URL: http://localhost:8000/ Django Version: 2.0 Exception Type: NameError Exception Value: name 'Post' is not defined Exception Location: D:\experiment\blogproject\blog\views.py in index, line 6 Python Executable: d:\experiment\blogproject_env\Scripts\python.exe Python Version: 3.6.3 Python Path: ['D:\\experiment\\blogproject', 'd:\\experiment\\blogproject_env\\Scripts\\python36.zip', 'd:\\experiment\\blogproject_env\\DLLs', 'd:\\experiment\\blogproject_env\\lib', 'd:\\experiment\\blogproject_env\\Scripts', 'd:\\professional soft\\python3.6.3\\Lib', 'd:\\professional soft\\python3.6.3\\DLLs', 'd:\\experiment\\blogproject_env', 'd:\\experiment\\blogproject_env\\lib\\site-packages'] Server time: 星期五, 22 十二月 2017 16:08:10 +0800 and the following was my views.py. from django.shortcuts import render from django.http import HttpResponse def index(request): post_list = Post.objects.all().order_by('-created_time') return render(request, 'blog/index.html', context={'post_list': post_list}) In case, there is the Post code in models.py. class Post(models.Model): title = models.CharField(max_length=70) body = models.TextField() created_time = models.DateTimeField() modified_time = models.DateTimeField() excerpt = models.CharField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title Thank u so much! -
ast.literal_eval - loop over string elements in a list
Goal: I want to extract longlat tuples in the map key from a request.POST below. <QueryDict: {'map': ['(38.70053557156445, 149.81571853160858)', '(38.70060091643143, 149.8153966665268)'], 'csrfmiddlewaretoken': ###}> Problem: I used ast.literal_eval to extract the tuples but somehow only 2nd tuple is returned. markers = request.POST position = ast.literal_eval(markers['map']) I also tried looping over map with but this is giving me SyntaxError: unexpected EOF while parsing on tuple parentheses. for idx, val in enumerate(markers['map']): position = ast.literal_eval(markers['map'][idx]) Finally, I tried list(map(ast.literal_eval, markers['map'])), but this returns the same SyntaxError as above.