Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting error: [Errno 101] Network is unreachable while using send_mail in django?
Settings.py AIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'no-reply@domain.com' EMAIL_HOST_PASSWORD = 'Zealous4$' EMAIL_PORT = 587 EMAIL_USE_TLS = True from django.core.mail import send_mail send_mail('dymmy', 'Here is the message.', 'demo@gmail.com', ['dymmy@gmail.com'], fail_silently=False) It works in my local environment . but not working on my production server(digital ocean ) . -
How to indicate in Django that a recently created data is new for a period of time?
I want to create an app that when you give a list of, for example, string data, where it has to make every letter uppercase. For a duration of 5 minutes to indicate that that string is new in the database. After 5 minutes to indicate that the string is processed. Any tips on how I can do that? -
Optimising postgres windows query
I need some guidance with this query being too slow. SELECT DISTINCT ON (id) id, views - lead(views) OVER (PARTITION BY id ORDER BY update_date DESC) vdiff FROM videoupdate; With 10 million+ rows it takes ~30 seconds. I have created a multicolumn index that reduced the original time from 1 minute. I want to see difference between views for each row partitioned by id. Some thoughts I had: After table update create TABLE AS with the query and select from it. Move old data to backup and shrink table. Look up data warehouse? Change database schema? Hope I made myself clear. Thank you! -
How to remove unicode characters from database in Django
i am new to Django and i have built quite huge database. now i am going to implement elastic search. but when i run push-to-index file it gives me error like this, elasticsearch.exceptions.ConnectionError: ConnectionError('ascii' codec can't decode byte 0xc2 in position 916: ordinal not in range(128)) caused by: UnicodeDecodeError('ascii' codec can't decode byte 0xc2 in position 916: ordinal not in range(128)) can anybody tell me how can i remove all Unicode ASCII characters from my database. is there any script which i can run in views? please help in this regard. any help or suggestion will be highly appriciated Thanks. -
Creating a new rank based on SearchRank in Django
I want to customize the rank results given by SearchRank by giving more weights to some courses based on the value of a field in the Course Model. I want use the rank given by SearchRank: vector=SearchVector('title', weight='A')+SearchVector('full_description', weight='B') query = SearchQuery(search) courses=Course.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('-rank') and Create a new one: rank2=[course.rank*2 if course.field1==Value1 else course.rank for course in courses] And use this new rank to order the courses: courses.annotate(rank2=rank2).order_by('-rank2') But this gives me the error: AttributeError: 'list' object has no attribute 'resolve_expression I also tried to modify the original rank before reordering again, but it seems to use the initial rank values vs. the new ones: def adjust_rank(courses): courses_temp=courses for course in courses_temp: if course.field1==Value1: course.rank=course.rank*2 return courses_temp courses2=adjust_rank(courses).order_by('-rank') I am using Django 1.11.1 and python 2.7.13 -
Can't reach DRF permissions in testing
The unsafe methods mustn't be availible to students. I try to test it but fail with 'AssertionError: 201 != 403', whereas post methods intended to be prohibited. My function gets to the permissions just in one particular case, which I can't understand why(emphasized in the code) permissions: class IsTeacherOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): print (request.method) print (request.user) if request.method in permissions.SAFE_METHODS: return True print(request.user.staff) return request.user.staff == 'T' settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'core.permissions.IsTeacherOrReadOnly', 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json' } test(I am not sure what exactly will be usefull, so I'm going to write the whole function): def test_student_API(self): factory = APIRequestFactory() User(username='student1', password='qwert1234', staff="S").save() student = User.objects.get(username='student1') Token.objects.create(user=student) self.student_list_api(factory, student) self.student_detail_api(factory, student) def student_list_api(self, factory, student): class_time_list = ClassTimeViewSet.as_view({'get': 'list'}) self._student_list_api_request(factory, student, class_time_list, 'api/v0/classtimes', 8) def _student_list_api_request(self, factory, student, class_time_list, url, resp_len): student_request = factory.get(url) response_unauthenticated = class_time_list(student_request) self.assertEqual(response_unauthenticated.status_code, status.HTTP_401_UNAUTHORIZED) force_authenticate(student_request, student, token=student.auth_token) response = class_time_list(student_request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), resp_len) def student_detail_api(self, factory, student): class_time_detail = ClassTimeViewSet.as_view({'get': 'retrieve'}) student_request = factory.get('api/v0/classtimes') response_unauthenticated = class_time_detail(student_request, pk=1) self.assertEqual(response_unauthenticated.status_code, status.HTTP_401_UNAUTHORIZED) force_authenticate(student_request, student, student.auth_token) print('--------------') print('Only in this case permissions is reached') response = class_time_detail(student_request, pk=1) print('---------------') response.render() self.assertEqual(response.status_code, status.HTTP_200_OK) … -
using ajax/jquery to pass stripe.js token to django
I am a beginner, implementing stripe to get payments handled on my django application. I am using dj-stripe and can create customers and add a plan through this set-up. I want to use stripe.js to create the token so I can use the nicely formatted card-submission forms from stripe itself (https://stripe.com/docs/elements/examples) . I don't want to use the django forms to collect card details, as these are hard to change on layout and I would rather not handle the credit card details with my django application myself from security perspective. I managed to get the stripe javascript form working, and it delivers an output in the form of a "token". I should pass the javascript output to my django application and attach this to my customer. I figured out this should happen with some sort of jQueary / Ajax set-up but as I am a beginner, I don't know how to get started. I found this but don't know how to adapt it to my needs. My current set-up prints the output token where in payment.html Success! Your Stripe token is <span class="token"></span> is coded. I tried referring to token inside a jQuery script like this but the token got … -
Confused how to use select_related or the SelectRelatedMixin
class Board(models.Model): author = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) create_date = models.DateField(auto_now=False, auto_now_add=True) def __str__(self): return F'{self.author.username} {self.create_date} {self.pk}' class Problem(models.Model): board = models.ForeignKey(Board, unique=False, on_delete=models.CASCADE) problem = models.TextField() def __str__(self): return self.problem[:30] def get_absolute_url(self): return The idea is I have a Board and then several Problems associated with it. I want to make a classView + template to drilldown the detail of a single board. like /board/187 The output would look like: BOARD: IT Issues Problems: 1) Old servers 2) No UPC 3) Static discharges I made a class-based view to generate the Board. My idea was that the board_detail.html would have an {{ include "board/_problem.html" }} tag that would then use a ListView derivative to enumerate all the Problems associated with that Board. I wasn't very clear on how to do this. I thought I could use a SelectRelatedMixin in the Problem's class, so that I could then have access to fields in the template something like for problem in board.problems kind of structure. But this doesn't seem to be working. I'm hazy on how this work all should be put together. In fact, I am not even sure how to do it with the original select_related() method. I guess … -
how to update the the model from where it is referenced in Django Rest Framework
Hi Every One I am new to Django. I have Question regarding Django RestFrame work. I am working on Car Rent Management System..... I am unable check if the car or driver status is not available below is my code. ----------------My CreateView------------------- class BookingCreate(APIView): permission_classes = (AllowAny,) # queryset = Booking.objects.all() # serializer_class = BookingCreateSerializer def post(self, request): serializer = BookingCreateSerializer(data=request.data) cr = request.data.get('car') dr = request.data.get('driver') car_obj = Car.objects.get(id=cr) driver_obj = Driver.objects.get(id=dr) if car_obj.isAvailable: car_obj.isAvailable = False else: return Response(status='No Car Available') if driver_obj.isAvailable: # data['driver'] = driver_obj.pk driver_obj.isAvailable = False else: return Response(status='No Driver Available') if serializer.is_valid(): # serializer.object. = car_obj.pk # serializer.object.driver_id = driver_obj.pk serializer.save(car_id = car_obj.pk, driver_id = driver_obj.pk) return Response(serializer.data,status=HTTP_201_CREATED) else: return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) -------------------Booking Model--------------- class Booking(models.Model): # Association driver = models.ForeignKey(Driver, related_name='bookings' ,on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) car = models.ForeignKey(Car, related_name='bookings' ,on_delete=models.CASCADE) # Booking Stuff start_time = models.DateTimeField(default=datetime.now, null=False, blank=False) end_time = models.DateTimeField(default=datetime.now, null=False, blank=False) booking_hours = models.FloatField(max_length=6 ) fare = models.FloatField(max_length=5 ) isEnded = models.BooleanField(default=False) SO i want to check whether the car and driver are available or not both have boolean isAvailable and if isavailable then assign it to the that booking and change the status of both driver and car … -
Getting Error with rest_framework_mongoengine with django
After serializing the model in view when i am trying to enter the RESTapi url getting error settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. using mongoengine so haven't set any database. Worked perfectly before tried api integration settings.py import mongoengine DBNAME = 'database' MONGO_HOST = 'localhost' MONGO_PORT = 27017 mongoengine.connect(DBNAME,host=MONGO_HOST, port=MONGO_PORT) INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_mongoengine', 'api' ) DATABASES = { 'default': { 'ENGINE': '', 'NAME': '', } } -
Django deploy : Should I use bootstrap3 CDN?
I have my website. It is made using Django and deployed to Heroku. And I used bootstrap3. Before deploying to heroku, when I test website at localhost:8000, bootstrap3 works well. I used bootstrap3 source file, NOT CDN. Below is my source tree. /home/<path>/multichat$ tree . ├── manage.py ├── static │ ├── bootstrap-3.3.7-dist │ │ ├── css │ │ │ ├── bootstrap-theme.css │ │ │ ├── bootstrap-theme.css.map │ │ │ ├── bootstrap-theme.min.css │ │ │ ├── bootstrap-theme.min.css.map │ │ │ ├── bootstrap.css │ │ │ ├── bootstrap.css.map │ │ │ ├── bootstrap.min.css │ │ │ └── bootstrap.min.css.map │ │ ├── fonts │ │ │ ├── glyphicons-halflings-regular.eot │ │ │ ├── glyphicons-halflings-regular.svg │ │ │ ├── glyphicons-halflings-regular.ttf │ │ │ ├── glyphicons-halflings-regular.woff │ │ │ └── glyphicons-halflings-regular.woff2 │ │ └── js │ │ ├── bootstrap.js │ │ ├── bootstrap.min.js │ │ └── npm.js │ ├── css │ │ └── base.css │ └── js │ └── jquery-1.12.2.min.js ├── staticfiles │ └── default_profile.png └── templates ├── 404.html ├── 500.html ├── base.html ├── home.html └── index.html All my html files extends templates/base.html. To apply bootstrap3 I coded like this in base.html. <!-- bootstrap --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="{% static … -
Deploying a Django App to OpenShift 3.0 that needs NLTK
I am working on a Django project needing Newspaper3K to retrieve some information over the internet. Trying to deploy my Django web app onto the free OpenShift Online Free 3.0, the build fails when it comes to installing the Newspaper3K and hence its dependency NLTK. Please advise the correct steps to achieve this "Django with NLTK deploying to OpenShift 3" installation. Thanks! -
how to aggregate by YEAR() in django models
I am using this code to aggregate rows from database: from django.db.models import Avg from django.db.models import FloatField query_set=testTable.objects.filter(location='TgR',\ part__in=['Q', 'F'],week_number__lte=38,week_number__gte=42).\ annotate(col1_avg=Avg('col1'),col2_avg=Avg('col2'),col3_avg=Avg('col3'),\ Total= (Avg('col1',output_field=FloatField())+Avg('col2', output_field=FloatField())+Avg('col3', output_field=FloatField())) ) raw query looks like this: SELECT week_number, part, type, AVG(col1), AVG(col2), AVG(col3), ( AVG(col1) + AVG(col2) + AVG(col3) ) as Total FROM table1 WHERE location = 'TgR' AND week_number BETWEEN 38 AND 42 AND part IN ('Q', 'F') GROUP BY 1 ,2 ,3; And I want to change it to : SELECT YEAR(date), week_number, part, type, AVG(col1), AVG(col2), AVG(col3), ( AVG(col1) + AVG(col2) + AVG(col3) ) as Total FROM table1 WHERE location = 'TgR' AND week_number BETWEEN 38 AND 42 AND part IN ('Q', 'F') GROUP BY 1,2,3,4; Basically all I want to do is add that Year to aggregate, but have no idea how to do this right. Thanks in advance, -
How to prevent remote file injection using Django and Python
I need one help. I need to prevent from remote file attack using Python. I am explaining my code below. if request.GET.get('file') is not None and request.GET.get('file') != '': file = request.GET.get('file') response = urllib.urlopen(file) lines = response.readlines() return HttpResponse(content=lines, content_type="text/html") else: return render(request, 'plant/home.html', {'count': 1}) Here if someone calling the query string value like this http://127.0.0.1:8000/createfile/?file=https://www.google.co.in/?gfe_rd=cr&dcr=0&ei=N46zWczCGojT8geN-pvwCg then remotes are also including here I need to prevent this remote file inclusion. -
I would like to know how to make class based views for my existing model forms. I need to redirect the form one model form to the other
These contains semester, subject, assesment etc, which are all linked to each other by foreign key models.py from django.db import models class Semester(models.Model): S_OPTIONS = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ) sem_type=models.CharField(max_length=1, choices=S_OPTIONS) def __str__(self): return self.sem_type class Subject(models.Model): S_OPTIONS = ( ('Math','Math'), ('English','English'), ('C++','C++'), ('Thermo','Thermo'), ('Electronics', 'Electronics'), ) sub_type = models.CharField(max_length=100, choices= S_OPTIONS) sem = models.ForeignKey(Semester, on_delete=models.CASCADE, default=1) def __str__(self): return self.sub_type class Assesment(models.Model): A_OPTIONS = ( ('1','CT1'), ('2','CT2'), ('3','CT3'), ) assess_type=models.CharField(max_length=1, choices=A_OPTIONS) sub = models.ForeignKey(Subject, on_delete=models.CASCADE, default=1) def __str__(self): return self.assess_type class Paper(models.Model): PA_OPTIONS = ( ('1','1'), ('2','2'), ) paper_type = models.CharField(max_length=1, choices=PA_OPTIONS,default=1) assesment = models.ForeignKey(Assesment, on_delete=models.CASCADE, default=1) # def get_absolute_url(self): # return reverse('teacher:home',kwargs={'pk': self.pk}) def __str__(self): return self.paper_type class Part(models.Model): P_OPTIONS = ( ('A','A'), ('B','B'), ('C','C'), ) part_type = models.CharField(max_length=1, choices=P_OPTIONS) paper= models.ForeignKey(Paper, on_delete=models.CASCADE, default=1) def __str__(self): return self.part_type class Question(models.Model): a = models.TextField() part= models.ForeignKey(Part,on_delete=models.CASCADE, default=1) def __str__(self): return self.a class Choice(models.Model): c = models.TextField(null= True) question = models.ForeignKey(Question, on_delete =models.CASCADE,default=1, null =True) def __str__(self): return self.c after submitting each form, in the vews, they must redirect to next modelform forms.py from django import forms from .models import Semester,Subject,Assesment,Paper,Part,Question,Choice from django.contrib.auth.models import User class … -
django : form automatically updated by user
I’m learning the Django framework. I went through the tango with Django tutorial a few times and start to have an overview of how the whole thing come together but my knowledge of the framework is still extremely basic. I’m trying to create my own very basic application to get some practice. I’m having trouble with one thing. I have (or rather would like to have) a “form page” where each user can create his own article. An article is made of pictures, text and video that are arranged in blocs. So for one article there can be a bloc of text, then a bloc of images then another bloc of text, then a bloc of video and so on. It’s up to the user to decide what he wants to have in his article. I would like the form to be automatically updated by the user himself as he is creating his article. There would be at the beginning on the empty form page three buttons : “add text”, “add images” and “add video”. The user would start by clicking on one of these 3 buttons. If he wants his article to start with some text he would click … -
Django viewset DRF
Serializer: class Test1Serializer(serializers.Serializer): name=serializers.CharField(max_length=256) usemember1=serializers.CharField(max_length=256) usemember2=serializers.CharField(max_length=256) test_name=serializers.CharField(max_length=256) id = serializers.CharField(max_length=10, read_only=True) Viewset: class Test1ViewSet(viewsets.ViewSet): serializer_class=Test1Serializer def list(self,request,parent_lookup_id=None): try: config = Config.objects.get(pk=parent_lookup_id) except KeyError: return Response(status=status.HTTP_404_NOT_FOUND) except ValueError: return Response(status=status.HTTP_400_BAD_REQUEST) serializer = NewSerializer(config) try: return Response(serializer.data['config']['test1']) except: return Response(None) My responce is "config": { "test1": { [ { "usemember1": "mem1", "name": "new3323", "usemember2": "mem2", "config_name": "policy", "config_value": "new23323", "id": 1 }, { "usemember1": "mem4", "name": "newro", "usemember2": "mem5", "config_name": "rule", "config_value": "newro", "id": 2 } ] but i want response by filter "config_name": "rule" what i need is [ { "usemember1": "mem4", "name": "newro", "usemember2": "mem5", "config_name": "rule", "config_value": "newro", "id": 2 } ] how can i get above result?? In viewset where can i change. when i list it should give "config_name": "rule" part alone. -
Django code not updating in server
I'm using Djnago 1.8.17. I have deployed the code to a remote server, checked that it is up to date, but the changes do not refresh in the web page. Things I've tried so far: Restarted gunicorn and nginx Using manage.py instead of gunicorn Clear memcached Restarted server Delete all .pyc files Open in incognito I've this module that is working fine in other servers, but for some reason this one is showing an old version. -
ValueError: invalid literal for int() with base 10: '013000ab7C8'
I wanna parse excel& make dictionary and put the model(User) which has same user_id of dictionary. Now I got an error,ValueError: invalid literal for int() with base 10: '013000ab7C8' . Of course,'013000ab7C8' is not int,but I really cannot understand why this error happens. I wrote in views.py #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/excel1.xlsx') sheet = book.sheet_by_index(1) def build_employee(employee): if employee == 'leader': return 'l' if employee == 'manager': return 'm' if employee == 'others': return 'o' for row_index in range(sheet.nrows): rows = sheet.row_values(row_index) is_man = rows[4] != "" emp = build_employee(rows[5]) user = User(user_id=rows[1], name_id=rows[2], name=rows[3], age=rows[4],man=is_man,employee=emp) user.save() files = glob.glob('./user/*.xlsx') data_dict_key ={} for x in files: if "$" not in x: book3 = xlrd.open_workbook(x) sheet3 = book3.sheet_by_index(0) cells = [ ] data_dict = OrderedDict() for key, rowy, colx in cells: try: data_dict[key] = sheet3.cell_value(rowy, colx) except IndexError: data_dict[key] = None if data_dict['user_id'] in data_dict_key: data_dict_key[data_dict['user_id']].update(data_dict) continue data_dict[data_dict_key['user_id']] = data_dict for row_number, row_data in data_dict_key.items(): user1 = User.filter(user_id=row_data['user_id']).exists() if user1: user1.__dict__.update(**data_dict_key) user1.save() I wanna connect excel files under user's folder & excel1.xlsx in user_id,it means if each data has same user_id,it will be connected. data_dict_key is dicts = { '013000ab7C8: OrderedDict([ ('user_id', … -
Packaging a django project using setup tool and hide the code from the user
I have developed a Django project and I want to package it using setup tools.The problem is when I packaged the project it creates a tar file which is installable and working fine, but it contains the all my python code which I don't want. I want to hide my code from user. So is there any way to use the pyc file instead of py file in packaging or any other way to hide the code and package the project. -
Date format changed in django forms
I am using django forms but date is not showing in specific format. forms.py class MyForm(forms.ModelForm): receive_date = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control ','readonly':True }), input_formats=DATE_INPUT_FORMATS, initial=date.today()) class Meta: model = Mymodel fields = "__all__" When i load or reload the page date format is look like after when i clicked on date format will change, but it should not be change. it look like this in Html file, simply i used {{forms.as_table}} Thanks in advance -
Django Rest Framework custom response for validation failure
Background I am new to Django and the rest framework, and I am trying to use the Django Rest Framework to build an API Demo of Register and Login for mobile app. I want I am using APIView and the ModelSerializer, and the arguments and contraints for registion are email <required, unique>, username <required, unique>, password <required, unique>, and here, my requirements focus on the exception, I want to get a custom error code to indicate that what validations(required or unique) has failed. For example when I send the arguments: username="", (leaves it blank) password=123, email="xxx@yyy.com" this will lead to the required validation failure, and the JSON response returns something like "username": [ "This field may not be blank." ] but, I want the JSON response to be something like { error_code: 1, msg: "blah blah blah" } in this way, mobile app can do whatever it wants according to the error_code. Problems I have found that, inside the framework's validation implementation, validation failures(all fields validation failures) have been transformed to plain texts and packed in an array, I can not get the specific exception(such as the username required exception), and I can not generate the error_code in the response. … -
django - deploy to Heroku : Server Error(500)
I am trying to deploy my first Django project to Heroku. My project uses django channels So I need to set up ASGI based environment. However, I got a 500 server error and I can't see why. I've read through my logs and nothing stands out. Below is my log. 2017-09-09T05:47:02.000000+00:00 app[api]: Build succeeded 2017-09-09T05:47:25.660750+00:00 heroku[web2.1]: Process exited with status 0 2017-09-09T05:47:25.651941+00:00 app[worker.1]: 2017-09-09 14:47:25,651 - INFO - worker - Shutdown signal received while idle, terminating immediately 2017-09-09T05:47:26.415829+00:00 heroku[worker.1]: Process exited with status 0 2017-09-09T05:47:29.354604+00:00 heroku[worker.1]: Starting process with command `python manage.py runworker` 2017-09-09T05:47:29.450528+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath multichat multichat.wsgi --log-file -` 2017-09-09T05:47:29.811901+00:00 heroku[web2.1]: Starting process with command `daphne multichat.asgi:channel_layer --port 34071 --bind 0.0.0.0` 2017-09-09T05:47:29.967498+00:00 heroku[worker.1]: State changed from starting to up 2017-09-09T05:47:30.500574+00:00 heroku[web2.1]: State changed from starting to up 2017-09-09T05:47:31.850448+00:00 app[worker.1]: 2017-09-09 14:47:31,850 - INFO - runworker - Using single-threaded worker. 2017-09-09T05:47:31.850705+00:00 app[worker.1]: 2017-09-09 14:47:31,850 - INFO - runworker - Running worker against channel layer default (asgi_redis.core.RedisChannelLayer) 2017-09-09T05:47:31.850983+00:00 app[worker.1]: 2017-09-09 14:47:31,850 - INFO - worker - Listening on channels chat.receive, http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-09-09T05:47:31.913010+00:00 app[web.1]: [2017-09-09 05:47:31 +0000] [4] [INFO] Starting gunicorn 19.7.1 2017-09-09T05:47:31.913782+00:00 app[web.1]: [2017-09-09 05:47:31 +0000] [4] [INFO] Listening at: http://0.0.0.0:20341 (4) 2017-09-09T05:47:31.913918+00:00 … -
I wanna make a dictionary has user_id's key & data
I wanna make a dictionary has user_id's key & data.In views.py I wrote #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/excel1.xlsx') sheet = book.sheet_by_index(1) def build_employee(employee): if employee == 'leader': return 'l' if employee == 'manager': return 'm' if employee == 'others': return 'o' for row_index in range(sheet.nrows): rows = sheet.row_values(row_index) is_man = rows[4] != "" emp = build_employee(rows[5]) user = User(user_id=rows[1], name_id=rows[2], name=rows[3], age=rows[4],man=is_man,employee=emp) user.save() files = glob.glob('./user/*.xlsx') for x in files: if "$" not in x: book3 = xlrd.open_workbook(x) sheet3 = book3.sheet_by_index(0) cells = [ ] data_dict = OrderedDict() for key, rowy, colx in cells: try: data_dict[key] = sheet3.cell_value(rowy, colx) except IndexError: data_dict[key] = None data_dict_key ={} data_dict_key['user_id'].update(data_dict_key) But when I run this code,error happens Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/XXX/testapp/app/views.py", line 164, in <module> data_dict_key['user_id'].update(data_dict_key) KeyError: 'user_id' I really cannot understand why this error happens. When I print out data_dict,it is OrderedDict([('user_id', '1'), ('name', 'Blear'), ('nationality', 'America'), ('domitory', 'A'), ('group', 1)]) My ideal dictionary is dicts = { 1: { user_id: 1, name_id: 'Blear', nationality: 'America', domitory: 'A', group: 1, }, 2: { }, } How should I fix this?Should I use for statement? -
Django (?P<pk>\d+) in URL's partly working
I have this as my users app urls.py: from django.conf.urls import url from users import views app_name = 'users' urlpatterns = [ url(r'^$',views.UserListView.as_view(),name='user_list'), url(r'^(?P<pk>\d+)/$',views.UserProfileView.as_view(),name='user_profile'), url(r'^(?P<pk>\d+)/edit$',views.UserEditProfileView.as_view(),name='user-profile-edit'), url(r'^login/$',views.user_login,name='user_login'), url(r'^logout/$',views.user_logout,name='user_logout'), url(r'^register/$',views.register,name='register'), ] This url pattern url(r'^(?P<pk>\d+)/$',views.UserProfileView.as_view(),name='user_profile'), works with this url http://127.0.0.1:8000/user/1/ but when I made a new user and logged in I get a page not found (404) when I click on the button that goes with that pattern The are not errors but this is what it tells me: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/user/3/ Raised by: users.views.UserProfileView No user profile info found matching the query You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. So to put it more simply, with that url pattern user 1's profile will work, but user 3's will not.