Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POSTMAN -> DJANGO -- Upload Binary file (jpeg). Can't get it to work no matter what I do
to simplify: curl --location --request PUT 'https://myserver.com/upload' \ --form 'file=@/Users/myname/Desktop/bond.jpg' \ --form 'test=test' It gets to my Django App: class MyUploadView(APIView): parser_classes = [FormParser, MultiPartParser] def put(self, request, **kwargs): print(request.FILES) but gives out: <MultiValueDict: {}> nothing I do work, file is always empty. when I use Content-Type: multipart/form-data it doesn't work as well, and sometimes django would complain there is no boundary -- but any value there gives out the same error. MY GOAL IS SIMPLE: all I want it to upload a file to django and save it to disk on the backend. I cannot believe this i taking all day long with zero results and zero examples online that actually work. -
Django images don't fill height
I am currently working on a django blog. However, I am experiencing some difficulties with the size of the post thumbnails. Here's a picture: What I marked in yellow is how the image should be filling the space. The width is fine, but the heigh isn't working well as you can see. Here's the code: {% extends 'base.html' %} {% load static %} {% block content %} <style> img { height: 100%; width: 100%; } </style> <!-- Post--> {% for obj in object_list %} <div class="row d-flex align-items-stretch"> {% if not forloop.first and not forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the image {% endif %} <div class="text col-lg-7"> <div class="text-inner d-flex align-items-center"> <div class="content"> <header class="post-header"> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> <a href="{{ obj.get_absolute_url }}"> <h2 class="h4">{{ obj.title }}</h2> </a> </header> <p>{{ obj.overview|linebreaks|truncatechars:200 }}</p> <footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap"> <div class="avatar"><img src="{{ obj.author.profile_picture.url }}" alt="..." class="img-fluid"></div> <div class="title"><span>{{ obj.author }}</span></div></a> <div class="date"><i class="icon-clock"></i> {{ obj.timestamp|timesince }} ago</div> <div class="comments"><i class="icon-comment"></i>{{ obj.comment_count }}</div> </footer> </div> </div> </div> {% if forloop.first or forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the … -
Django Channels JWT Authentication
I'm trying to access the user in the scope in my Consumer.py and grab some user related models from the DB. However, it seems like AuthMiddlewareStack I'm using for authenticating all the websocket connections is not working correctly. What is the best/secure way to be able to authenticate websocket connection in django channels when I'm using JWT Tokens django-rest-framework-simplejwt for authentication in my REST Framework? -
Render a form inside a modal - django
Probably my question is easy enough for people more experienced than me, so i would like your help with the following. I would like to use a modal on my website for Login/Register and i have an issue when rendering a form inside the modal. I've created a urls.py file app_name = "users" urlpatterns = [ path('register/', UserRegisterView.as_view(), name='register') ] the views.py file where loading the AccountRegisterForm class UserRegisterView(SuccessMessageMixin, CreateView): template_name = 'users/register.html' form_class = AccountRegisterForm success_url = '/' success_message = "Your account has been created!" the template <li class="list-inline-item list_s"><a href="#" class="btn flaticon-user" data-toggle="modal" data-target=".bd-example-modal-lg"> <span class="dn-lg">Login/Register</span></a></li> </ul> </nav> </div> </header> <!-- Modal --> <div class="sign_up_modal modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body container pb20"> <div class="row"> <div class="col-lg-12"> <ul class="sign_up_tab nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Login</a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Register</a> </li> </ul> </div> </div> and the form: <form method="POST" form action="{% url 'users:register' %}"> {% csrf_token %} <div class="row"> <div class="col-lg-12"> <button type="submit" class="btn btn-block btn-fb"><i class="fa fa-facebook float-left mt5"></i> Login with Facebook</button> </div> <div class="col-lg-12"> … -
Django logging errors occuring in admin page
I face the following issue: I want to add a new instance of a model in the django admin page, but I do get an 500 error. Now I want to log all the errors occurring in the admin page to a file. Important details: website running in production, hence I do not get feedback in the browser or the console (since I use Gunicorn). this occurs only for one specific model. this only happens when adding a new instance for that model, not when changing exisiting instance logging in the view does not help, since error occurs within admin page I do not want you to help me debug my django code. I am only interessted for tips and a tutorial on how to log every error occuring no matter if it happens in the admin page or the actual site. I am happy for any tips and suggestions! Thanks! Thanks for any advice! -
Django-reactjs Not Found: /asset-manifest.json
I'm trying to connect my ReactApp to my Django server. I actually did connect these 2 but I can't get the layout of react app on the django side.However, I can see the title of ReactApp on my Django server but no layout at all, actually there is nothing but white page at localhost:8000(django-server). If I check my django server from my terminal I get this following Not Found: /manifest.json I actually do have a manifest.json in my react app. I can send screenshots, or more code If you ask. -
how to save step for FormWizard Django
I have a series of related models and I need to save the queryset in the current step to be available in the next step, otherwise a choice option will be empty forms.py class AttachmentForm(forms.ModelForm): class Meta: model = Attachment fields = '__all__' class SkuAttachmentForm(forms.ModelForm): class Meta: model = SkuAttachment fields = '__all__' class DomainsAttachmentForm(forms.ModelForm): class Meta: model = DomainsAttachment fields = '__all__' widgets = { 'name_key': forms.TextInput(attrs={'disabled': True}), } def __init__(self, *args, **kwargs): # first call parent's constructor super(DomainsAttachmentForm, self).__init__(*args, **kwargs) # there's a `fields` property now self.fields['name_key'].required = False models.py class DomainsAttachment(models.Model): name_key = models.CharField(default='frequency', max_length=100) values_allow = models.CharField(verbose_name='Frequencia', help_text='1month ou 1, 15, 28', max_length=50) class Attachment(models.Model): name = models.CharField(max_length=50) is_required = models.BooleanField(default=False) is_active = models.BooleanField(default=True) domains = models.ManyToManyField(DomainsAttachment) class SkuAttachment(models.Model): attachment = models.ForeignKey(Attachment, on_delete=models.CASCADE) sku = models.ForeignKey(Sku, on_delete=models.CASCADE) -
PWA serviceworker.js being displayed on startup of website
When I open up my website when it is first deployed, the javascript code of the serviceworker is displayed on a white screen instead of the website and I have to hard refresh the page everytime to make it work. I don't know why its doing this. I am using Django as my backend so my manifest.json is in the settings.py file. Here is my serviceworker code: var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '', ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); Here is my manifest code: #PWA manifest.json settings PWA_APP_NAME = 'test' PWA_APP_DESCRIPTION = "test PWA" PWA_APP_THEME_COLOR = '#000000' PWA_APP_BACKGROUND_COLOR = '#ffffff' PWA_APP_DISPLAY = 'standalone' PWA_APP_SCOPE = '/' PWA_APP_ORIENTATION = 'any' PWA_APP_START_URL = '/' PWA_APP_STATUS_BAR_COLOR = 'default' PWA_APP_ICONS = [ { 'src': 'static/images/icon-160x160.png', 'sizes': '160x160' } ] PWA_APP_ICONS_APPLE = [ { 'src': 'static/images/icon-160x160.png', 'sizes': '160x160' } ] PWA_APP_SPLASH_SCREEN = [ { 'src': 'static/images/icon.png', 'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)' } ] PWA_APP_DIR = 'ltr' PWA_APP_LANG = 'en-US' -
Custom Django Form - modify cleaned data based on request
This has most likely already been asked before, but I could not figure out the right thing to google. I am creating a simple form for people to fill out a COVID screen for an event. Basically, they click on an event and then click fill out form. I have created a model for this as such: class Response(models.Model): """ model for a completed covid screen """ temperature = models.DecimalField(max_digits=5, decimal_places=2, default=98.6) contact_with_covid = models.BooleanField(default=False) account = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) time = models.DateTimeField() event = models.ForeignKey("Event", on_delete=models.CASCADE) def __str__(self): return f'{self.account.user.username}\'s response for "{self.event.title}"' As well as created a form for users to fill out for this response. class ResponseForm(forms.ModelForm): class Meta: model = Response fields = ['temperature', 'contact_with_covid'] labels = {'contact_with_covid': 'Have you had contact with covid in the last 14 days?'} help_texts = {'temperature': 'Your temperature in degrees.'} I did not want the user to select the account, time and event parameters. They should be defined as such: account should be the currently logged in user request.user.account time should be the time of submission datetime.datetime.now() event should be the event in the URL parameter. path('event/<uuid:event>/response/create', views.create_response, name='response-create') Therefore, the view I have sets these parameters in cleaned_data after … -
I need help in Filter some data id Django
I have a model structure, but have tough time understanding how to use the Django filters. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) class Bar(models.Model): user_id = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=10) class Tables(models.Model): bar = models.ForeignKey(to=Bar, on_delete=models.CASCADE) I want to be able to filter the user of a table from the model below. -
CART functionallity in DRF
I am new to Django and currently setting up an ecommerce backend. I have created models, serializers, views and urls. Now, I need to set up a cart functionality, like create/update/delete/calculate_total and etc. The thing is I am totally lost. Don't know where to start and what to do next. If you have a little time for quick guidance I'd be sincerely grateful. class Cart(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) number_of_items = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return "User: {}, items in cart: {}".format(self.owner, self.number_of_items) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return str(self.id) class CartSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField() class Meta: model = Cart fields = '__all__' class CartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = "__all__" class CartView(viewsets.ModelViewSet): serializer_class = CartSerializer queryset = Cart.objects.filter() def perform_create(self, serializer): serializer.save(owner=self.request.user) class CartItemView(viewsets.ModelViewSet): serializer_class = CartItemSerializer queryset = CartItem.objects.all() router = DefaultRouter() router.register(r'view', CartView) router.register(r'item', CartItemView) urlpatterns = [ path('', include(router.urls)), ] -
Django unable to iterate prefetch_related objects at template
I'm unable to access my prefetch_related objects at my template, can smb help views.py def support(request, pk=None): ... else: list_support_tickets = sorted( chain( SupportTickets.objects.filter(Q(status=0) | Q(status=1), requester=request.user).prefetch_related('reply_relation'), #Can't iter object ), key=attrgetter('creation_date'), reverse=True ) paginator = Paginator(list_support_tickets, 10) page = request.GET.get('page') support_tickets = paginator.get_page(page) args = {'support_tickets': support_tickets, 'form': form } print(list_support_tickets) return render(request, template, args) At my template I do the following: {% for support_ticket in support_tickets %} ... {% for reply in support_ticket.reply_relation %} <span class="font-size-small">We have a query, yeah</span> {% endfor %} {% endfor %} But I'm unable get a query here, error: TypeError: 'GenericRelatedObjectManager' object is not iterable models.py class SupportTicketMessages(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=referential_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='support_ticket_reply_author', verbose_name='Author', blank=True) reply = models.TextField(verbose_name="Reply Content", max_length=2000) date = models.DateTimeField(auto_now_add=True, blank=False) class SupportTickets(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) ticket_id = models.IntegerField(default=ticket_id_generator, unique=True, blank=False, null=False, editable=False) requester = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) category = models.IntegerField(choices=TICKET_CATEGORY, verbose_name='Ticket Category') subject = models.CharField(max_length=40) problem_description = models.TextField(max_length=5000) status = models.IntegerField(choices=STATUS_OF_TICKET, verbose_name='Ticket Status', default=0) reply_relation = GenericRelation(SupportTicketMessages, related_query_name='reply_relation') creation_date = models.DateTimeField(auto_now_add=True, null=True) Thanks in advance -
How can I filter objects in my model to only show those of my ForeignKey user?
Trying to filter objects in my view.py to only show items (in my case Buckets) owned by Users. I implemented the code below in my original Model [my model.py code is at the bottom of post] class PostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Bucket.owner) But I'm not sure if that is the correct procedure to list all items? Here is the view.py where I'm trying to filter data by User aka owner. Users should ONLY be allowed to view their own items. (I will deal with permissions later) class BucketList(generics.ListCreateAPIView): queryset = Bucket.objects.all() #INSERT FILTER HERE pass Here is the model I'm referring too. class Bucket(models.Model): options = ( ('personal', 'Personal'), ('social', 'Social'), ) class PostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Bucket.owner) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buckets') users = models.ManyToManyField(settings.AUTH_USER_MODEL) category = models.CharField(max_length=30, choices=options) name = models.CharField(max_length=35) created = models.DateTimeField(default=timezone.now) slug = models.SlugField(unique=True, blank=True) stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6),size=10) objects = models.Manager() postobjects = PostObjects() class Meta: ordering = ('-created',) def total_stocks_calc(self): self.stock_count = Bucket.objects.aggregate(Sum('stock_list', distinct=True)) self.save() def get_absolute_url(self): return reverse("bucket:bucket-view", kwargs={"slug": self.slug}) def __str__(self): return self.stock_list To re-state my question, how can I filter objects owned by users in class BucketList for their private view only? UPDATE: from django.db.models import Q … -
Django custom user model with password
Can Django use a password field from a legacy db for authentication? I have got all of my models working with my legacy postgresql database. I have implemented the custom user model as documented and switched the login to USERNAME_FIELD = 'email'. When running createsuperuser, I do not get prompted for password. I would like to use the password field in my legacy postgres db, field name crypted_password. During createsuperuser I get an error after entering the email. django.db.utils.ProgrammingError: column accounts_users.password does not exist LINE 1: SELECT "accounts_users"."id", "accounts_users"."password", "... I am not sure what info would be useful for assistance. I have implemented the custom user model step by step as documented in official documentation. I am at a loss. -
IntegrityError: FOREIGN KEY constraint failed
I am trying to post a form(ReviewForm) but I get the error FOREIGN KEY constraint failed when my form tries to save.Any help please?Thanks in advance. Here is my views.py code(the post function in the view class) def post(self,request,*args,**kwargs): pk=self.kwargs.get("pk") di = self.kwargs.get("di") dis=get_object_or_404(Disease,pk=di) pestiside=Pestiside.objects.get(pk=pk,disease=dis) if request.method=='POST': user = request.user form= ReviewForm(request.POST) if form.is_valid(): form.save() comment=form.cleaned_data.get('comment') new_review=Review.objects.create(author=user,pes_id=pestiside_id,comment=comment) new_review.save() return redirect('diagnose:pestiside') Here is my models.py code: class Review(models.Model): author= models.ForeignKey(User,default=1, on_delete=models.CASCADE) time = models.DateTimeField(auto_now_add=True, blank=True) pes = models.ForeignKey(Pestiside,default=0,on_delete=models.CASCADE) comment = models.CharField(max_length=200) Here is my forms.py code: class ReviewForm(forms.ModelForm): class Meta: model=Review fields=('comment',) Here is my stacktrace,the error shows at form.save() in views.py : Traceback (most recent call last): File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) ***File "/home/risper/django_projects/Tomadoc/diagnose/views.py", line 276, in post form.save()*** File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/forms/models.py", … -
Django: Setting a cookie asynchronously
To set a cookie, I used this on Django docs.. blog/models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=180, null=False) text = tinymce.models.HTMLField() created_date = models.DateTimeField(auto_now_add=True, editable=False) published_date = models.DateTimeField(null=True, default=None) def __str__(self): return self.title def publish(self): self.published_date = timezone.now() self.save() class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.DO_NOTHING) liked = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, editable=True) visitor_uid = models.CharField(max_length=37) def __str__(self): return self.visitor_uid[:5] blog/views.py import uuid def make_cookie(request, pk): post = get_object_or_404(Post, pk=pk) like = Like() like.post = post like.visitor_uid = str(make_uuid()) like.save() request.session[post.pk] = like.visitor_uid Making a HttpResponse('Some HTML') which redirects. I don't want this behaviour to happen without the refreshing/redirecting. Also referred this from GFG but even they are redirecting... Any ideas? -
Django can't resolve url path 404
Hi I'm having a very annoying issue with django: I've setup many urls paths and they all work fine except one and I really can't figure out why: Urls urlpatterns = [ # path('foods/search', food_search), path('food_list/', FoodListVersionListCreateAPIView.as_view(), name='foodList-list'), path('all_foods/<str:survey>/<str:string>', FoodListCreateAPIView.as_view(), name='food-list'), path('food_classification/', FoodClassificationListCreateAPIView.as_view(), name='foodClassification-list'), path('food/<str:survey>/<str:string>/', FoodDetailAPIView.as_view(), name='food-detail'), ] Views class FoodListCreateAPIView(generics.ListCreateAPIView): queryset = Food.objects.all() serializer_class = FoodSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['description', 'food_code', 'cofid_code', 'foodex_code', 'food_classification'] search_fields = ['food_list', 'SYSTEM_TIME'] permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): assert self.queryset is not None, ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self.__class__.__name__ ) survey = self.request.query_params['survey'] food = self.request.query_params['string'] raw_queryset = perform_food_search(survey, food) queryset = Food.objects.filter(pk__in=[i.pk for i in raw_queryset]) if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset Error message -
How to use JSON data on Django View
I need to use data as JSON from an API in Django View here is my JSON data; [{'Count': 5491}] I need to pass just value of the "Count" key to HTML and views.py is as below; def serviceReport(request): data = mb.post('/api/card/423/query/json') context = { 'count' : data['Count'] } return render(request, 'service_report.html', context) I get error like this; Exception Type: TypeError Exception Value: list indices must be integers or slices, not str What I want is to pass value of count key to service_report.html and also I want to pass multiple JSON datas like data2, data3 as data on views.py how can I do it? -
Django object filter - highest bid for every item
I want to filter an object which contains the highest price for each listing_id. from models.py class Listing(models.Model): title = models.CharField(max_length=64) class Bid(models.Model): listing_id = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing") user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") price = models.DecimalField(max_digits=19, decimal_places=2, blank=False, validators=[MinValueValidator(1)]) Can I get some advice guys? -
How to add dictionary values as model object values into postgres in django
this is the model.py from django.db import models from datetime import datetime from postgres_copy import CopyManager class state_data(models.Model): date = models.DateTimeField(default=datetime.now) state = models.CharField(max_length=200) death = models.IntegerField() hospitalizedIncrease = models.IntegerField() def __str__(self): return self.state I have this model. and i have some dictionary like {'date' :12/2/1985,'state ':'fgyu', 'death':1245, 'hospitalizedIncrease':58} I wanted to add dictionary values [12/2/1985,fgyu,1245,58] into database created by the model after migrations please help me todo this. -
Create equivalent paths in Django urls.py
I am attempting to create 2 url prefixes that would be equivalent in my app (this is due to some aesthetic user requirements), and am unsure the best way to go about this. The most straightforward option would be to create another set of urlpatterns with the alternate prefix. However, this would be repetitive and make maintenance more difficult. Is there a simpler way to make foo/<str:key>/ equivalent to bar/<str:key> and staff/<str:key>/ equivalent to foo/<str:key>/staff/? Current URLS urlpatterns = [ path('foo/<str:key>/welcome/', views.welcome), path('foo/<str:key>/dashboard/', views.dashboard), path('foo/<str:key>/staff/dashboard/', views.staff_dashboard), ] Desired Patterns urlpatterns = [ # Original paths path('foo/<str:key>/welcome/', views.welcome), path('foo/<str:key>/dashboard/', views.dashboard), path('foo/<str:key>/staff/dashboard/', views.staff_dashboard), # Alternate paths to the same pages path('bar/<str:key>/welcome/', views.welcome), path('bar/<str:key>/dashboard/', views.dashboard), path('staff/<str:key>/dashboard/', views.staff_dashboard), ] -
token blacklist outstandingtoken
token_blacklist_outstandingtoken is The Collection In Mongodb Database Which Django REst Framework Use To Store Tokens Assigned To Recently Registered Users, It Stores Access Token Well For First User Register, But It Makes Error While Inserting Second UserError Details: djongo.sql2mongo.SQLDecodeError: FAILED SQL: INSERT INTO "token_blacklist_outstandingtoken" ("user_id", "jti", "token", "created_at", "expires_at") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s) Params: [11, 'fe4bbe67b6a4413e81cfca6b4e2919aa', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYwOTE3Nzc4MCwianRpIjoiZmU0YmJlNjdiNmE0NDEzZTgxY2ZjYTZiNGUyOTE5YWEiLCJ1c2VyX2lkIjoxMX0.JtyGSL_nJ4iiKXqijvxCkipxMQAxTksFKEP6g5qPGiI', datetime.datetime(2020, 12, 14, 17, 49, 40, 602304), datetime.datetime(2020, 12, 28, 17, 49, 40)] Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'jti_hex': 1}, 'keyValue': {'jti_hex': None}, 'errmsg': 'E11000 duplicate key error collection: patientStatus.token_blacklist_outstandingtoken index: token_blacklist_o_jti_hex_d9bdf6f7_uniq dup key: { jti_hex: null }', 'op': {'id': 10, 'user_id': 11, 'jti': 'fe4bbe67b6a4413e81cfca6b4e2919aa', 'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYwOTE3Nzc4MCwianRpIjoiZmU0YmJlNjdiNmE0NDEzZTgxY2ZjYTZiNGUyOTE5YWEiLCJ1c2VyX2lkIjoxMX0.JtyGSL_nJ4iiKXqijvxCkipxMQAxTksFKEP6g5qPGiI', 'created_at': datetime.datetime(2020, 12, 14, 17, 49, 40, 602304), 'expires_at': datetime.datetime(2020, 12, 28, 17, 49, 40), '_id': ObjectId('5fd7a5b444a87611a60654ae')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} -
How to avoid duplicate values from queryset
I am having three models class Records(Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE, related_name="records_plan", null=True) observation = models.CharField(max_length=255, blank=True) description = models.TextField(null=True, blank=True) rating = models.CharField(max_length=255, blank=True) class Plan(Model): plan_title = models.CharField(max_length=255, blank=True) plan_size = models.ForeignKey(Size, on_delete=models.CASCADE, related_name="%(class)s_size", null=True) description = models.TextField(null=True, blank=True) class Size(Model): value = models.CharField(max_length=255, blank=True) order = models.CharField(max_length=255, blank=True) In this I need to draw a chart of plan based on size of the plan my initial queryset is qs = Plan.objects.values('plan_size__value').annotate( count=Count('plan_size__value'), ).order_by("-plan_size__order").distinct() Using this query i'm able to get a queryset with data and field The same queryset I would like to apply a filter on later stages of my code qs = qs.filter(records_plan__rating = 'low') In this case I am getting the output , but values are duplicating (Example, if a plan having two records my chart need to consider it as a single plan , but here it comes as two plans),how to fix this Or how do I get the distinct value of plan while filtering it with record model -
What is the best way to create a website. Django or React Js or Angular Js or Node Js [closed]
I have finished a course on web development and I learn Django and a bit of react js. I want to know what is the best way to create a website that is used in real-life web applications. Well I searched through google and found that most web applications are made with React Js and firebase I want to know if I should go with Django or React Js with Firebase or with Angular Js with Firebase or should I go with node.js I want to know what's really used in real-life web applications so I can start practicing or if there are recommended courses please do tell me and I would like a description of why I should go with that so I could make a decision with what web development part I should go with or what is the best at least. Thanks, -
Select multiple rows from list to perform action [closed]
I have a Table-List which is getting their values from the Database, where each row is a representation of a model in the DB. Now I want to make them selectable (checkbox), to multiple delete or submit entries. As now I can only delete entries by deleting them row for row. I dont have any idea at all how to achieve this, hopefully someone has an directional idea?