Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get Django to upload files
I have read many questions, followed the Django docs, googled for answers, and I can't get to upload a file in my Django app. There is no error, form.cleaned_data shows the file and the other foreign key field, but no upload to media folder and no record in my db. I can't figure what am I missing. Any help would be much appreciated. #models.py class ReportFile(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE) file = models.FileField(upload_to='files/reports') uploaded = models.DateTimeField(auto_now_add=True) uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE) def save(self, *args, **kwargs): user = get_current_user() if user and not user.pk: user = None if not self.pk: self.creado_por = user #forms.py class FileForm(forms.ModelForm): class Meta: model = ReportFile fields = ['file','report'] This is the view I'm using, based on what I've read #views.py def CreateFile(request): if request.method == 'POST': form = FileForm(request.POST,request.FILES) if form.is_valid(): form.save() print(form.cleaned_data) #OUTPUT: HTTP POST /file 200 [0.09, 127.0.0.1:59053] # {'file': <InMemoryUploadedFile: test-image.png (image/png)>, 'report': <Report: 49>} return render(request, 'segcom/file_upload.html', {'form': form,}) else: form = FileForm() context = { 'form':form, } return render(request, 'segcom/file_upload.html', context) The relevant settings that I know of #settings.py # Media Root MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' This is the template I'm using {% extends "layouts/base.html" %} {% load … -
Trying to create a separate comments app for a ticket project using django generic class based views
I'm trying to create a separate comments app from my tickets app. I believe that I've gotten most of the functionality down because when I use the frontend, the comments show up in my admin site but it is not connected to the respective ticket. Instead what happens is that the comment creates its own new page of tickets. How do I connect the comment with the ticket even though they are in separate apps? I believe the problem lies in my urls.py files and in the way that I implemented them but it could also be a problem with my models or views that I am not seeing. Here's what I have so far tickets urls.py urlpatterns = [ path('', TicketListView.as_view(), name='ticket-home'), path('user/<str:username>', UserTicketListView.as_view(), name='user-tickets'), path('tickets/<int:pk>/', TicketDetailView.as_view(), name='ticket-detail'), path('tickets/new/', TicketCreateView.as_view(), name='ticket-create'), path('tickets/<int:pk>/update/', TicketUpdateView.as_view(), name='ticket-update'), path('tickets/<int:pk>/delete/', TicketDeleteView.as_view(), name='ticket-delete'), path('about/', views.about, name='tickets-about'), ] comments urls.py urlpatterns = [ path('<int:pk>/', CommentListView.as_view(), name='comment-detail'), path('tickets/<int:pk>/comments/new/', CommentCreateView.as_view(), name='comment-create'), path('tickets/comments/<int:pk>/update/', CommentUpdateView.as_view(), name='comment-update'), path('tickets/comments/<int:pk>/delete/', CommentDeleteView.as_view(), name='comment-delete'), ] ticket models.py class Ticket(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) status = models.BooleanField(choices=MARKED, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) label = models.CharField(choices=TYPES, default='Misc', max_length=100) def __str__(self): return … -
How to unpack Django RawQuerySet result in a pandas dataframe
I'm using a raw SQL query to bring objects from a Postgresql table: data_result = Search.objects.raw(search_sql) The problem is that when I try to put it into a Pandas data frame, I'm left with a data frame as a single column full of objects, instead of having them unpacked for every property: 0 Search object (167157) 1 Search object (167159) 2 Search object (167160) 3 Search object (167163) 4 Search object (167164) 5 Search object (167165) 6 Search object (167166) 7 Search object (167169) 8 Search object (167170) 9 Search object (167174) The only way I managed to make it happens was accessing dict property and then removing the "_state" property, but this doesn't seem to be the properly way to do it: data_result = pd.DataFrame([{key: value for key, value in row.__dict__.items() if key != '_state'} for row in data_result]) id number date 0 167157 180981-02 2022-02-04 1 167159 180983-01 2022-01-31 2 167160 180982-01 2022-01-31 3 167163 180990-01 2022-02-06 4 167164 180992-01 2022-01-24 5 167165 180998-01 2022-01-23 6 167166 180993-01 2022-02-08 7 167169 181001-01 2022-02-09 8 167170 181002-01 2022-02-11 9 167174 181026-02 2022-02-09 I tried creating a serializer to see if it comes as a dictionary, but I had no … -
Django - initial load/seed of model attributes from a CSV?
I have a CSV with ~500 columns that represent data I need to use in my Django app in a single model. I don't want to manually go through and declare 500 attributes in my models.py file for this new model. Is there some way to bootstrap this or make it easier? -
How can I filter multiple tables that are linked together and make it work correctly?
I want to make a filter for the following tables, but in an orm way, I used the traditional filter through objects.row, but the method brings me a lot of problems I own several tables class Store(ModelUseBranch): name = models.CharField(verbose_name=_("Name"), max_length=50, unique=True) is_stoped = models.BooleanField(verbose_name=_("Is Stopped"), default=False) def __str__(self): return self.name class Meta: verbose_name = _("Store") class Item(ModelUseBranch): name = models.CharField(verbose_name=_("name"), max_length=50, unique=True) def __str__(self): return self.name class Meta: verbose_name = _("Item") class ItemMainData(CustomModel): item = models.ForeignKey(Item, on_delete=models.CASCADE) is_stopped = models.BooleanField(verbose_name=_("Is Stopped"), default=False) use_expir_date = models.BooleanField( verbose_name=_("Use Expiration Date"), default=False ) def __str__(self): return str(self.item) class Meta: verbose_name = _("ItemMainData") class StoreQuantity(CustomModel): item = models.ForeignKey(Item, on_delete=models.PROTECT, blank=True,verbose_name=_("Item")) qty = models.PositiveIntegerField(verbose_name=_("qty"),) store = models.ForeignKey(Store, on_delete=models.PROTECT, blank=True,verbose_name=_("store")) expire_date = models.DateField(verbose_name=_("expire date"), null=True, blank=True) class Meta: verbose_name = _("Store Quantity") def __str__(self): return str(self.expire_date)+" "+str(self.qty)+" "+str(self.store) Now I want to make a query via orm with this sql = "SELECT DISTINCT warehouse_item.id ,warehouse_item.name_ar , warehouse_store.name,qty,expire_date FROM warehouse_storequantity,public.warehouse_item ,public.warehouse_itemmaindata,public.warehouse_store WHERE date (warehouse_storequantity.expire_date) - date (now()) <= (SELECT 0 FROM warehouse_storequantity,public.warehouse_item ,public.warehouse_itemmaindata,public.warehouse_store where warehouse_item.id = warehouse_itemmaindata.item_id and warehouse_item.id = warehouse_storequantity.item_id and warehouse_store.id = warehouse_storequantity.store_id and warehouse_itemmaindata.use_expir_date='1')" I tried, but I did not reach the desired goal StoreQuantity.objects.values( "pk", "item__name_ar", "store__name", "qty", "expire_date" ) .filter(item_id__in=col2) -
Django Dropbox BadInputException: OAuth2 access token must be set
I've built a Python application which utilizes the dropbox API to access the amount of files and folders within a given directory. I've been trying to host this on a web portal that my partner and I have created in Django. Due to dropbox no longer using permanent keys, the plan was to have an admin user login to the web portal and manually pass in a new app key retrieved from the dropbox console's website and pass it into the app. The issue that arises though is when I try to pass in a new access token code through the UI, Django fires the following error: BadInputException at /landBoxReport/ OAuth2 access token or refresh token or app key/secret must be set Request Method: POST Request URL: http://localhost:7000/landBoxReport/ Django Version: 4.0.5 Exception Type: BadInputException Exception Value: OAuth2 access token or refresh token or app key/secret must be set Exception Location: C:\Users\username\AppData\Local\Programs\Python\Python310\lib\site-packages\dropbox\dropbox_client.py, line 189, in __init__ Python Executable: C:\Users\username\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.5 Here's the rest of my code: For the logic in my views.py which is firing the error form = LandBoxTokenForm(request.POST) if request.method == 'POST': token = request.GET.get('landToken') if token != 'None': manager = LandBoxManager(token) manager.dropbox_show_folders() return render(request, 'landBox_report.html', {'form': … -
Django prefetch related returns null
The requirement is to have subtopics prefetched at the Campaigns queryset as the attribute prefetched_subtopics but it currently returns null Models class SubTopic(Base): name = models.CharField(max_length=100, unique=True) class CampaignSubTopicAssn(HistoryMixin, Base): campaign = models.ForeignKey(Campaign, related_name='subtopic_assn', on_delete=models.CASCADE) subtopic = models.ForeignKey(SubTopic, related_name='campaign_assn', on_delete=models.PROTECT) View def get_queryset(self): return super(CampaignViewSet, self).get_queryset().prefetch_related(Prefetch('subtopic_assn__subtopic', queryset=SubTopic.objects.all(), to_attr='prefetched_subtopics')) -
NOT NULL constraint failed: shipping_ship.user_id Django
So I'm working on a shipping website with the django rest framework. The website brings two to four people together so they can easily ship their goods together at the same time. But I'm facing a major stumbling block on the views where user book a shipping the code is below. models.py from django.db import models from django.contrib import get_user_model User = get_user_model() class Container(models.Model): container_type = models.Charfield(max_length = 30, blank=False, null = False) max_users = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places =2, default=0, blank=True, null=True) users = models.ManyToManyField(User) class Ship(models.Model): container = models.ForeignKey(Container, related_name='cont', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='shipper', on_delete=models.CASCADE) location = ( ('France', 'France'), ) from_location = models.CharField(max_length=30, choices=location, blank=False, null=False) to_location = ( ('Lagos', 'Lagos'), ('Abuja', 'Abuja'), ('Abeokuta', 'Abeokuta'), ('Osun', 'Osun'), ) to_location = models.CharField(max_length=30, choices=to_location, blank=False, null=False) date_leaving = models.DateField(auto_now=False) price = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True) def __str__(self): return self.user then my serializer.py file from rest_framework import serializers from .models import Container, Ship class ContainerSerializer(serializers.ModelSerializer): class Meta: model = Container fields = '__all__' class MiniContainerSerializer(serializers.ModelSerializer): class Meta: model = Container fields =['container_type', 'price'] class ShipSerializer(serializers.ModelSerializer): class Meta: model = Ship fields = '__all__' read_only_fields = ('user', 'price') class MiniShipSerializer(serializers.ModelSerializer): class Meta: model = Ship fields = … -
What is the difference between queryset last() and latest() in django?
I want to get data which inserted in the last so I used a django code user = CustomUser.objects.filter(email=email).last() so it gives me the last user detail but then experimentally I used user = CustomUser.objects.filter(email=email).latest() then It didn't give me a user object. Now, what is the difference between earliest(), latest, first and last()? -
Can't extract Data with For Loop (JavaScript / Fetch)
Why can't I extract the fields that I want from the for loop? Console Log JSON Data document.addEventListener('DOMContentLoaded', function() { let user = 'example'; fetch(`/jsonresponse/${user}`) .then(response => response.json()) .then(data => { // The line below works and prints the username console.log(data['UsersInfo'][0].username) // Doesn't work in a for Loop for (let i = 0; i < data.length; i++) { console.log(data['UsersInfo'][i].username); } }); Any hints would be appreciated -
Drag And Drop Feature Not Working in Django
I am making a website using django as backend framework. I have made the frontend of image upload for content writers so that they can upload image either by clicking on "browse files" or by just dragging and dropping the image. The simple button click(browse files) feature works perfectly. However, when using drag and drop, the file is not uploaded to the django files request nor in the post request. I need help on how to make it appear in the file or post request in my backend. When I upload the File using the button instead of drag and drop then i can see the file appear in the files request like this:- What I want is to make the file appear here in the yellow marked area when I use drag and drop:- Here is the code .html {% extends 'main/navbar.html' %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'css/main/index.css' %}"> <link rel="stylesheet" href="{% static 'css/contentWriting/Create Event.css' %}"> {% endblock %} {% block content %} <div class="min-h-screen flex items-center justify-center"> <form method="POST" enctype="multipart/form-data" class="w-3/4 mx-auto"> {% csrf_token %} <input type="file" name="event-banner-image" id="id-event-banner-image"> {# Main Container For Image and Details Of Event#} <div class="flex … -
django creating Profile with custom company fields try to conect with the owner
I have two forms (OwnerCreateForm, EmployeesCreateForm) and 3 models (Profile, Company and Owner). when the owner signs up, it creates the company and its own User object. after owner login, you can create employees. Have the Owner connect to the profile and associate it with the company I need to associate the owning company to the employees. That each company manages its users, that they see the same thing Here are the details I'm using: MODELS class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return '{} Profile'.format(self.user) class Owner(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return '{} Owner'.format(self.profile) class Tienda(models.Model): dueño = models.ForeignKey(Owner, null=True, on_delete=models.CASCADE) nombre_tienda = models.CharField(verbose_name='Nombre de la Tienda', max_length=120) direccion = models.CharField(verbose_name='Su Direccion', max_length=160) phone = models.CharField(max_length=11, null=True) businessemail = models.EmailField(unique = True, verbose_name='Su email') def __str__(self): return self.nombre_tienda class Employee(models.Model): STATUS = ( ('Admin', 'Admin'), ('Gerente', 'Gerente'), ('Validador', 'Validador') ) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) role = models.CharField(choices=STATUS, max_length=16) tienda = models.ForeignKey(Tienda, null=True, on_delete=models.CASCADE) def __str__(self): texto = "{0} ({1}) {2}" return texto.format(self.tienda, self.role, self.role) FORMS class TiendaForm(ModelForm): class Meta: model = Tienda fields = ('nombre_tienda', 'direccion', 'businessemail') class OwnerCreateForm(UserCreationForm): class Meta: fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') model = … -
import "hcaptcha_field" could not be resolved Django
I'm trying to add hCaptcha to my project but I can't get it to work, I've tried several versions of this library but I can't get it to work every time importing 'hcaptcha_field' or 'hcaptcha_fields' gives me the error 'import "hcaptcha_field" could not be resolved Django'. Any solution? -
No 'Access-Control-Allow-Origin' header is present on the requested resource. Uploads are not working
I ran into this cors issue when i deployed my django project which is using the django rest api and netlify for the frontend. I tried some of the solutions on here but nothing worked for me not even: CORS_ORIGIN_ALLOW_ALL = True Is there maybe something i'm missing on the frontend? Is there a way to get more details about what exactly the issue is? This only seems to happen on my upload form. (I added the code below) It works fine on on my local machine using docker. Access to XMLHttpRequest at 'https://domain/dj-rest-auth/user/' from origin 'https://domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. patch https://domain/dj-rest-auth/user/ net::ERR_FAILED 400 import { useState } from 'react'; import { Formik, Field, Form, ErrorMessage } from 'formik'; import axios from "axios" import { API } from '../api' import { useDispatch, useSelector } from "react-redux"; import { setInfo } from "../store/userInfoSlice"; import { Button, message, Upload } from 'antd'; import { UploadOutlined } from '@ant-design/icons'; import ImgCrop from 'antd-img-crop'; import { Spin } from 'antd'; export function Profile() { const info = useSelector((state) => state.userInfo.value); const accessToken = useSelector((state) => state.tokens.value.accessToken); const [loading, setLoading] = useState(false) const … -
Add default widgets to a model class
I have one model Foo and a few different forms to create different types of Foo instances. Foo contains several date fields, and I always want to use the Bootstrap datepicker when these fields are listed in a form. The only two approaches I know about right now are: To add the widget to every form, violating the DRY principle. To add the widget to class FooForm(ModelForm), and then inherit FooForm into class BarForm(FooForm), class BazForm(FooForm), etc. However, this approach mean I must remember to inherit each time. If I had instead been able to add widget specifications in the model Foo, then I can "set-and-forget" these settings. However, I have not identified how to do this yet, if it is at all possible. Any thoughts on how to add default widgets to a Django Model class? -
rabbitmq connection across two django project celery task
I have two Django project one for crawl data and another one for rest api. I have a celery task in my crawler project that send crawled data to my api project app that include a celery task for get data and do something on that with rabbitmq connection my problem is while celery tasks run and data send to api getter task. i have below error in my getter task : [2022-08-09 19:00:49,376: ERROR/MainProcess] Received unregistered task of type 'crawler.tasks.news_crawler'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) Traceback (most recent call last): File "/home/.../Projects/.../.../venv/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 581, in on_task_received strategy = strategies[type_] KeyError: 'crawler.tasks.news_crawler' -
Creating a separate comments app for a ticket project using django generic class based views
How do I override the get_context_data method of my DetailView so that it displays both the ticket details and its comment list? How do I get the comment object from a different app so that I can put it into the view? The end goal is to have both the Ticket Details and have the comment list on the same page. Here's what I have so far This is my TicketDetailView class TicketDetailView(DetailView): model = Ticket context_object_name = 'comments' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = context['comments'].filter(author=self.request.user) return context This is my CommentListView class CommentListView(ListView): model = Comment template_name = 'tickets/ticket_detail.html' context_object_name = 'comments' ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self, *args, **kwargs): ticket = self.kwargs['ticket'] return Comment.objects.filter(ticket=ticket).order_by(self.ordering) -
Django: how to fix collect static in django heroku?
I am trying to deploy a django app to heroku i am already serving the static files using AWS and eveything seems to be working fine on the local server, i have committed the code to github repo and and now i want to deploy using heroku, i get this error on the process of deploying Successfully built django-auto-logout django-formset-js-improved django-jquery-js django-mailgun-provider django-plaintext-password django-rest-auth django-rest-framework django-static-fontawesome psycopg2 rjsmin validate-email starkbank-ecdsa Installing collected packages: validate-email, starkbank-ecdsa, rjsmin, pytz, python-decouple, django-widget-tweaks, django-tinymce, django-templated-mail, django-static-fontawesome, django-social-share, django-js-asset, django-dotenv, django-ckeditor-5, django-auto-logout, dj-database-url, whitenoise, urllib3, uritemplate, sqlparse, six, python-http-client, pyjwt, psycopg2-binary, psycopg2, Pillow, oauthlib, lxml, jmespath, idna, gunicorn, djoser, django-environ, django-crispy-forms, django-ckeditor, charset-normalizer, certifi, asgiref, sendgrid, requests, python-dateutil, Django, requests-oauthlib, djangorestframework, django-taggit, django-storages, django-plaintext-password, django-mailgun-provider, django-jquery-js, django-jazzmin, django-heroku, django-filter, botocore, s3transfer, djangorestframework-simplejwt, django-rest-framework, django-rest-auth, django-formset-js-improved, boto3 Successfully installed Django-3.2.7 Pillow-9.1.0 asgiref-3.5.0 boto3-1.20.26 botocore-1.23.54 certifi-2022.6.15 charset-normalizer-2.0.12 dj-database-url-0.5.0 django-auto-logout-0.5.0 django-ckeditor-6.0.0 django-ckeditor-5-0.1.6 django-crispy-forms-1.12.0 django-dotenv-1.4.2 django-environ-0.9.0 django-filter-21.1 django-formset-js-improved-0.5.0.2 django-heroku-0.3.1 django-jazzmin-2.4.8 django-jquery-js-3.1.1 django-js-asset-1.2.2 django-mailgun-provider-0.2.3 django-plaintext-password-0.1.0 django-rest-auth-0.9.5 django-rest-framework-0.1.0 django-social-share-2.2.1 django-static-fontawesome-5.14.0.0 django-storages-1.12.3 django-taggit-3.0.0 django-templated-mail-1.1.1 django-tinymce-3.4.0 django-widget-tweaks-1.4.8 djangorestframework-3.13.1 djangorestframework-simplejwt-5.2.0 djoser-2.0.5 gunicorn-20.0.4 idna-3.3 jmespath-0.10.0 lxml-4.6.2 oauthlib-3.2.0 psycopg2-2.8.6 psycopg2-binary-2.9.1 pyjwt-2.4.0 python-dateutil-2.8.2 python-decouple-3.5 python-http-client-3.3.7 pytz-2022.1 requests-2.27.1 requests-oauthlib-1.3.1 rjsmin-1.1.0 s3transfer-0.5.2 sendgrid-6.9.7 six-1.16.0 sqlparse-0.4.2 starkbank-ecdsa-2.0.3 uritemplate-4.1.1 urllib3-1.26.9 validate-email-1.3 whitenoise-5.2.0 -----> $ python manage.py collectstatic --noinput Traceback (most recent … -
Django For Loop with Javascript Math
I am trying to figure out how to run all my for loop values through this javascript math. For example, the individual value is a loop for all my inputs whereas the total value is fixed. Exp: Indivdual values are [10, 5, 20] and the total value is 100, I want the javascript to return 10/100, 5/100, and 20/100 to get pct's for each input. This is intended to fill out a table, so it should fill in each % in a table, for instance, the row "cookies" has 10% of total, the row "fish" has 5%, and the row "soup" has 20% of the total 100. Thanks. let securities_in_asset = document.getElementById("asset-size").innerText; securities_in_asset = parseInt(securities_in_asset) for(let i = 0; i < securities_in_asset; i++) { let PctOfPool = document.querySelectorAll(`[id^="pct-of-pool"]`)[i] let indiviudal_value = document.getElementById("individual-market value").innerText; let total_value = document.getElementById("total-market-value").innerText; let problemTypeChoice = 0; if (problemTypeChoice === 0) { PctOfPool.innerText = `${((parseInt(indiviudal_value) / parseInt(total_value)) * 100).toFixed(2)}%` } else { PctOfPool.innerText = 0 } } -
Access Token still working after network changed from local to server
I have same database for local and hosted site. So, I logged in from LOCALHOST and change my base URL to server URL still the older token is working and can access all of the things on hosted site as well. All of this is done in localhost. JWT Authentication settings.py INSTALLED_APPS = [ ... 'rest_framework_simplejwt.token_blacklist', ... ] REST_FRAMEWORK = { 'NON_FIELD_ERROR_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=12), 'REFRESH_TOKEN_LIFETIME': timedelta(days=3), } Backend in DRF Frontend React.js Note if you need more info just ask, i don't really have i any idea what might required for this question -
Initial data not working if I hide some one-to-many fields in django
I want to prefill some one to many fields and also hide these field because I want to avoid a scenario where a user can see all the records related to the fields. The problem I'm facing is when I use 'all' on the form fields I the initial data dictionary is working well, but if I try to use a list of the fields I want displayed, the initial data is not getting passed into the form. Here is my models.py class Agent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) first_name = models.CharField(max_length=15, null=True, blank=True,) surname = models.CharField(max_length=15, null=True, blank=True,) provcoord = models.ForeignKey(Provcoord, null=True, blank=True, on_delete=SET_NULL) regcoord = models.ForeignKey(Regcoord, null=True, blank=False, on_delete=SET_NULL) region = models.CharField(max_length=15, null=False, blank=True, choices=REGION) province = models.CharField(max_length=15, null=False, blank=False, choices=PROVINCE) id_no = id_no = models.CharField(max_length=10, null=False, blank=False, unique=True,) agent_no = models.CharField(default="Not Assigned", max_length=20, null=False, blank=False) address = models.TextField(null=False, blank=False) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) profile_pic = models.ImageField(upload_to="assets", default="default.png") is_blacklisted = models.BooleanField(default=False) reason_for_blacklist = models.TextField(max_length=500, null=True, blank=True) registered_at = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse("agent", kwargs={'str' :str.id}) def __str__(self): return self.user.username class Adult(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) agent = models.ForeignKey(Agent, null=True, blank=True, on_delete=SET_NULL) regcoord = models.ForeignKey(Regcoord, null=True, blank=True, on_delete=SET_NULL) provcoord = … -
Object of type QuerySet is not JSON serializable Django JSON
Everything works until I try to Return JsonResponse I'm looping through the list, which contains usernames then passing those usernames to the models which return basic user information and storing those values in a variable which I later added to the list. def jsonresponse(request, username): Current_User = User.objects.get(username=username) #List of who this user follows followingList = Follower.objects.filter(follower=int(Current_User.id)) UsersInfo = [] for user in followingList: singleUser = User.objects.filter(username=user.following).values( 'username','bio', 'profile_image') UsersInfo.append(singleUser) results = User.objects.filter(username=Current_User).values( 'username','bio', 'profile_image') **This Works** return JsonResponse({'results':list(results), 'UsersInfo':list(UsersInfo)}) This works 'results':list(results), This doesn't 'UsersInfo':list(UsersInfo) print(results) gives me this: <QuerySet [{'username': 'John', 'bio': 'Hello, im new!', 'profile_image': 'images/ape_xhRtC2R.jpg'}]> print(UsersInfo) gives me this: [<QuerySet [{'username': 'Tristan', 'bio': 'Hello, im new!', 'profile_image': 'images/1-scary-tiger-head-robbybubble.jpg'}]>, <QuerySet [{'username': 'William', 'bio': 'Hello, im new!', 'profile_image': 'images/ape_PvPNwCP.jpg'}]>] Any help would really be appriciated -
No library found for Django + React Integrating Sign In With Google 2022 ( Google Identity Services )
For React there is a Library - React OAuth2 | Google For Django AllAuth library existed But after new update in Sign In With Google 2022 ( Google Identity Services ) AllAuth is not been Updated.. There is no other Libraries or easier documentation So please suggest me some Library for Django -
Django Dropdown GET Option Data
I wanted to get the selected text from the dropdown, But I am getting value if I use request.GET['Type']. I wanted to get Data001 instead of Value001 def index(request): print("The output: ",request.POST.get('Type')) return render(request,'index.html',content) <div class="form-row last"> <div class="form-wrapper"> <label for="">Meeting Type</label> <select id="Type" name="Type" class='form-control'> <option disabled="disabled" selected="selected">Choose option</option> <option value='Value001'>Data001</option> </select> </div> </div> <div class="form-wrapper"> <button data-text="Book" type="submit" name="action" value="book"> <span>Book</span> </button> </div> Please note that, There are 30+ dropdown options and I must use values in the dropdown. Kindly help me to get the selected option instead on value -
Use content_object to add an object instead of object_id, in generic relations
I have have a model(profile) which has generic relation with another model(member) in another app. when I want to add a new profile object I have to use object_id which is a field that shows the ID of that member object which has relation with this profile object. I want to use another field instead of that, for example, I have a content_object field that shows exactly the object itself. I Is there a way to use this field(content_object ) instead of object_id feild. profiling.models.Profile: class Profile(models.Model): #objects = ProfileManager() MAN = 'M' WOMAN = 'W' OTHER = 'O' GENDER_TYPE = [ (MAN, 'Man'), (WOMAN, 'Woman'), (OTHER,'Other'), ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=30) birthdate = models.DateField() gender = models.CharField(max_length=1,choices=GENDER_TYPE) address = models.TextField() profile_image = models.ImageField(null=True, blank=True) #to define generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(unique=True) content_object= GenericForeignKey() def __str__(self) : return f'{self.first_name} {self.last_name}' ticketing.models.Member: class Member(models.Model): username = models.CharField(max_length=100, unique=True) def __str__(self) -> str: return self.username class Meta: ordering = ['username']