Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to merge two XML files with different child elements into single XML file
The below given are my sample xml files. (XML 1) ` <?xml version="1.0" encoding="utf-8"?> <objects> <object> <record> <organization>1010</organization> <code>000010001</code> <name>A &amp; SOLICITORS</name> <address_1>NORTH</address_1> <address_2/> <city/> <postcode>NUHMAN 1</postcode> <state/> <country>IE</country> <vat_number/> <telephone_number>054456849</telephone_number> <fax_number>01 64964659</fax_number> <currency>USD</currency> <start_date>1990-01-01</start_date> <end_date>2999-12-31</end_date> <status>ACTIVE</status> </record> <record> <organization>1010</organization> <code>0000100004</code> <name>ACCUTRON LTD.</name> <address_1>RAZIK PARK</address_1> <address_2/> <city>LIME</city> <postcode>V94654X7</postcode> <state/> <country>IE</country> <vat_number>IE6566750H</vat_number> <telephone_number>353 -61 - 54614</telephone_number> <fax_number/> <currency>USD</currency> <start_date>1990-01-01</start_date> <end_date>2999-12-31</end_date> <status>ACTIVE</status> </record> ` (XML 2) ` <?xml version="1.0" encoding="utf-8"?> <objects> <record> <po_number>45670369</po_number> <po_currency>USD</po_currency> <po_organization>1010</po_organization> <code>0000156001</code> <name>SOFTWAREONE INC</name> <capture_row_type>NONE</capture_row_type> <source_system>SAP</source_system> </record> <record> <po_number>45670372</po_number> <po_currency>USD</po_currency> <po_organization>1010</po_organization> <code>0000156001</code> <name>SOFTWAREONE INC</name> <capture_row_type>NONE</capture_row_type> <source_system>SAP</source_system> </record> ` As we can see some of the fields are similar here. I'm trying to merge these two into one xml in a way that inside the record element each of the data in the two xml's must be there. Both data in the two files are not in order. I want the data with the matching 'code' to be grouped together in the new XML file. Both files have different number of fields and code is on of the common field and I want it to be the common factor for which the data to be grouped together. -
Testing HTML and CSS for Email
I am building a Django application that needs to send out some Emails using HTML templates. The email templates use images as well as some variables from django context. Right now, every time I make an update to the inline css or html I send myself a new Email to check how the email looks in different Browsers/Applications. Is there a way I can preview the Email without having to send it to myself? Just previewing the Email in the browser doesn't work as the CSS is always "interpreted" differently when I send it in an actual Email. <table cellpadding="0" bgcolor="#fff" border="0" style="width: 900px;"> <a href="mailto:kontakt@schmerz-experts.de"> <img style="width: 900px" src="cid:top.jpg" /> </a> </table> <table cellpadding="12" bgcolor="#fff" border="0" style="width: 900px; margin-left: 0em; margin-bottom: 15px;"> <p style="font-weight: bold; font-size: 24px; text-align: center;">VIELEN DANK.</p> <p>Sehr geehrte Patientin, Sehr geehrter Patient,</p> <p>Ihre Registrierung ist nun abgeschlossen. In Kürze erhalten Sie Ihren ersten Newsletter. </p> <p>Sollten Sie diesen innerhalb von 24 Stunden nicht erhalten, schauen Sie bitte auch in Ihrem Spam Ordner nach. </p> <p>Sollten Sie Fragen oder Anmerkungen haben, zögern Sie nicht uns zu kontaktieren.</p> <table role="presentation" cellspacing="0" cellpadding="0" style="background-color: rgb(1,41,101)"> <tr> <td style="width: 350px; padding: 16px 48px; background-color: rgb(1,41,101); text-align: center;font-weight: 700;"> <a … -
Django Auto Increment Field Non Pk
How to make the model so that each order that a costumer submit is gonna be auto incremented (ie. order_number) without messing with the order obj primary_key? Models.py class Costumer(models.Model): costumer_name = models.CharField(max_length=100) costumerID = models.CharField(max_length=100) class Order(models.Model): costumer = models.ForeignKey(Costumer, related_name='order', on_delete=models.CASCADE) order_name = models.CharField(max_length=100) order_number = models.IntegerField(default=0) JSON Example [ { "id": 1, "order": [ { "id": 1, "order_name": "fruit", "order_number": 1, "costumer": 1 }, { "id": 2, "order_name": "chair", "order_number": 2, "costumer": 1 }, { "id": 3, "order_name": "pc", "order_number": 3, "costumer": 1 } ], "costumer_name": "john doe", "costumerID": "81498" }, { "id": 2, "order": [ { "id": 4, "order_name": "phone", "order_number": 1, "costumer": 2 }, { "id": 5, "order_name": "car", "order_number": 2, "costumer": 2 } ], "costumer_name": "jane doe", "costumerID": "81499" } ] If i need to submit more file such as seriallizers.py etc please let me know. Thank you in advance. -
(React Native and Django) TypeError: Network request failed
I'm developing a mobile app with the concept of using react-native as front end and Django as back-end. I'm actually following this series of tutorials: Javascript Fetch - Communicating between a ReactNative App and Django REST API but when I got to the part where I have to use a fetch method I am getting a TypeError: Network request failed. Here is a snippet of my code: const [ domain, setDomain ] = useState("http://10.0.2.2:8000") function initAppSettings(){ console.log(domain) fetch(`$(domain)/api/v1.0/app/settings`, { method: 'GET', }) .then (result => { if (result.ok) { return result.json() } else { throw result.json() } }) .then (JSON => { console.log(JSON) }) .catch (error => { console.log(error) }) } useEffect(() => { initAppSettings() }, []) I have already tried editing the AndroidManifest.xml by adding android:usesCleartextTraffic="true". I also tried using my own ipv4 address in my Django runserver but still failed to access it. I have the same question as this but the answer here do not solve my issue. -
Redirect all page not found to home page
I would like to redirect all 404 pages to a home page. I try this but it don't work app/views.py from django.http import HttpResponse from django.shortcuts import render, redirect def home(request): return HttpResponse('<h1> HOME </h1>') def redirectPNF(request, exception): return redirect('home') app/urls.py from . import views urlpatterns = [ path('home', views.home, name="home"), ] app/settings.py handler404 = 'app.views.redirectPNF' ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] DEBUG = False -
Combine 2 Query sets and display Django
Im new to django I am trying to combing two query sets for example, I have different farms. and in those farms they have respective blocks. I would like to output the farm as a heading and list the blocks of each farm underneath it. Example: Farm 1 Block 1 Block 2 Blaock 3 Farm 2 Block 1 Block 2 Block 3 What I currently in have in views: def irrigation(request): obj3 = Farms.objects.all().values("id", "farm_name") obj2 = Blocks.objects.all() obj = obj2 | obj3 context = {"object": obj} return render(request, "irrigation.html", context) in html: {% for farms in object %} <tr> <td>{{ farms.farm_name }} {{ farms.id }}</td> <td><a href="/ifarm/{{ farms.id }}"> Edit </a> </tr> {% endfor %} Please help! -
Django==3.2.15 celery v5.1.2 and jango-celery-beat==2.2.1 enable task and nothing heppens
Ok all day trying to figure out what is wrong. mysite.settings """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'your_secret_key_here' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'correlator.apps.CorrelatorConfig', 'reviews.apps.ReviewsConfig', 'parameters.apps.ParametersConfig', 'trex', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', #'django_filters', 'rest_framework_swagger', # optional, creates browsable API docs 'easy_thumbnails', # Required by `content_image` plugin 'celery', 'django_celery_beat', 'iris', 'django_celery_results', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'mysite.mycsrfmiddleware.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'mysite.mymiddleware.CorrelatorControllerMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'M@ster449644p', 'HOST': 'localhost', 'PORT': '5432', } … -
Django 4.1.2 unique=true doesn't create index?
Email = models.EmailField(max_length = 300, unique = True) Doesn't create index on sqlite 3. Documentation says, unique = True, will create a index. But checking the indexes on sqlite. It is not created. https://docs.djangoproject.com/en/4.1/ref/models/fields/ -
Django cannot find data that I'm sure exists in the database
basically my app receives a serial number through an AJAX POST request from the front end, and it has to find the product who's serial number matches the given serial number and return it's details. here is my view , I have confirmed that the data is being received correctly and that a product with the exact serial number exists in the database but i still get a 404 not found response. i am using Mariadb as my app's database. here is my code: `` ``` from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from products.models import Products from django.shortcuts import get_object_or_404 `` # Create your views here. @csrf_exempt def products(request): if request.method == 'POST': query = request.body.decode('utf-8') products = Products.objects.all() for i in products: print(f"item{i} : {i.serial_number}") print(f"request : {query}") context = { 'products' : products, } get_object_or_404(products,serial_number = query) return render(request,"products/products.html",context) else: return render(request,"products/products.html") ``` here is the terminal output: ` `[31/Oct/2022 10:29:48] "GET / HTTP/1.1" 200 2459 itemProducts object (1) : https://blog.minhazav.dev/research/html5-qrcode.html itemProducts object (3) : 123 itemProducts object (4) : itemProducts object (5) : http://shooka.com request : "http://shooka.com" Not Found: /` `` and here is my models code: ` ``` `` `from … -
How can I modify the keys in Django Auth ADFS claims mapping?
I am using django-auth-adfs to authenticate Azure AD users on my django backend, this works fine for users within my organization. For users in other organizations however, there are certain keys defined in my CLAIMS_MAPPING that aren't returned in the JWT token. I have tried different suggestions I found to get those keys to be present but non have worked for me, so I decided to just make use of the keys present in both tokens (tokens from my organization and tokens from outside my organization). For example, I changed 'USERNAME_CLAIM': 'upn' to 'USERNAME_CLAIM': 'email' because the upn key is not present in both tokens but the email key is and they pretty much return the same values. My problem right now is with the first_name and last_name keys. With tokens from my organization, this mapping works fine: 'CLAIM_MAPPING': {'first_name': 'given_name', 'last_name': 'family_name', 'email': 'upn'}, However the key family_name does not exist in tokens from outside my organization. The name key exists in both tokens, so I thought to .split(" ") the name key and get the parts but I am not sure how to go about this since the mapping is to a string representing a key in the … -
Django rest framework create or update in POST resquest
can anyone help please, with DRF according to POST request, I want to create(if not exists) or update() table belows are my codes model.py class User1(models.Model): user = models.CharField(max_length=10) full_name = models.CharField(max_length=20) logon_data = models.DateTimeField(blank=True, null=True) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User1 fields = '__all__' views.py from .models import User1 from .serializers import UserSerializer from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET', 'POST']) def UserView(request): if request.method == 'GET': users = User1.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) elif request.method == 'POST': users = User1.objects.all() serializer = UserSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400) urls.py from django.urls import path from . import views urlpatterns = [ path('users/', views.UserView), ] when POST request, I want to check like this: if user exists: if user.full_name == request.fullname update (user.logon_data) save() else: update (user.full_name) update (user.logon_data) save() else: create( user = request.user, full_name = request.full_name, logon_data = request.logon_date) save() POST request for JSON like this: [ { "user": "testuser1", "full_name": "test user1", "logon_data": "2022-10-19 09:37:26" }, { "user": "testuser2", "full_name": "test user2", "logon_data": "2022-10-20 07:02:06" } ] -
Does npm server is necessary for ReactJS with django on production?
I have developped the application with DJango + ReactJS when in developpment, using $python manage.py runserver and $yarn start which launche the two servers on localhost:8000 and localhost:3000 However in production environment, I need to launch two servers?? When I use webpack before I run two server in developpment environment, but in Production just building in advance and use only on one server uwsgi -
"django.core.exceptions.ImproperlyConfigured:" while doing migrations to posgreSQL
I created a table in models.py and also added the connection to my PostgreSQL database in settings.py. But when I do the migrations in the command prompt I get these error ` django.core.exceptions.ImproperlyConfigured: 'django.db.backends.posgresql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' ` I have installed Django through command prompt but still I don't know why I get these error. I was expecting a successful migration of my table to PostgreSQL data base. -
deploy django app to vps server using cyberpanel
I am trying to deploy django app to vps server using cyberpanel.I followed the steps in the doc, here is the link to the doc (https://community.cyberpanel.net/t/how-to-setup-django-application-on-cyberpanel-openlitespeed/30646), but the site gives 500 Internal Server Error In the Error log, this error appears 2022-10-31 06:15:44.516946 [INFO] [126625] [wsgi:futuurelineworkshop.com:/]: locked pid file [/tmp/lshttpd/futuurelineworkshop.com:.sock.pid]. 2022-10-31 06:15:44.516975 [INFO] [126625] [wsgi:futuurelineworkshop.com:/] remove unix socket for detached process: /tmp/lshttpd/futuurelineworkshop.com:.sock 2022-10-31 06:15:44.517516 [NOTICE] [126625] [LocalWorker::workerExec] VHost:futuurelineworkshop.com suExec check uid 99 gid 99 setuidmode 0. 2022-10-31 06:15:44.517541 [NOTICE] [126625] [LocalWorker::workerExec] Config[wsgi:futuurelineworkshop.com:/]: suExec uid 99 gid 99 cmd /usr/local/lsws/fcgi-bin/lswsgi -m /home/futuurelineworkshop.com/public_html/workShop2/WorkShop/wsgi.py, final uid 99 gid 99, flags: 0. 2022-10-31 06:15:44.518080 [NOTICE] [126625] [wsgi:futuurelineworkshop.com:/] add child process pid: 146100 2022-10-31 06:15:44.518154 [INFO] [126625] [wsgi:futuurelineworkshop.com:/]: unlocked pid file [/tmp/lshttpd/futuurelineworkshop.com:_.sock.pid]. 2022-10-31 06:15:45.031045 [NOTICE] [126625] [127.0.0.1:44700#futuurelineworkshop.com] Premature end of response header. I am trying to deploy django app to vps server using cyberpanel.I followed the steps in the doc, here is the link to the doc (https://community.cyberpanel.net/t/how-to-setup-django-application-on-cyberpanel-openlitespeed/30646), but the site gives 500 Internal Server Error In the Error log, this error appears -
Form Filter with Pagination not working in Django
I am trying to use Form filters and Pagination together in a view and only one works at one point of time, I am not able to make both work together, Please help if there is a workaround to my problem. views.py ` def viewAmc(request): amc = Amc.objects.all() paginator = Paginator(amc, 10) page_obj = paginator.page(request.GET.get('page', '1')) amcFilter = AmcFilter(request.GET, queryset=amc) amc = amcFilter.qs#qs means query set context = {'amc': page_obj, 'amcFilter': amcFilter} return render(request, 'view_amc.html', context) ` filters.py ` class AmcFilter(django_filters.FilterSet): class Meta: model = Amc fields = 'amc_type', 'amc_status' ` view_amc.html ` {% extends 'base.html' %} {% load static %} {% block content %} <br> <div class="row"> <div class="col-md-8"> <div class="card card-body"> <h5>&nbsp; Annual Maintenance Contract :</h5> <div class="card card-body"> <form method="get"> {{ amcFilter.form.amc_type.label_tag }}{{ amcFilter.form.amc_type }} {{ amcFilter.form.amc_status.label_tag }}{{ amcFilter.form.amc_status }} <button class="btn btn-primary" type="submit">Filter</button> </form> </div> <div class="col"> </div> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_amc' %}">Create New AMC</a> <table class="table table-sm"> <tr> <th>Customer</th> <th>Location</th> <th>AMC ID</th> <th>AMC Type</th> <th>AMC Status</th> <th>AMC Cost</th> <th>AMC Start</th> <th>AMC Expiry</th> </tr> {% for items in amc %} <tr> <td>{{ items.customer }}</td> <td>{{ items.location }}</td> <td>{{ items.name }}</td> <td>{{ items.amc_type }}</td> <td>{{ items.amc_status }}</td> <td>{{ items.amc_cost }}</td> … -
How api_key for 3rd party application works?
In my project i want to provide data with APIs what is the better way to generate and auth api-keys. BTW i'm using python django. tried django-rest-framework-api-keys but not worked. -
How to override the help messages shown in Django's "set password" step?
I replaced the password set's step HTML with my own HTML, so far everything's good. Thing is, all tutorials seem to use the {{form.as p}} part when the user is changing their password, so the code will be left like this: {% extends "account/base.html" %} {% load static %} {% block title %}Password recovery{% endblock title %} {% block content %} {% if validlink %} <h1>Password change</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Change password"> </form> {% else %} <h1>Error.</h1> <p>Please try again.</p> {% endif %} {% endblock%} Thing is, when testing it, the page displays this additional help text: Your password can’t be too similar to your other personal information. Your password must contain at least 8 characters. Your password can’t be a commonly used password. Your password can’t be entirely numeric. And I want to modify that text. I looking for the validator's class in password_validation.pyi at contrib.auth, and calling it from a forms.py I created in my "login" app, changing the "get_help_text" function this way def get_help_text(self): return ngettext( "Blah blah, text changed", "Blah blah, text changed", self.min_length ) % {'min_length': self.min_length} But it doesn't seem to be changed in the set password … -
image not showing in browser using easy thumbnail with Amazon S3 in Django Project
working on django project and use easy thumbnail for croping the images. Previously i used the in local enviornment and its working fine. but when i move media to Amazon S3 then images not showing (could not load the image) in browser. easy-thumbnail library link image tag in template:- image tag in browser:- But when i remove the (.1200x800_q95_crop.jpg) this part through web developer tools in img tag. then its working. but image size and crop option not working. I want to crop and resize image when its showing in browser. -
How to inspect oracle database without primary key in django
command: python .\manage.py inspectdb --database=ORACLE > models.py This command run successfully. But models.py output is # Unable to inspect table 'acc_advance_other_adj_dt' # The error was: ORA-00904: "USER_TAB_COLS"."IDENTITY_COLUMN": invalid identifier # Unable to inspect table 'acc_ari_entries_dt' # The error was: ORA-00904: "USER_TAB_COLS"."IDENTITY_COLUMN": invalid identifier # Unable to inspect table 'acc_asset_mt' # The error was: ORA-00904: "USER_TAB_COLS"."IDENTITY_COLUMN": invalid identifier -
{% for top in topwear.brand %} is not executing
I want to list the items by brand so user can choose according to the brand of the product in the sidebar but somehow it is not happenning `your text`` views.py class home(View): def get (self,request): products=Product.objects.all() topwear=Product.objects.filter(Category='TW') bottomwear=Product.objects.filter(Category='BW') context={'topwear':topwear,'bottomwear':bottomwear,'products':products} return render(request,'store/index.html',context) models.py your text class Product(models.Model): category=[ ('TW','Top Wear'), ('BW','Bottom Wear'), ('Shoes','Shoes'), ('mobile','mobile'), ('Laptop','Laptop') ] title=models.CharField(max_length=100) selling_price=models.FloatField() discounted_price=models.FloatField() description=models.TextField() brand=models.CharField(max_length=100) Category=models.CharField(choices=category,max_length=10) product_image=models.ImageField(upload_to='productimg') def __str__(self): return str(self.id) Bottom wear and mobile section is showing but not topwear section. index.html your text <div class="dropdown-menu position-absolute bg-secondary border-0 rounded-0 w-100 m-0"> {% for top in topwear.brand %} <a href="{% url 'searchproduct' top %}" class="dropdown-item">Top Wear</a> {% endfor %} <a href="" class="dropdown-item">Bottom Wear</a> <a href="" class="dropdown-item">Mobile</a> </div> Everything else is running file .Just top wear section is not showing in browser. Is this syntax not correct? Help will be appreciated -
how can i search for a keyword in order django
content = request.query_params.get('search') searchList = list(content.strip(" ")) resultLoop= Medicines.objects.filter(name__icontains=searchList[0]) for letter in searchList: resultLoop = resultLoop.filter(name__icontains=letter) this is the how I manage to get the result which contains all the letters that the keyword contains, but it is a scrambled result. ie. if am searching 'abc' from ['abcd','bcda','cdab','adbc'], it returns all the four elements because it contains all the letter that the keyword has, What I need is, only two elements which is in the actual order of the keyword. Those are ['abcd','abdc'] -
Django - Copy and edit data from one model into another
I have a 'Services' model that contains a user's templated services. I have a 'serviceSelect' model that I want to be able to copy and a template from 'Services' into the 'ServiceSelect' model which will then be related to a proposal and can be edited. I have a ServiceSelectForm that has initial dropdown data from the 'Service' model. I am trying to be able to select a 'service' from the drop-down and copy it into the 'ServiceSelect' model for later editing. When I try to do this I'm getting: Cannot assign "'a303adbb9bd4'": "Proposal.services" must be a "ServiceSelect" instance. This is what I have tried: **Service model ** There are only a few entries as these are templated services. title = models.CharField(null=True, blank=True, max_length=100) discription = models.TextField(null=True, blank=True) category = models.CharField(choices=CATEGORY, blank=True, max_length=100) quantity = models.FloatField(null=True, blank=True) price = models.FloatField(null=True, blank=True) paymentTerms = models.CharField(choices=PAYMENT, blank=True, max_length=100) salesTax = models.CharField(choices=SALESTAX, blank=True, max_length=100) uniqueId = models.CharField(null=True, blank=True, max_length=100) slug = models.SlugField(max_length=500, unique=True, blank=True, null=True) date_created = models.DateTimeField(blank=True, null=True) last_updated = models.DateTimeField(blank=True, null=True) def __str__(self): return '{} {}'.format(self.title, self.uniqueId) def get_absolute_url(self): return reverse('product-detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if self.date_created is None: self.date_created = timezone.localtime(timezone.now()) if self.uniqueId is None: self.uniqueId = str(uuid4()).split('-')[4] self.slug … -
Django ORM Using Dynamic Variable To Get Object Field Value
my_dict['name'] = my_model.objects.get(pk=pk).object_name I need ".object_name" to be a dynamic variable. I tried creating a variable and adding it to the end. my_model.objects.get(pk=pk).variable_name my_model.objects.get(pk=pk)variable_name etc... When I try to add a variable to the end of the query it throws an error. "Object has no attribute 'variable_name'". "Statements must be separated by a new line or semicolon." I'm sure there must be some other way to write this but I can't find any information to achieve this. -
How to fix type 'Null' is not a subtype of type 'Map<dynamic, dynamic>' in type cast error
Hi I am new to flutter & dart. I am trying to get the api of Django Rest Framework using the following test.dart import 'dart:convert'; import 'package:http/http.dart' as http; // var response = await http.get(Uri.parse("http://127.0.0.1:8000/")); // print(response.body); Future<void> main() async { final response = await http.get(Uri.parse("http://127.0.0.1:8000/api/Username/items/")); final decoded = jsonDecode(response.body) as Map; final data = decoded['data'] as Map; print(data['name']); for (final name in data.keys) { final value = data[name]; print('$name,$value'); } } Here is the api.views @api_view(['GET']) def getItem(request, **kwargs): user = get_object_or_404(User, username=request.user) items=Item.objects.filter(user=user) serializer = ItemSerializer(workouts, many=True) return Response(serializer.data) Here is the api/urls: path('<str:username>/workouts/',views.getWorkout, name='api_workout'), Here is the serializer.py class ItemSerializer(serializers.ModelSerializer): user = serializers.CharField(source="user.username", read_only=True) class Meta: model= Workout fields = '__all__' I am not sure why I am getting: Unhandled exception: type 'Null' is not a subtype of type 'Map<dynamic, dynamic>' in type cast #0 main bin\test.dart:11 <asynchronous suspension> My question: Why am i getting this error and how can I get access to the api json in the mentioned http -
Subscription System IAP using some language of backend
I want to create a management subscription IAP for my app in Flutter, I don't want to use renewcat or other like that. I want to create my own backend Manager What is the best option for create faster? and what do I need, this system is like to a CRUD? exist some Api or tools for make easy this work? Sorry for my doubt, I tried looking information about but I didn't found nothing.