Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to limit usage for freemium django app
I'am just struggling to figure out how can I limit my app usage for freemium users. Basically I want to make a variable on my model which I can set the usage limit for freemium usage, ex. allowing them 100 request per day. I found django ratelimit app. However I`am just wondering is there any other way to make this. -
Django REST Custom (token) authentication
Because I'm mixing things up and just making myself more confused, maybe someone can actually guide me through it. I need to make a Django REST API that requires login. However the User table already exists in a Postgres database. I think token-based authentication is most suitable, however, those tokens don't exist yet. (Login once to retrieve/create a token, check the token on each request) How can I use a POST request to submit login details purely for verifying the user? How would I generate a token upon successful login, and should I store it in a new Token table? After this, how can I use the token to provide authentication/authorization on API data requests? All examples I can find use the default Django User model or don't go into enough detail, which I can't use in this case. I've made a custom authenticator that checks the username and password, however I can't get through the next steps. from api.models import LogonAccount from rest_framework import authentication from rest_framework import exceptions import bcrypt class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.data.get('username') # get the username request header password = request.data.get('password') # get the password request header if not username or not … -
This is a result portal application, I keep getting this ' Reverse for 'pdf' not found. 'pdf' is not a valid view function or pattern name' error
from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse from io import BytesIO from django.shortcuts import redirect, render, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.views import PasswordChangeView from django.contrib.auth import update_session_auth_hash from django.contrib.auth import authenticate, login from django.views.generic import TemplateView, View from django.contrib.auth.models import User from results.models import DeclareResult from django.http import JsonResponse from django.urls import reverse_lazy from django.core import serializers import json from student_classes.models import StudentClass from results.models import DeclareResult from subjects.models import Subject from students.models import Student def index(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] print("\nUser Name = ",username) print("Password = ",password) user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('dashboard:dashboard') else: context = {'message':'Invalid Username and Password'} return render(request, 'index.html', context) return render(request, 'index.html', {'name': 'Risky', 'pass': 'risky'}) class DashboardView(LoginRequiredMixin,TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super(DashboardView, self).get_context_data(**kwargs) context['cls'] = StudentClass.objects.count() context['results'] = DeclareResult.objects.count() context['students'] = Student.objects.count() context['subjects'] = Subject.objects.count() return context def find_result_view(request): student_class = DeclareResult.objects.all() if request.method == "POST": data = request.POST # data = json.loads(form) roll = int(data['rollid']) pk = int(data['class']) clss = get_object_or_404(DeclareResult, pk=pk) if clss.select_student.student_roll == roll: data = { 'pk': data['class'] } return JsonResponse(data) … -
Using mock objects to test Python/Django models
I'm building some Django models I'd like to test. I'm trying to avoid having to create lots of unnecessary objects purely to run unit tests. I thought unittest.mock might help with this but I'm really struggling to understand its operation. All the tutorial examples seem to relate to mocking external API calls which is a use case I think I understand but I'm beginning to think either it might not be applicable to my situation or I'm just misunderstanding it completely. This is a typical model: class Foo(models.Model): id = models.AutoField(primary_key=True) bar = models.ForeignKey(Bar, models.RESTRICT) ...other FKs baz = models.PositiveIntegerField() def do_something(self): return True if self.baz > 10 else False And my issue is I want to test do_something() but I don't want to create a full Foo object with objects for all those FKs. I was hoping I could do something like this, but clearly I've got something wrong along the way. @patch('models.foo.Foo') class FooTestCase(TestCase): def test_foo_do_something(self, foo): f = foo() f.baz = 20 self.assertTrue(f.do_something()) Can anyone show me where I'm going wrong? -
Different Output in While Loop in Django Python
I have a while loop function. But they give code 1 and code 2 different outputs. Why is this so? len(yourSkills) = 7 Code 1 def getSkills(): i = 0 while i < len(yourSkills): skill = "<li>" + yourSkills[i] + "<span class='percent'>" + skillsPercent[i] + "</span></li>" i += 1 if i == len(yourSkills): return html.unescape(skill) Code 2 def getSkills(): i = 0 while i < len(yourSkills): skill = "<li>" + yourSkills[i] + "<span class='percent'>" + skillsPercent[i] + "</span></li>" if i == len(yourSkills): return html.unescape(skill) i += 1 Code 1 Output is = 7 Code 2 Output is = none -
Django - return char-field for each object in model
Goal: I'm trying to allow for the saving of each players score when saving a game using the create view. So for each object that is returned for Person a char-field should be shown in the create view. Current: What's currently happening is all of the Person objects are showing up in a char-field and are able to be selected but there is no where to enter the score. How can I show a char-field for each Person object that is returned in my Game create view? (Note: I been through both of these questions & tried all the answers with no luck. Q1 Q2) Model: class Game(models.Model): name = models.CharField(verbose_name="Game Title", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) person = models.ManyToManyField( Person, through='GamePlayers', related_name='person' ) class GamePlayers(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) score = models.CharField(max_length=6) Forms: class GameCreationForm(forms.ModelForm): class Meta: model = Game fields = ('__all__') Views: class GameSaveView(CreateView): model = Game form_class = GameCreationForm success_url = 'game/game_details.html' -
Django: order set queries
I have following 3 models class Product(models.Model): name = models.CharField( blank=False, max_length=256 ) class TaskGroup(models.Model): name = models.CharField( blank=False, max_length=256 ) product = models.ForeignKey( Product, on_delete=models.CASCADE, null=False, blank=True ) class Task(models.Model): name = models.CharField( blank=False, max_length=256 ) task_group = models.ForeignKey( TaskGroup, on_delete=models.CASCADE, null=False, blank=True ) execute_at = models.DateField( blank=True null=True, ) I want to get task groups for a product and order the tasks for each task group by execute_at. I can get all the task groups and all the tasks for a product by product = Product.objects.first() task_groups = product.taskgroup_set.all() task_groups contains all the groups and all tasks for each group. How can I order the tasks of each groups by execute_at. -
Delete model and DB table in Django with migrations
I have two models: Clause and Template, they have been migrated locally, but I want to delete one of them. The question is: If I just delete it from models.py and admin.py, and run makemigration and migrate, will delete and the related DB table as well? -
Getting a field from another django model?
How can I get the field pto from emplyees app and use it in the permission app. employee/models.py class Employee(AbstractUser): department = models.ForeignKey(Department, on_delete=models.CASCADE,blank=True, null=True) pto = models.IntegerField(default=20) is_deleted = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) roles = models.ManyToManyField(Role, related_name='+') def __str__(self): return self.username permission/models.py class Permission(models.Model): STATUS = ( ('PENDING', 'PENDING'), ('DENIED', 'DENIED'), ('ACCEPTED', 'ACCEPTED') ) user = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='lorem') description = models.CharField(max_length=255) date_created = models.DateTimeField(auto_now=True, blank=True, null=True) date = models.DateField() status = models.CharField(max_length=200, choices=STATUS, default=STATUS[0][0]) is_deleted = models.BooleanField(default=False) def __str__(self): return self.description sorry if a was not clear, thanks in advance -
If object exist move me here if not here, PYTHON>Django
i have little issue: I have created an organigram in which I have a list of managers and when I click on a manager the link takes me to a list of their sub employees, but some managers do not have any employees under them and then an empty list is displayed. I am looking for a solution where the link redirects to 1 of 2 links: 1. If "the manager has employees moves to the list", 2. if "manager has no employees moves to X(another employee details link)" Solution that looks in the database for sub employees if they are there then link 1, if not there then link 2. my models:Managers Managers2 my views:Manager views Manager2 views my urls:Urls my main site where link is:Main -
serialize nested objects in djangoresetframework
i am using django-mptt for implement nested categories. this is my model : class Category(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") i have some nested objects like mobile --> samsung --> s_group and so on. i want to serialize all the children categories when return parent category something like this : { "name" : "mobile", "children" :{ "name" : "samsung", "children" { "name" : "s_group", "children" : { "name" : "something", "children" : {} } } } how can i implemnt this? -
django-bootstrap4 doesnt recognize forms passed to context
Im trying to pass two forms in to my view: @login_required() def register(request): registered = False if request.method == 'POST': user_form = UserCreateForm(data=request.POST) profile_form = ProfileCreationForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'logo' in request.FILES: profile.logo = request.FILES['logo'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserCreateForm() profile_form = ProfileCreationForm() return render(request, 'companies/registration.html', {'form': user_form, 'profile_form': profile_form, 'registered': registered}) Then in my html Im calling the two forms using django-bootstrap4: {% extends 'base.html' %} {% load bootstrap4 %} {% block content %} {% load static %} <div class="container"> {% if registered %} <p>Thank you for registering</p> {% else %} <div class="form-group mt-5"> <h3>Register</h3> <form method="POST"> {% csrf_token %} {% bootstrap_form user_form %} {% bootstrap_form profile_form %} <input class="btn btn-primary" type="submit" value="Register"> </form> </div> {% endif %} </div> {% endblock %} As a result I get the error: raise BootstrapError('Parameter "form" should contain a valid Django Form.') bootstrap4.exceptions.BootstrapError: Parameter "form" should contain a valid Django Form. [06/Apr/2021 13:57:47] "GET /companies/register/ HTTP/1.1" 500 162738 The same time if I pass in only one form and call it 'form' then no errors appear: from views: return render(request, 'companies/registration.html', {'form': user_form, 'profile_form': … -
Avoiding InconsistentMigrationHistory with explicit inserts in migrations
I have a little problem with the order of the migrations. The fact is that in my database there is a "Products" model whose migration is one of the first in the history list, call it 001_products. After this migration, others are executed that make inserts in this same table (some inserts necessary for the basic operation of the application), called migration 002_inserts_products. The problem appeared when modifying the "Products" model, call it 003_modify_products migration. The migration was applied after the inserts and made the tests fail (tests that generate a test database doing all the migrations), which followed this order: 001_products 002_inserts_products 003_modify_products The solution then was to add a dependency on migrations that made inserts in "Products" with respect to the subsequent migration that modified that table. That is, make 002_inserts_products dependent on 003_modify_products. However, this, which worked in the tests and locally (where the modification in "Products" had already been applied), does not work in production, since there the migration that has not been applied is the one that modifies the "Products" model ". That is, the panorama in production is: [X] 001_products [X] 002_inserts_products [ ] 003_modify_products When trying to do the new migration, the error … -
Django cropper.js is rotating the elongated portrait images in mobile view
Hi I have been following this tutorial for making cropper.js worked in my Django app. The issue is, that whenever I try to upload an image in mobile view the canvas rotates the image. Like this: Can anyone please point out what the issue is and how can I prevent this? -
How to Upgrade Amazon Elastic Beanstalk Linux 1 to Linux 2 for Django Application
I am trying to upgrade a Django application from AWS Elastic Beans Python 3.6 running on 64bit Amazon Linux/2.9.20 to Python 3.8 running on 64bit Amazon Linux 2/3.2.0. It runs locally. When I try and deploy to Elastic Beanstalk I'm getting the following error: Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/current/src/core/wsgi.py", line 14, in <module> Apr 6 10:30:48 ip-172-31-43-9 web: application = get_wsgi_application() Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application Apr 6 10:30:48 ip-172-31-43-9 web: django.setup(set_prefix=False) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/__init__.py", line 19, in setup Apr 6 10:30:48 ip-172-31-43-9 web: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ Apr 6 10:30:48 ip-172-31-43-9 web: self._setup(name) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup Apr 6 10:30:48 ip-172-31-43-9 web: self._wrapped = Settings(settings_module) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ Apr 6 10:30:48 ip-172-31-43-9 web: mod = importlib.import_module(self.SETTINGS_MODULE) Apr 6 10:30:48 ip-172-31-43-9 web: File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module Apr 6 10:30:48 ip-172-31-43-9 web: return _bootstrap._gcd_import(name[level:], package, level) Apr 6 10:30:48 ip-172-31-43-9 web: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Apr 6 10:30:48 ip-172-31-43-9 web: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Apr 6 10:30:48 … -
DRF OPTIONS request - include initial/default choices
I'm using options to populate select inputs in my project. Is there a way to include also information about default values? For this field: DELIVERY_METHOD__SHIPPING_ONLY = 'shipping_only' DELIVERY_METHOD__LOCAL_PICKUP_ONLY = 'local_pickup_only' DELIVERY_METHOD__SHIPPING_AND_LOCAL_PICKUP = 'shipping_and_local_pickup' DELIVERY_METHOD_CHOICES = ( (DELIVERY_METHOD__SHIPPING_ONLY, 'Shipping only'), (DELIVERY_METHOD__LOCAL_PICKUP_ONLY, 'Local pickup only'), (DELIVERY_METHOD__SHIPPING_AND_LOCAL_PICKUP, 'Shipping & local pickup'), ) delivery_method = models.CharField(max_length=32, choices=DELIVERY_METHOD_CHOICES, default=DELIVERY_METHOD__SHIPPING_ONLY) The OPTIONS actions.POST.delivery_method is this: "delivery_method": { "type": "choice", "required": false, "read_only": false, "label": "Delivery method", "choices": [ { "value": "shipping_only", "display_name": "Shipping only" }, { "value": "local_pickup_only", "display_name": "Local pickup only" }, { "value": "shipping_and_local_pickup", "display_name": "Shipping & local pickup" } ] }, But it should also say that Shipping only is the default one so I can prepopulate the input with this value. Is there a built-in way to do that? -
How to run a project in single docker container and run the installed dependencies of project in docker filesystem instead of using docker images?
I am new to docker I am noob and I have a full running application in docker consist of multiple containers responsible to run the project. I want to make the container image and gave it to the client but when I pushed my project to docker-hub it can only contain one container in the repository at a time. So, now I want to work with single container instead of using the multiple containers running MySQL and Redis as the dependencies of project. So, I installed redis and MySQL inside the docker file-system using bash of my container. But my project is not working without running my project I cannot start the redis and MySQL installed inside the container which is running on Debian Linux and when I run my project I can access the bash of my container and start the services but still my django app in the container is giving errors relevant to SQL. Can anyone tell me how to tackle this situation? -
Send Django-form to other server for data-handling
I have a Django app which is hosted on Google App Engine. One of the models consist of three fields class product_prices(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,null=True) start_price = models.FloatField(default=0) last_price = models.FloatField(default=0) data = models.TextField(max_length=512) I want to do some database calls, based on the information entered, and then alter the data-field, the last-price based on the data returned from the database, e.g in my (pseudo) view below, I call MyDatabaseFunctionCall(form) to do those calculations. What I would prefer is, to have that calculation being on another server with some more CPU/RAM such that I don't slow down GAE hosting my application. #Current views.py on GAE def add_link_to_track(request): user = request.user instance = MyModel(user=user) if request.method == "POST": form = MyForm(request.POST,instance = instance) if form.is_valid(): #Create the dummy-model form.save() #Do the calculation in the back-ground thr = threading.Thread(target=MyDatabaseFunctionCall,args=(form,),daemon=True) #Alters the data thr.start() return redirect("my_site") else: form = MyForm() return render(request, "my_site/my_template.html",context=context) Can a form-instance e.g be pickled and thus send back-n-forth between servers in some way? Or is it better having a "temp-database" that I push the form information to uppon creation and then having the compute-server monitoring that database such that it can pull new forms, alter … -
AWS resend invite link after expiration
from the boto3 documentation i came to know we need to set the MessageAction="RESEND" to resend the invitation message to a user that already exists and reset the expiration limit on the user's account. def get_set_cognito(sender, instance, *args, **kwargs): self = instance if self.pk is None: client = boto3.client('cognito-idp', region_name=settings.AWS_DEFAULT_REGION) # try: # # Check if the user exists in Cognito # existing_user = client.admin_get_user(Username=self.user.email, # UserPoolId=settings.COGNITO_USER_POOL_ID) # except client.exceptions.UserNotFoundException: # pass try: # if not existing_user: response = client.admin_create_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email, ForceAliasCreation=True|False, MessageAction='RESEND', DesiredDeliveryMediums=['EMAIL'], UserAttributes=[ { 'Name': 'custom:backend_url', 'Value': settings.BACKEND_API_URL }, { 'Name': 'custom:backend_id', 'Value': settings.BACKEND_ID }, { 'Name': 'email_verified', 'Value': 'true' }, { 'Name': 'email', 'Value': self.user.email }, { 'Name': 'family_name', 'Value': self.last_name if self.last_name else ' ' }, { 'Name': 'given_name', 'Value': self.first_name if self.first_name else ' ' }, { 'Name': 'phone_number', 'Value': self.phone if self.phone else ' ' } ], ) self.user.username = response['User']['Username'] if(len(response['User']['Username']) < 3): logger.error("empty response from cognito for email - " + self.user.email) logger.error(response) self.user.delete() else: self.user.save() # else: # self.user.username = existing_user['Username'] # self.user.save() except client.exceptions.UsernameExistsException: # existing_user = client.admin_get_user(Username=self.user.email,UserPoolId=settings.COGNITO_USER_POOL_ID) existing_user = client.admin_get_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email ) self.user.username = existing_user['Username'] self.user.save() except Exception as e: logger.error( "there was an error trying to … -
is there way to add style to username field - django forms
is there way to add style to username field - django forms , i tried use self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username','style': 'font-size:24px;text-align: center;'}) but it's not work why class UserForm(forms.ModelForm): password = forms.CharField(required=True,label=' pass',widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':' pass ','style': 'font-size:24px;text-align: center;'})) first_name = forms.CharField(required=True,label=' first name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' first name ','style': 'font-size:24px;text-align: center;'}) ) last_name= forms.CharField(required=True,label=' 2nd name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' 2nd name ','style': 'font-size:24px;text-align: center;'}) ) email= forms.EmailField(required=True,label=' email ',widget=forms.EmailInput(attrs={'class': 'form-control','placeholder':' email ... youremail@email.com','style': 'font-size:24px;text-align: center;'}) ) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ('username','first_name','last_name','email','password') def __init__(self, *args, **kwargs): super(UserForm,self).__init__(*args,**kwargs) self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username','style': 'font-size:24px;text-align: center;'}) -
What If I compile the py manage.py collectstatics?
What If I compile the py manage.py collectstatics? I am on my localhost. I have configured all the s3 url accourding to given url. We can see on last paragraph then it's telling run python manage.py collectstatic . My question is why we are doing this? Do we need to run this on every static or media changes? I tried to run this but it asking do you want to override this? Can I simply do yes? If I give yes then what will happen? I am not much aware in this topic collectstatics -
Getting wrong value when reading an xlsx file using openpyxl
i'm trying to read values from an xlsx file containing formulas using openpyxl, i noticed that for some cells i'm getting a wrong value. here's the XLSX exemple. the result i get. and the code: wb = openpyxl.load_workbook(excel_file, data_only=True) # getting all sheets sheets = wb.sheetnames print(sheets) # getting a particular sheet worksheet = wb["Feuil1"] print(worksheet) # getting active sheet active_sheet = wb.active print(active_sheet) # reading a cell print(worksheet["A1"].value) excel_data = list() # iterating over the rows and # getting value from each cell in row for row in worksheet.iter_rows(): row_data = list() for cell in row: #cell.number_format='0.0########' print(cell.number_format) row_data.append(str(cell.value)) print(cell.value) excel_data.append(row_data) return render(request, 'myapp/index.html', {"excel_data":excel_data}) -
How do i share my django models with a child process using python multiprocessing?
I am trying to pass my django models to another child process, for that i am using the following code from multiprocessing import Process from multiprocessing.managers import BaseManager from role.models import Role from group.models import Group from kafka import KafkaConsumer class KafkaProcessManager(BaseManager): pass def consume_events(kafka_ip_port, events_topic, Role, Group): # To consume latest messages and auto-commit offsets consumer = KafkaConsumer(events_topic, bootstrap_servers=[kafka_ip_port]) for message in consumer: print ("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition, message.offset, message.key, message.value)) #if (message["MODEL"] == "UserFeature" and message["TYPE"] == "DEACTIVATED"): group = Group.objects.get(id=1) group.description = "UPDATED AFTER CONSUMING EVENT THROUGH CHILD PROCESS" group.save() kafka_manager = KafkaProcessManager() kafka_manager.register('Role', Role) kafka_manager.register('Group', Group) kafka_manager.start() Role = kafka_manager.Role() consumer = Process(target=consume_events, args=(kafka_ip_port, events_topic, Role, Group, )) consumer.start() consumer.join() The intention is to do some processing/updating when a certain message (event) is receieved. But i am getting an error on line Role = kafka_manager.Role() AttributeError: Manager isn't accessible via Role instances. Can anyone guide me how to pass the model instances to the child process. Thanks is advance. -
Django REST framework POST without insert
I'm building a Django REST API which has access to our existing database with existing users. The purpose of this API is allowing the upcoming mobile application to make requests. I'm sending a post request to a view with custom authenticator to verify the sent account details. My existing model: class LogonAccount(models.Model): id = models.BigIntegerField(primary_key=True) email = models.TextField() two_step_enabled = models.BooleanField() password = models.TextField(blank=True, null=True) username = models.TextField(unique=True, blank=True, null=True) My View and Serializer class LogonAccountViewSet(viewsets.ModelViewSet): queryset = LogonAccount.objects.all().order_by('username') serializer_class = LogonAccountSerializer class LogonAccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = LogonAccount fields = ('username', 'email') Sending a post request to this endpoint with username and password in its body keeps returning me a bad request (400) with: { "username": [ "logon account with this username already exists." ], "email": [ "This field is required." ] } Making the fields not required in the serializer just changes the error to database constraints (null value in column id) class LogonAccountSerializer(serializers.HyperlinkedModelSerializer): username = serializers.CharField(required=False) email = serializers.CharField(required=False) class Meta: model = LogonAccount fields = ('username', 'email') I'm not trying to insert data, just trying to validate it. What am I doing wrong or how do I stop it from trying to insert data? -
Converting djangos object.values dict into native datatype?
I'm trying to get specific fields from my database using the object.values() attribute, as such: stocks = Stock.objects.values("ticker", "stock", "exchange__exchange_code", "earnings_yield", "roic") The reason I'm not using Stock.objects.filter()... is because I only need a subset of the fields, and as far as I know, values() is the way to go. stocks[0] returns this: { 'ticker': 'ATRLJ-B', 'stock': 'Atrium Ljungberg AB (publ)', 'exchange__exchange_code': 'ST', 'earnings_yield': Decimal('0.0250'), 'roic': Decimal('0.0200') } How do I get earnings_yield and roic as regular floats? E.g, proper JSON formatted I tried clean = json.dumps(list(stocks), cls=DjangoJSONEncoder) stocks = json.loads(clean) But that returns the decimals as strings, not decimals