Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am unable to use daterangepicker to my template for filter date-range. "Please help R" thanks in advance
Models.py class Expenses(models.Model): reg_date = models.DateField(auto_now_add=True) exp_id = models.AutoField(primary_key=True) # F description = models.CharField(max_length=200) expenses_value = models.IntegerField() def __str__(self): return str(self.exp_id) forms.py class Expensesform(forms.ModelForm): description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":40,'class':'form-control','placeholder':'Enter Detail here...'}),required=True) expenses_value = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Amount here...'}),required=True) class Meta: model = Expenses fields = ("description", "expenses_value") i used code base date which is working fine. but i am unable to user date-range picker input for costume date range result. mean user can use daterange picker to calculate expenses for such date range views.py def DailyExpReport(request): tday = datetime.date.today() datepicker1 = datetime.datetime.strptime('01072019', "%m%d%Y").date() total = 0 myexpenses = Expenses.objects.filter(reg_date__gte = start_Date, reg_date__lte=tday) today_entry = Expenses.objects.filter(reg_date__gte = start_Date, reg_date__lte=tday).aggregate( Sum('expenses_value')) return render (request, "blog/expenses_report.html",{'Expenses':myexpenses, 'total': today_entry}) Here is my template which is working fine for daily report or for specific coded date <!DOCTYPE html> {% extends "blog/base.html"%} {% block body_block %} <h1>Expenses Detail:</h1> <br> <div class="container"> <table class = "table"table table-striped table-bordered table-sm> <thead calss= "thead-dark"> <tr> <th>Date</th> <th>ID</th> <th>Description</th> <th>Expences Value</th> </tr> </thead> <tbody> {% for object in Expenses %} <tr> <td>{{object.reg_date }}</td> <td>{{object.exp_id }}</td> <td>{{object.description}}</td> <td>{{object.expenses_value}}</td> <td> <a href="/editexpenses/{{object.exp_id}}"><span calss = "glyphicon glyphicon-pencil">Edit</span> </a> <a href="/deleteexpenses/{{object.exp_id}}" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a> </td> </tr> {% endfor%} </tbody> </table> … -
Where to get a detailed information about sessions in Django?
guys! I wanna to develop my own server via Django and now I want to understand how to work with sessions and cookies in Django. I'm interested in different examples, because I found a lot of theory, but I can't find good examples of implementation. So if someone has any books/tutorial/links where I can get acquainted with sessions in django, then I will be glad if you share the information. -
usercreationform doesn't show any field
I'm new to django and as my first project I'm trying to make a website which has a sign up page. In order to do that I'm trying to use UserCreationForm method. I don't get any errors and everything is just fine. The only problem is that it doesn't show any username or password field in the web page. I mean in doesn't show any field that the UserCreationForm is supposed to show. I searched a lot and I didn't find any related answer from django.shortcuts import render, redirect from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserCreationForm() return render(request, 'users/register.html', {'from': form}) -
Import Python file which contains pySpark functions into Django app
I'm trying to import in views.py of my Django app, a python file "load_model.py" which contains my custom pyspark API but I got an error And I can't figure out how to solve it. I import the file "load-model.py" with a simple: import load_model as lm My load_model.py contains the following code (this is just part of the code): import findspark # findspark.init('/home/student/spark-2.1.1-bin-hadoop2.7') findspark.init('/Users/fabiomagarelli/spark-2.4.3-bin-hadoop2.7') from pyspark.sql import SparkSession from pyspark.ml.regression import RandomForestRegressionModel from pyspark.ml.linalg import Vectors from pyspark.ml.feature import VectorAssembler from pyspark.sql import Row from collections import OrderedDict spark = SparkSession.builder.appName('RForest_Regression').getOrCreate() sc = spark.sparkContext model = RandomForestRegressionModel.load('model/') def predict(df): predictions = model.transform(df) return int(predictions.select('prediction').collect()[0].prediction) # etc... ... ... when I lunch python manage.py run server on my command line, I get this error log: 19/07/20 07:22:06 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties Setting default log level to "WARN". To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 323, … -
My coupoun view doens't perform post request.It performs get which i don't want?
I made a coupon view which can basically see if the coupon exists and if it exists than reduce the amount of the total order but i get a strange csrf token in the url when i perform post Here's the coupon view def get_coupon(request, code): try: coupon = Coupoun.objects.filter(code=code) return coupon except ObjectDoesNotExist: messages.info(request, "This coupon does not exist") return redirect("item:cart") class Coupoun_view(generic.View): # First i have to get the order and the coupoun and then i have to detuct the amount the coupoun will use # If the order has a copoun then he can't use it again def post(self,*args,**kwargs): form = Coupoun_Form(self.request.POST or None) if form.is_valid(): code = form.cleaned_data.get("code") order = Order.objects.get( user=self.request.user, ordered=False) order.coupoun = get_coupon(self.request, code) print(order.coupoun) order.save() messages.success(self.request, "Successfully added coupon") return redirect("item:cart") Here's my cart view which will render out the form class Cart_View(generic.View,LoginRequiredMixin): def get(self,*args,**kwargs): order_item = OrderItem.objects.filter(user=self.request.user,ordered=False)[:3] # This is just for calling the subtotoal price of these 3 orders try: order_mini = Order.objects.get(user=self.request.user,ordered=False) qs1 = get_object_or_404(Order,user=self.request.user,ordered=False) # If the order is ordered and there is no order item which isn't ordered, # then there would be no order_item and hence there would be no order so i set them to … -
How to Implement 3-way Dependent/Chained Dropdown List with Django?
I am using django and postgresql. I'm dealing with a 3-way dependent drop-down list. After adding the country selection, the province area is automatically updated depending on the selected country. After selecting a province, the county field opens only when the page is refreshed. I would be glad if you help me in this regard. models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class District(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=100) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) district = models.ForeignKey(District, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py from django import forms from .models import Person, Country, City, District class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'birthdate', 'country', 'city', 'district') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['district'].queryset = District.objects.none() … -
How to Create and change Dynamic shared and periodic_tasks tasks by api in Django
I'm using Celery to run periodic_tasks and schedule task. @shared_task def first(city): print(city) @celery_app.on_after_finalize.connect def first_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(minute=0, hour=15), job.s('test'), ) @celery_app.task def job(arg): print(arf) I want to create second_periodic_tasks dynamic using my api. AND I also want to change first_periodic_tasks run time using my api. How can i do this using Celery? -
I got this error when installing psycopg2 in Centos7
I'm using pip install psycopg2 but i got this error; Centos7 Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/5c/1c/6997288da181277a0c2 9bc39a5f9143ff20b8c99f2a7d059cfb55163e165/psycopg2-2.8.3.tar.gz Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Complete output from command /var/www/vhosts/sample.com/httpdocs/venv/ bin/python3 -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-bi jd4pos/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__ );code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(cod e, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-86gg6c3t --python-t ag cp36: ERROR: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/errors.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_lru_cache.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/compat.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.6/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/psycopg gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protec tor-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic - D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_VERSION=2.8.3 (dt dec pq3 ext) -DPG_V ERSION_NUM=90224 -I/usr/include/python3.6m -I. -I/usr/include -I/usr/include/pgs ql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.6/psycopg/psyc opgmodule.o -Wdeclaration-after-statement In file included from psycopg/psycopgmodule.c:27:0: ./psycopg/psycopg.h:34:20: fatal error: Python.h: No such file or directory #include <Python.h> ^ compilation terminated. It appears you are missing some prerequisite to build the … -
Using custom schema in model's db_table
I have several schemas in postgresql. Now all of my django models are in public schema (i always have written db_table in models to manage table names). Now i need to migrate models from public schema (default) to new schema (named workadmin). How can i change postgres schema for my models? Change db_table to db_table = 'workadmin\".\"realty_land_plot' helped for many people, but those messages were for a long time ago. I have tried to use this way, but migrate command gave me the message: django.db.utils.ProgrammingError: ОШИБКА: ошибка синтаксиса (примерное положение: ".") LINE 1: ...TER TABLE "realty_land_plot" RENAME TO "workadmin"."realty_l... it means syntax error at "." symbol during alter table process. db_table = 'realty_land_plot' -
Why page is getting loaded even I use ajax?
I am using ajax to submit the form when I try to submit the form it is showing the error jquery-3.4.1.js:9837 POST http://127.0.0.1:8000/shop/tracker/ 404 (Not Found). I have added event.preventDefault(); still it is not working $.ajax({ type: 'POST', url: '/shop/tracker/', data: formData, encode: true }) .done(function(data) { console.log(data) updates = JSON.parse(data); if (updates.length > 0 & updates != {}) { for (i = 0; i < updates.length; i++) { let text = updates[i]['text']; let time = updates[i]['time']; mystr = <li class="list-group-item d-flex justify-content-between align-items-center"> ${text} <span class="badge badge-primary badge-pill">${time}</span> </li> $('#items').append(mystr); I am expecting the html output in the same page but there is no changes occuring. -
How to encrypt Messages in Django Channels
Well i have gone through the tutorials of django channels. But the is a loop hole since there is no explanation on how to encrypt a message in django channel. Lets say i have a chat models bellow class ChatThread(models.Model): name=models.CharField(null=True,max_length=200) class chat(models.Model): thread_id=models.ForeignKey(ChatThread,null=True) messages=models.TextField() I want the object of chat to be encrypted when created and decrypted on request within the application. Please i am new to python, so be kind with your explanations. Thanks -
No module named 'rest_frameworkoauth2_provider'
I am setting up a django rest api and need to integrate social login feature.I followed the following link Simple Facebook social Login using Django Rest Framework. After setting up all , when a migrate (7 th step :- python manage.py migrate ) , getting the error ' ModuleNotFoundError: No module named 'rest_frameworkoauth2_provider' ' . Is there any package i missed? i cant figure out the error. -
How do I connect Django to a DB2 database on IBM Cloud?
I am trying to create a simple data entry (CRUD) application using Django and DB2 on the Cloud. The question is, how do I actually do that? I started trying to follow this tutorial. It's not on the cloud, but it's specifically what I can found close about Django with DB2. Following my intuition, I created a credential on DB2 via IBM Cloud console and filled settings.py's DATABASES variable with the following: DATABASES = { 'default': { 'ENGINE': 'ibm_db_django', 'NAME': 'BLUDB', 'USER': '*********', 'PASSWORD': '***********', 'HOST':'**********.services.<loc>.bluemix.net', 'PORT': 5000, 'PCONNECT' : True, } } However, after trying to run python manage.py migrate, I got the following error: django.db.utils.Error: [IBM][CLI Driver] SQL1531N The connection failed because the name specified with the DSN connection string keyword could not be found in either the db2dsdriver.cfg configuration file or the db2cli.ini configuration file. Data source name specified in the connection string: "BLUDB". SQLCODE=-1531 Honestly, I had no idea what was going on. But after doing a little searching, I found this post on StackOverflow about the same problem. It had no real definite answer, but it leads me to this tutorial. Basically, I had a couple of stuff in the INSTALLED_APPS list like so: INSTALLED_APPS … -
Pass Authentication Basic without access to header
I am trying to create a mobile app in Thunkable x. It allows for cross-platform development. The problem that I have encountered is that they don't have an option where you can set dynamic data in the header. I have it so that users can enter a username and password then it will send it to my Django server where it will return the base64 of the login credentials. I have to send the credentials to my second API where it will authenticate and return the information that I want. Since I cant Access the Headers is there a way in which I can send the authentication that is not in the header? The body is able to be edited. -
How to control a variable from the Django template and increment it
I have a problem creating a slideshow (well more like a one way slideshow) with random sequence every time, and no repeated pictures. I do not know how to connect the "next" button with the previously made sequence and is it possible for the template to increment a python counter. def ChemistryView(request): all_private_keys = PostForChemistry.objects.all() list_of_private_keys = [post.id for post in all_private_keys] random_ids = random.shuffle(list_of_private_keys) priv = list_of_private_keys[0] i = 1 querysetforchem = PostForChemistry.objects.get(pk=list_of_private_keys[0]) context = { "querysetforchem" : querysetforchem, "list_of_private_keys" : list_of_private_keys } return render(request, 'main/chemistry.html', context) I want a single id object on screen at a time and for it to increment not to the bigger one, but to the next in the random list. -
navigating with animate, the navigation hides the top of the target area. How can I make the upper part visible in this case?
I have a question. When navigating with animate, the navigation hides the top of the target area. How can I make the upper part visible in this case? code $(".go_btn").click(function(){ const number = $(".go_input").val(); if(number == 1){ $('html, body').animate({ 'scrollTop' : $("#index_first").offset().bottom }); } $('html, body').animate({ 'scrollTop' : $("#index_"+number).offset().top }); }) -
Django 2.2 - Testcase - client.logout() method does not log out user
I am writing tests for my simple Django web application, checking if user can login and logout correctly. Views:user_login and user_logout def user_login(request): if request.method == 'POST': email = request.POST.get('email address') password = request.POST.get('password') user = authenticate(username=email, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('main_page:index')) else: print("\nWARNING: invalid login detected\n\nemail: {}\npassword: {}\n".format(email, password)) messages.error(request, 'Ivalid email or password. Try again.') return HttpResponseRedirect(reverse('users:login')) else: return render(request, 'users/login.html', {}) @login_required def user_logout(request): messages.add_message(request, messages.INFO, 'See you Space Cowboy!') logout(request) return HttpResponseRedirect(reverse('main_page:index')) And the tests themself: class LoginLogoutTests(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create_user(email='test_user@email.com', password='S6y4Mb9Aqfu79YcF') print("\nsetup") def tearDown(self): self.user print("teardown\n") def test_login(self): # test if email is equal self.assertEqual(self.user.email, 'test_user@email.com') # test authentication self.assertTrue(self.user.is_authenticated) self.assertFalse(self.user.is_anonymous) # test if login request index.html self.assertTrue(self.client.get('main_page.index.html')) # test login with valid credentials self.assertTrue(self.client.login(email='test_user@email.com', password='S6y4Mb9Aqfu79YcF')) # test login with invalid credentials self.assertFalse(self.client.login(email='test_user@email.com', password='password')) print("test login") def test_logout(self): self.client.logout() self.assertTrue(self.user.is_authenticated) self.assertFalse(self.user.is_anonymous) print("test logout\n") Tests return this output: (venv) [user@manjaro django-project]$ ./manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). setup test login teardown setup test logout teardown .... ---------------------------------------------------------------------- Ran 4 tests in 0.515s OK Destroying test database for alias 'default'... What goes here wrong? EDIT: I rebuilt user model … -
How to add external css/js in django2.2
How do i add an external css/js to my html template when working with django i've tried some previously asked questions reply but seem like they're outdated and below is one of the procedure i followed # after making sure the installed app has contrib.static then i make a file called static/my_apps/my.css {%loadstatic%} <link rel='stylesheet' href="{%static 'my_apps/my.css' %}"> # i also tried {%loadstaticfile%} but none work -
Django FormModel some fields aren't saved
I'm using a FormModel in Django but some fields are not saved to the database... models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.forms import ModelForm # Create your models here. class Bill(models.Model): image_name = models.CharField(max_length=150) upload_date = models.DateTimeField(default=timezone.now) image = models.ImageField() description = models.TextField(blank=True) result = models.CharField(max_length=1000) uploaded_by = models.OneToOneField(User, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.result + self.description) forms.py file from django import forms from django.db import models from django.forms import ModelForm from .models import Bill class BillForm(ModelForm): class Meta: model = Bill fields = ['image', 'description'] exclude = ['result', 'image_name', 'upload_date', 'uploaded_by'] views.py file def upload(request): if request.method == 'POST': form = BillForm(request.POST, request.FILES) if form.is_valid(): form.image_name = request.FILES['image'] form.upload_date = datetime.now() form.uploaded_by = request.user form.result = "something" form.save() return redirect('cism-home') else: form = BillForm() return render(request, 'auth/upload.html', {'form': form}) So the image and description fields are saved but other fields are not. Any ideas why is that? -
How to pass request over Django channels WebSocket and call Django view
I'm working on a single page application with Django, and would like to use WebSockets, and therefore Channels. To keep things simple, I think I want to handle all server communication over a WebSocket alone, rather than adding XHR (XML HTTP Request) into the mix. I'm using channels from the get-go since there will be a lot of data pushed from the server to the client asynchronously. With regular Django, a conventional request made to https://example.com/login or https://example.com/logout or whatever and the Django URL router will decide what view to send it to. Instead, I would like to have the user perform their action in the client, handle it with Javascript, and use the WebSocket to send the request to the server. Since I'm using Django-allauth, I would like to use the provided Django views to handle things like authentication. The server would then update the client with the necessary state information from the view. My question: how can I process the data received over the WebSocket and submit the HTTP request to the Django view? I can picture what would happen using XHR, but I'm trying to avoid mixing the two, unless someone can point out the usefulness in … -
Gunicorn ModuleNotFoundError: No module named 'django'
I'm trying to deploy a django application by following this tutorial. At the time of starting gunicorn, I use this command: gunicorn -b 127.0.0.1:8000 wsgi:application, being inside the folder where my wsgi.py is located. wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() And I get the following error: [2019-07-19 20:54:39 -0300] [7786] [INFO] Starting gunicorn 19.9.0 [2019-07-19 20:54:39 -0300] [7786] [INFO] Listening at: http://127.0.0.1:8000 (7786) [2019-07-19 20:54:39 -0300] [7786] [INFO] Using worker: sync [2019-07-19 20:54:39 -0300] [7789] [INFO] Booting worker with pid: 7789 [2019-07-19 20:54:39 -0300] [7789] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.6/dist-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/ubuntu/renato-sfera/mysite/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' [2019-07-19 20:54:39 -0300] [7789] [INFO] Worker exiting (pid: 7789) [2019-07-19 20:54:39 -0300] [7786] [INFO] Shutting down: Master [2019-07-19 20:54:39 -0300] [7786] [INFO] Reason: Worker failed to boot. What can … -
Django Rest Framework: get multiple source fields from reverse relation
My models: class A(models.Model): name = models.CharField('Name', max_length=250) content = models.TextField('Content') timestamp = models.DateTimeField(auto_now_add=True) b = models.ForeignKey('bs.B', blank=True, null=True, verbose_name='b', related_name='as') class B(models.Model): name = models.CharField('Name', max_length=250) description = models.TextField('Description') timestamp = models.DateTimeField(auto_now_add=True) I want to serialize my B model and include multiple fields in it, but not all of them. Creating serializer like this: class BSerializer(serializers.ModelSerializer): a_items = ASerializer(many=True, read_only=True, source='as') class Meta: model = B fields = '__all__' gives me B objects with a_items field, containing all of A fields, but I would like to get only name and content. I've seen this question and the answer, but unfortunately, since DRF 3.0, it no longer supports field_to_native() method. I would be grateful for any kind of hints where to start with this, since even trying to add source='as.name' doesn't seem to work and related objects just disappears. I tried with some random string following as. and it still does not fail, even though I would expect that. -
How to make REST API to iterate all items in a table
I have image slide show UI to display all image in a db table, one by one, randomly. I want to use REST API to get the image by AJAX call. In each call, if the parameter passed to server is image id in a db table, how to make sure all image get displayed? For example, file_table = [1, 2, 3, 4, 5, 6], image_list = [5, 2, 3]. 'image_list' is db query result of table 'file_table'. Some item in file_table should not be displayed. Display order is 5, 2, 3. Since REST API is stateless, where 'image_list' should be stored and tracked, so that image '5', '2', '3' can be retrieved by REST API, one by one? -
Can't figure out a way set the DOC file permission for single,multi or Enterprise user
(https://i.stack.imgur.com/wxGXK.png) I have been working on a Django project where a user is allowed to download the DOC file after he makes payment for the file. But I can't figure out a way to restrict this doc file from being forwarded or copied. Please Help!! Here is the Image if anyone can help. -
'NoneType' object has no attribute 'get' when the object is not type None
I am trying to make an application that allows a view of all of a customer's financial portfolio (in this case that's various stocks, mutual funds, and "other" like a 401k) I have a QuerySet of mutual funds filtered by customer created in my views.py file that I am trying to pass to the html template and render the list. I am running into the error in the title, though: 'NoneType' object has no attribute 'get'. I have verified via print statements that the QuerySet is not of type None, and all the data I want to use is returned correctly when I store it in a variable in my view. I have a everything working for stocks, and it has identical functionality that works just fine, so I can't figure out the difference and why one works but the other doesn't. What would be causing this error? models.py class Stock(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='stocks') symbol = models.CharField(max_length=10) name = models.CharField(max_length=50) shares = models.DecimalField(max_digits=10, decimal_places=1) purchase_price = models.DecimalField(max_digits=10, decimal_places=2) purchase_date = models.DateField(default=timezone.now, blank=True, null=True) def created(self): self.recent_date = timezone.now() self.save() def __str__(self): return str(self.customer) def initial_stock_value(self): return self.shares * self.purchase_price def current_stock_price(self): symbol_f = str(self.symbol) main_api = 'https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=' api_key …