Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djanog save a model in admin.py
I need to save a parameter(specs which is a dictionary) in Estimate model in django's admin.py. Earlier I used signals but that did not appear to be a wise option. I have below admin.py and here I want to update Estimate's specs field by merging this field with Environment's specs. How can I achieve that? I am still learning Django. I have understood that in the Django admin, when I deal with Estimate model, I get response from Estimate and EstimateAdmin class. At the same time I also have Environment whose foreign key is Estimate and in the Django Admin's Estimate model, Environment is an object. I tried Estimate_specs = Estimate.objects.all() but need to filter the specs on the basis of current estimate and Environment_specs = Environment.objects.all() but again this needs to be filtered with specs on the basis of current estimate. I am not able to figure out how to get this working. class EnvironmentInlineAdmin (admin.TabularInline): model = Environment ... class EstimateAdmin (CommonAdmin): ... admin.site.register(Estimate,EstimateAdmin) class EnvironmentDetailsInlineForm(forms.ModelForm): class Meta: model = EnvironmentDetail fields = ['item_name','qty'] show_change_link = True class AddEnvironmentDetailsInlineForm(forms.ModelForm): ... class EnvironmentDetailsInlineAdmin (admin.TabularInline): ... class AddEnvironmentDetailsInlineAdmin (admin.TabularInline): model = EnvironmentDetail fields = ('item_name','item', 'qty', ) form = AddEnvironmentDetailsInlineForm … -
Django rest framework with djoser token authentication retrieve user first_name
I am using django rest framework djoser authentication. So what i want is when user login, it will return their user token, promptmsg, status, first_name and last_name. djoser: http://djoser.readthedocs.io/en/latest/introduction.html Now i am able to display the token , promptmsg and status but as for the first_name and last_name, i have error trying to do it. serializers class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) default_error_messages = { 'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR, 'inactive_account': constants.INACTIVE_ACCOUNT_ERROR, } def __init__(self, *args, **kwargs): super(TokenCreateSerializer, self).__init__(*args, **kwargs) self.user = None self.fields[User.USERNAME_FIELD] = serializers.CharField( required=False ) def validate(self, attrs): self.user = authenticate( username=attrs.get(User.USERNAME_FIELD), password=attrs.get('password') ) self._validate_user_exists(self.user) self._validate_user_is_active(self.user) return attrs def _validate_user_exists(self, user): if not user: self.fail('invalid_credentials') def _validate_user_is_active(self, user): if not user.is_active: self.fail('inactive_account') customviews.py class CustomTokenCreateView(cutils.ActionViewMixin, generics.GenericAPIView): """ Use this endpoint to obtain user authentication token. """ serializer_class = TokenCreateSerializer permission_classes = [permissions.AllowAny] def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token content = { 'Token': token_serializer_class(token).data["auth_token"], 'promptmsg': 'You have successfully login', 'status': '200', 'first_name': self.request.user.first_name, 'last_name': self.request.user.last_name } return Response( data=content, status=status.HTTP_200_OK, ) This code will give an error : AttributeError at /logintest/ 'AnonymousUser' object has no attribute 'first_name' Is there a way to fix this ? -
SyntaxError when create django project
When I try to create a django project with python3.6, this error raises: Error creating Django application: Error on python side. Exit code: 1, err: Traceback (most recent call last): File "D:\PyCharm 2017.3\helpers\pycharm\_jb_django_project_creator.py", line 12, in <module> management.execute_from_command_line(argv=["django-admin", "startproject", project_name, path]) File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\management\__init__.py", line 328, in execute django.setup() File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\__init__.py", line 15, in setup from django.utils.log import configure_logging File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\utils\log.py", line 16, in <module> from django.views.debug import ExceptionReporter, get_exception_reporter_filter File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\views\debug.py", line 9, in <module> from django.core.urlresolvers import Resolver404, resolve File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\urlresolvers.py", line 17, in <module> from django.http import Http404 File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\http\__init__.py", line 4, in <module> from django.http.response import ( File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\http\response.py", line 13, in <module> from django.core.serializers.json import DjangoJSONEncoder File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\serializers\__init__.py", line 24, in <module> from django.core.serializers.base import SerializerDoesNotExist File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\serializers\base.py", line 6, in <module> from django.db import models File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\__init__.py", line 6, in <module> from django.db.models.query import Q, QuerySet, Prefetch # NOQA File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\query.py", line 16, in <module> from django.db.models import sql File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\sql\__init__.py", line 2, in <module> from django.db.models.sql.subqueries import * # NOQA File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\sql\subqueries.py", line 7, in <module> from django.db.models.query_utils import Q File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\query_utils.py", line 13, in <module> from django.db.backends import utils File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\backends\utils.py", line 11, in <module> from … -
I am having errors with Django authenticated built-in function
I have been woking in django for a while. Now i am facing some problems with built-in function in django. The error state that TypeError: 'bool' object is not callable. This kind of error happened because of statement 'print(request.user.is_authenticated())'. Here below is source code: def login_page(request): form = LoginForm(request.POST or None) #ensure user is logged in or not print(request.user.is_authenticated()) if form.is_valid(): print(form.cleaned_data) return render(request,"auth/login.html",{}) For LoginForm() is imported by my file forms.py from django import forms class ContactForm(forms.Form): #first will be name which is variable fullname = forms.CharField(widget=forms.TextInput (attrs={"class":"form-control","placeholder":"Your fullname"})) email = forms.EmailField(widget=forms.EmailInput (attrs={"class":"form-control","placeholder":"Your Email"})) content = forms.CharField(widget=forms.Textarea (attrs={"class":"form-control","placeholder":"Your content"})) def clean_email(self): email = self.cleaned_data.get("email") if not "gmail.com" in email: raise forms.ValidationError("Email has to be gmail.com") #return value of email to be stored return email class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField() -
How to use multiple attributes in algolia search using Django
How to use multiple attributes in algolia search using Django. I want print course details and loan details in algolia. { "approved_by": "GTU, Ahmedabad", "institute_type": "Private", "established": "2000-01-01", "image": "images/1_iSHnp8X.jpg", "course_": [ { "course_name": "Btech", "tution_fees": "4500", "other_fees": "0", "duration": "2", "hostel_fees": "0", "course_type": "Full Time", "loan": [ { "amount": "3.2", "tenures": [ { "interest_rate": 14.1, "duration": "24" }, { "interest_rate": 25, "duration": "6" } ] } ] }, { "course_name": "Mtech", "tution_fees": "80000", "other_fees": "0", "duration": "4", "hostel_fees": "0", "course_type": "part time", "loan": [ { "amount": "2.0", "tenures": [ { "interest_rate": 4, "duration": "24" } ] } ] } ], "address": "Greater Noida", "name": "A. D. Patel Institute Of Technology - [ADIT], Vallabh Vidyanagar", "location_type": "domestic", "college_facilities": "Hostel Medical", "slug": "asfdsfsdfdsfdgdfgfgfhhf", "type": "institute", "objectID": "1" } screenshort How to use multiple attributes in algolia search using Django. I want print course details and loan details in algolia. instantsearch.widgets.hits({ container: '#result', hitsPerPage: 9, templates: { empty:noTemplate, item: hitTemplate, } }) ); var hitTemplate='<div class="col-lg-4 col-xs-12" data-sku="{{slug}}><div class="post-module hover" data-product-id="{{objectID}}" ><div class="thumbnail"><img src="/media/{{image}}" class="img-responsive"></div><div class="post-content"><div class="category"><i class="fa fa-map-marker" aria-hidden="true"></i>{{address}}</div><div class="row head"><div class="col-lg-6 col-xs-6"><p>Type: {{institute_type}}</p></div><div class="col-lg-6 col-xs-6 pull-right"><p>Rank: N/A</p></div></div><h3 class="title">{{name}} </h3><h5 class="sub_title">Courses</h5><hr><div class="row"><div class="col-lg-6 col-xs-6 ca-border"><ul><li>{{course_.course_name}}</li><li>EMI: <i class="fa fa-inr" aria-hidden="true"></i> {{course_.loan.amount}}</li><li>Fee: <i … -
membership management in Django
I'm writing my first Django application in Django 2.0 My application has two types of membership level Free Users Paid Users Also, there in the application I want certain function/views disabled for Free Users and hide elements in template based on the membership level. How can I manage all these in my application? Is it possible to do it all using built-in permission manager? I tried reading the docs, but it contains few inbuilt modules and could not get how to separate it as per my requirement -
Where is the supervisor keep a process's pidfile?
Error explain: I do a django-celery project and use supervisor to keep the celery process. With a lot of action,it mad out a error that I can't start a work.It says: stale pidfile exists.Removing it. But i did not point the pidfile path when I setting the supervisor. question where is the supervisor keep the process's pidfile default? Could someone tell me how to right do command that I can see the tasks and workers in django-admin-site? I try like this when I develop the projects: python manage.py runserver 0.0.0.0:8090 python manage.py celery events --camera=djcelery.snapshot.Camera python manage.py celerybeat -l INFO python manage.py celeryd -n worker_1 -l INFO But when I try like this in supervisor,with nginx+uwsgi,I see nothing in django-admin-site -
Django rest framework with Djoser token authentication token response
As i am using a third party package called djoser to handle the token authentication. i want to customise the response. But after trying to change it, the result is not what i wanted. I just wanted to get the token value of the token instead of having "auth_token:" in front. Here is the link to djoser: https://github.com/sunscrapers/djoser Here is my code : serializer.py class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) default_error_messages = { 'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR, 'inactive_account': constants.INACTIVE_ACCOUNT_ERROR, } def __init__(self, *args, **kwargs): super(TokenCreateSerializer, self).__init__(*args, **kwargs) self.user = None self.fields[User.USERNAME_FIELD] = serializers.CharField( required=False ) def validate(self, attrs): self.user = authenticate( username=attrs.get(User.USERNAME_FIELD), password=attrs.get('password') ) self._validate_user_exists(self.user) self._validate_user_is_active(self.user) return attrs def _validate_user_exists(self, user): if not user: self.fail('invalid_credentials') def _validate_user_is_active(self, user): if not user.is_active: self.fail('inactive_account') views.py class TokenCreateView(utils.ActionViewMixin, generics.GenericAPIView): """ Use this endpoint to obtain user authentication token. """ serializer_class = settings.SERIALIZERS.token_create permission_classes = [permissions.AllowAny] def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token return Response( data=token_serializer_class(token).data, status=status.HTTP_200_OK, ) my custom views.py class CustomTokenCreateView(utils.ActionViewMixin, generics.GenericAPIView): """ Use this endpoint to obtain user authentication token. """ serializer_class = TokenCreateSerializer permission_classes = [permissions.AllowAny] def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token content = { 'Token': token_serializer_class(token).data, 'promptmsg': 'You have successfully login', … -
How to make Django 2.0 to use Oracle 11g syntax instead of 12c?
This is my dev environment: Windows 7 (x64) Python 3.6.3 64bit (virtual environment) Django 2.0 cx_Oracle 6.1 Oracle 11.2 Enterprise Edition 64 bit (on remote machine) I am failing to migrate (django manage.py migrate) because Django is creating sql suitable for Oracle 12c; but I am using 11g. How can I make django use 11g syntax? -
Django testing with handlebars
I am having the issue where by generating the html:s content in Handlebars it does not show up in the html when trying to get it via tests: visit_list_url = str(reverse_lazy('visit_view', kwargs={'username': self.client.username})) resp = self.client.get(visits_list_url) What it is getting: <table id="visit_activities" class="table"> <thead> <tr> <th>#</th> <th>Activity</th> <th>Started</th> <th>Ended</th> <th>Status</th> </tr> </thead> <tbody></tbody> </table> What it is expecting: <table id="visit_activities" class="table"> <thead> <tr> <th>#</th> <th>Activity</th> <th>Started</th> <th>Ended</th> <th>Status</th> </tr> </thead> <tbody> <tr class="<act_class>" act-id="<act_id>"> <td>1</td> <td><name></td> <td>10:41 a.m.</td> <td>10:44 a.m.</td> <td><status_text></td> <td><status_char></td> </tr> </tbody> </table> But the since the content is generated via Handlebars, it does not show up in the response. Any suggestions? -
What's the relationship between csrfmiddlewaretoken and csrftoken?
I was working with Django to create a website and got some questions about CSRF. I use django.middleware.csrf.CsrfViewMiddleware and add <form action="" method="post">{% csrf_token %} in my POST form. And when I test the website: GET / HTTP/1.1 Host: 123.207.137.168:8000 Then, I got cookies Set-Cookie:csrftoken=Ev8veOH89vFDnG3a0GJUsMXA1oGZXxqXRw2nFWiKrvZ9UE10niTlZCiOxdnoKfTv; expires=Thu, 27-Dec-2018 06:37:41 GMT; Max-Age=31449600; Path=/ But in the html: <input type='hidden' name='csrfmiddlewaretoken' value='JswHLk4fNpxHkh0OObD1uKiOxSDUzkMDWtqzcsFR5pRdRfYEbNNs1AD23Hkjm2fb' /> So I was wondering why the csrftoken and csrfmiddlewaretoken is different and how did the server use these two value to valid if the request is from the users or hackers? -
nginx 502 bad gateway gunicorn
I am tried to load a page with django formset, I clearly see in the logs that the backend logic is executed well within 1 second, I have a logger printing right before return render() and it is very clear that the backend process is almost done. The point here is,it is taking way too much time to render the template and nginx throwing bad gateway at me. What should I do? -
How can I add a 'is_logged_in' condition along with another if statement in django python?
This is my views.py for search. @csrf_exempt def search(request): if request.method == 'POST': name = request.POST.get('name') loc = request.POST.get('location') bussinessName = request.POST.get('bussinessName') d = { 'name': name, 'loc': loc, 'bussinessName': bussinessName, } return render(request, "search.html", d); else: # do the thing you want to do in GET method return render(request,"search.html",{}); I need to add a session to get the id. This is how I am getting the id for my success page def success(request): if('is_logged_in' in request.session): id = request.session['authToken']; return render(request,"success.html",{'uid':id}); else: return render(request,"success.html",{}); HOW CAN I able to add this session in search. I am a beginner in Django and I do not have much idea about the same. Please help me to have a session for my search too.. -
How to upload multiple files individually with additional data
I am using blueimp's fileupload. The data is sendable if I do not try to send an additional input on submit. I am trying to upload files with a title following this pattern: user clicks a "select HHs" button to select files After the files are selected and opened, user sees every file listed in rows with a "title" input box and a "submit" button. User types in value for the "title" box and hits "submit" button to send to backend. After #3, I keep getting a 403 sent back a "Forbidden (CSRF token missing or incorrect.)" on the server side (django). Why am I getting this error message and how do I solve this issue? I've replaced data.formData with a simple object to test what I'm trying to accomplish below. upload.js file: $('#fileupload').fileupload({ formData: {title: 'test'}, dataType: 'json', ... add: function (e, data) { var convertElem = $('<input type="submit"/>').click(function() { data.formData = {"title":"test"}; data.submit(); }); ... data.context = $(outerElem) ... } }); upload.html: <button>Select</button> <form id="fileupload" data-url="{% url 'file-upload' %}" enctype="multipart/form-data" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> <input id="fileupload-files" type="file" name="file" multiple> </form> -
Django detailView an duplicates from foreign key relationship
Really hoping someone can point me in the right direction here. I'm new to Django and about ready to move back to CakePHP since I can't seem to find an answer anywhere. I'm most likely looking in the wrong direction so any guidance would be hugely appreciated. Models class active_customer(models.Model): custno = models.IntegerField(primary_key=True) company = models.CharField(max_length=256) cust_firstname = models.CharField(max_length=50) address = models.CharField(max_length=100) address2 = models.CharField(max_length=100) suburb = models.CharField(max_length=200) state = models.CharField(max_length=3) postcode = models.IntegerField() contact_phone = models.CharField(max_length=20) contact_mobile = models.CharField(max_length=20) contact_fax = models.CharField(max_length=20) contact_email = models.CharField(max_length=200) contact_firstname = models.CharField(max_length=200) contact_surname = models.CharField(max_length=200) def __str__(self): #string used to identify the model object return self.company class active_service(models.Model): customer_name = models.CharField(max_length=50) service_number = models.CharField(primary_key=True, max_length=100) customer = models.ForeignKey('active_customer', db_column='customer') service_id = models.CharField(max_length=6) service_type = models.CharField(max_length=50) sub_address_type = models.CharField(max_length=50) sub_address_no = models.CharField(max_length=10) street_no = models.CharField(max_length=50) street_name = models.CharField(max_length=200) street_type = models.CharField(max_length=50) suburb = models.CharField(max_length=100) postcode = models.CharField(max_length=4, null=True) state = models.CharField(max_length=3, null=True) def __str__(self): #string used to identify the model object return self.service_number URLS urlpatterns = [ url(r'^customer-profile/(?P<pk>\d+)$', views.CustomerDetailView.as_view(), name='active_customer_profile'),] View class CustomerDetailView(generic.DetailView): model = active_customer context_object_name = "active_customer_profile" template_name = "nbn/active_customer_profile.html" Template <h4>Customer Addresses</h4> {% for active_service in active_customer_profile.active_service_set.all %} <li>{{ active_service.suburb }}</li> {% empty %} <li>No addresses found, contact IT.</li> {% endfor … -
Wagtail can't access images on S3 - I/O operation on closed file
I'm trying to get Wagtail to store and serve images from an AWS S3 bucket. I have followed the instructions and have it working great in a test environment, however when I switch to the Production Database and Bucket, I run into problems using the Admin and occasionally the frontend too. I have: boto3==1.4.8 botocore==1.8.1 wagtail==1.10c1 python 2.7 What I do: I go to /admin/, browse Images, it shows a list of image thumbnails (so far so good) I click on one of them and I get a Django error: ValueError at /admin/images/4236/ I/O operation on closed file The exception says: /usr/lib/python2.7/StringIO.py in tell _complain_ifclosed(self.closed) ... /usr/lib/python2.7/StringIO.py in _complain_ifclosed raise ValueError, "I/O operation on closed file" ... But, like I said, it works in a new test environment with only a few images. The issue seems to be a time out. We have about 4,000 original images (and then results in about 18,000 resized images). They are all in the one collection. Is there any way to increase the time out on this operation so that it doesn't time out? I can see the database has values for width, height, file_size columns; why is Wagtail trying to read this info … -
Django rest framework with djoser customise token authentication response
As i am using a third party package called djoser to handle the token authentication. i want to customise the response. But after trying to change it, the result is not what i wanted. Here is the link to djoser: https://github.com/sunscrapers/djoser Here is my code : models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) ethnicGroup = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return self.username serializer.py class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) default_error_messages = { 'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR, 'inactive_account': constants.INACTIVE_ACCOUNT_ERROR, } def __init__(self, *args, **kwargs): super(TokenCreateSerializer, self).__init__(*args, **kwargs) self.user = None self.fields[User.USERNAME_FIELD] = serializers.CharField( required=False ) def validate(self, attrs): self.user = authenticate( username=attrs.get(User.USERNAME_FIELD), password=attrs.get('password') ) self._validate_user_exists(self.user) self._validate_user_is_active(self.user) return attrs def _validate_user_exists(self, user): if not user: self.fail('invalid_credentials') def _validate_user_is_active(self, user): if not user.is_active: self.fail('inactive_account') views.py class TokenCreateView(utils.ActionViewMixin, generics.GenericAPIView): """ Use this endpoint to obtain user authentication token. """ serializer_class = settings.SERIALIZERS.token_create permission_classes = [permissions.AllowAny] def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token return Response( data=token_serializer_class(token).data, status=status.HTTP_200_OK, ) my custom serializer.py class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) class Meta: model = MyUser def __init__(self, *args, **kwargs): super(TokenCreateSerializer, self).__init__(*args, **kwargs) self.user = … -
python-docx Table column position and order
I used python-docx module to create Tables. I have a dabase table named data, and I get it by django queryset. The python-docx Table values' code like below: heading_cells = table.rows[0].cells keys = data[0].keys() keys = list(keys) for r in range(len(keys)): heading_cells[r].text = keys[r] values = list(data[i].values()) for r in range(len(keys)): device_table.cell(i + 1, r).text = str(values[r]) I got the Table in my .doc successfully. My problem is: I want to add a column Leftmost, how to do it? and I want to modify every columns position like the first column is id ,the second is name...... how to do it? Thanks! -
Django queryset list that have expanded relational model data
In my Django webapp, I have Function Based API that display a list for with pagination. The problem is I want each row in the list to have expanded output of relational field. This is my model for attendance: class Attendance(models.Model): CHECKIN = 1 CHECKOUT = 2 ATTENDANCE_TYPE_CHOICES = ( (CHECKIN, "Check In"), (CHECKOUT, "Check Out"), ) employee = models.ForeignKey(Employee) company = models.ForeignKey(Company) activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN) This is part of my list API where I define what fields I want to display and is paginated. employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).values("id","employee","company","activity_type").order_by('id') page = request.GET.get('page', request.POST['page']) paginator = Paginator(employee_list, request.POST['page_limit']) try: employees = paginator.page(page) except PageNotAnInteger: employees = paginator.page(request.POST['page']) except EmptyPage: employees = paginator.page(paginator.num_pages) return Response(list(employees), status=status.HTTP_200_OK) The output is a list like this but without employee detail. [ { "id": 14, "employee": 15, "company": 15, "activity_type": 1, }, { "id": 15, "employee": 15, "company": 15, "activity_type": 2, } ] My expected output, how do I get something like this ? [ { "id": 14, "employee": { "id":"2", "name":"Michael" }, "company": 15, "activity_type": 1, }, { "id": 15, "employee": { "id":"2", "name":"Jeniffer" }, "company": 15, "activity_type": 2, } ] How can I produce a list that shows the relational … -
Sort and set REST API data into a new list
I'm trying to create a report table based from an API, but the API currently is not sorted as I wanted it to be and I'm not sure how to rearrange it. Here's an example of how the API that look like this : [ { "task": { "id": 2, "name": "Texturing", }, "assign_to": { "id": 1, "official_name": "Roy Harper", }, "duration": 3.0, }, { "task": { "id": 4, "name": "Lighting", }, "assign_to": { "id": 3, "official_name": "Donna Troy", }, "duration": 4.0, }, { "task": { "id": 8, "name": "Rendering", }, "assign_to": { "id": 1, "official_name": "Roy Harper", }, "duration": 7.0, }, { "task": { "id": 11, "name": "Coloring", }, "assign_to": { "id": 3, "official_name": "Donna Troy", }, "duration": 5.0, }, { ] What i trying to achieve now, is an API list that centralize on the assign_to field and also set the list so it only populate the same person once. here's how the desired output that I trying to achieve : [ { "assign_to": { "id": 1, "official_name": "Roy Harper", }, "total_task"[ "task":{ "id": 4, "name": "Lighting", }, "duration": 3.0, "task":{ "id": 8, "name": "Rendering", }, "duration": 7.0, ], }, { "assign_to": { "id": 3, "official_name": "Donna Troy", … -
How do I handle multiple choice using Django?
Suppose I have a model with a multiple choice field and 4 options. This would be passed to the template and rendered on the HTML page. I want the user to select an option, and then process the option and return either "Correct" or "incorrect". I'm not too sure how to go on about starting this, any help is so much appreciated. -
Django cannot import models into commands
I have an app with the following folder structure: - project - dashboard - consumption - management - commands - command.py - models.py - dashboard - data And what I'm trying to do is import models.py into command.py with following import: from dashboard.consumption.models import * But I get the following error: ModuleNotFoundError: No module named 'dashboard.consumption' Despite my installed apps in settings.py being: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'consumption', ] Any idea why the import isn't working? -
Cannot login with Django custom login
So i do not want to use the inbuilt login in Django .Going about a custom login is very important to my project. So i created a custom login using function base view ,but when i try to log in ,i can not login , but instead i get a display message stating, "the user already exist". As if i am trying to create an account . Bellow is my lfunction base view code to login user . # Login account def login_view(request): if request.method == 'POST': form= UserLoginForm(request.POST) if form.is_valid(): username=form.cleaned_data['username'] password=form.cleaned_data['password'] user = authenticate(username=username,password=password) if user is not None: if user.is_active: login(request,user) return rederict('gbiz1990:businesshub') else: print("invalid login details" + username +""+password) form=UserLoginForm() return render(request,'gbiz1990/user_account/login.html',{'form':form}) else: form=UserLoginForm() return render(request,'gbiz1990/user_account/login.html',{'form':form}) form.py class UserLoginForm(forms.ModelForm): class Meta: exclude=['first_name','last_name','email'] widgets={ 'password':forms.PasswordInput(attrs={'class':'password'}), 'username':forms.TextInput(attrs={'class':'name'}), } model =User fields=['username','password'] So please help me to find out ,where i am my going wrong with my code .Thanks in advance -
Unable to save response data to instance's fields; other data in same block is saved correctly (Django/Celery)
I'm running a task to create an account on a third-party service and save relevant data from that service's response to my profile object. The data is getting returned correctly but not being properly saved on the object. Relevant code: # payload is generated in helper method. if that was the point of # failure, i'd see an error result = self.third_party_client.post(self.creation_endpoint, payload) json_result = result.json() if json_result.get('Error') != 'SUCCESS': # Account Creation Failed. error is handled. else: # Currently I log this on our staging server to make sure # the data's coming back properly; it is returned as expected self.logger.error('CoreCard Account Created. Data: {}'.format(json_result)) profile = user.profile profile.account_number = json_result.get('AccountNumber') profile.card_number_last_four = int(json_result.get('CardNumber')[12:]) profile.customer_id = json_result.get('CustomerID') profile.account_creation_datetime = datetime.datetime.utcnow() profile.save() So if I then query this profile instance, it has the account_creation_datetime value as expected, but the other fields are blank. I've checked the logs and the json_result values are all correct. Now here's where it's a bit weird. Where I think it's actually failing is the celery task that calls the utility that runs this bit of code. If I run this utility manually, the fields are saved properly. If I run it as part of our … -
Django raising ValueError: invalid literal for int() with base 10 on POST
Django is consistently throwing a ValueError on every POST request to the server. From cruising around forms and SE, it seems like this an issue with my Django models. However, I'm not sure why the models would throw this error or why they would be called by Django since this is thrown in a POST event. View in question: def channel(request, channel): user_form = weblog_userForm(request.POST or None) if request.method == 'POST' and user_form.is_valid(): nickname = user_form.cleaned_data['nickname'] message = user_form.cleaned_data['message'] password = user_form.cleaned_data['password'] postDetails = {} ... process request and eventually ... return HttpResponse(json.dumps(postDetails), content_type="application/json") My application models: class Line(models.Model): message = models.TextField(blank=True, default="") nick = models.CharField(max_length=50) hostname = models.CharField(max_length=300) channel = models.CharField(max_length=200) timestamp = models.DateTimeField(auto_now_add=True) LINE_TYPES = ( ('PMSG', 'PRIVMSG'), ('SMSG', 'SOCKETMSG'), ('WMSG', 'WEBMSG'), ('NTCE', 'NOTICE'), ('ACTN', 'ACTION'), ('JOIN', 'JOIN'), ('PART', 'PART'), ('QUIT', 'QUIT'), ('NICK', 'NICK'), ('TPIC', 'TOPIC'), ) msgType = models.CharField(max_length=4, choices=LINE_TYPES, default='PRIVMSG') def __str__(self): return self.message class banned_ips(models.Model): bannedIp = models.GenericIPAddressField() Traceback: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/weblogs/log/views.py", line 96, in channel json_data = serializers.serialize("json", list(reversed(Line.objects.filter(id__gt=latest_line_id, channel=channel).order_by('-id')[:100]))) …