Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JWT validation in class based view django
I've implemented jwt authentication in django using Django-graphql-jwt library, now I want to allow get/post on my endpoint (/graphql) only for requests with JWT token. There are examples in django-graphql-jwt documentation like @login_required, but I don't want to put a decorator above every query and mutation. So, I've decided to restrict an access to a view. I added path('graphql/', PrivateGraphQLView.as_view()) in url.py but how can I implement request checking for a valid token in the header? from graphene_django.views import GraphQLView class PrivateGraphQLView(GraphQLView): pass -
Adding Semantic UI React value of Form.Select into variable I post into my Django API
I'm new to React and I try to understand how I can add Form.Select value into my variables that I post into my Django API. When I only use Form.Input it works ok but when I add a Form.Select value doesn't passed into the userform. I saw that using event.target.elements.inputname.value is not possible for Form.Select, but after a lot of hours trying to make this works ... it looks like I'm unable to do it. errors shown is : Uncaught TypeError: Cannot read property 'value' of undefined Your help would be much appreciated. Thanks a lot !!! Here is my code : import React from 'react' import { Button, Form } from 'semantic-ui-react' //import axios from 'axios' const options = [ { key: 'm', text: 'Male', value: 'male' }, { key: 'f', text: 'Female', value: 'female' }, ] class MyClass extends React.Component{ handleFormSubmit = (event) => { event.preventDefault() const aa = event.target.elements.aa.value const bb = event.target.elements.bb.value const cc = event.target.elements.cc.value //axios.post('http://127.0.0.1:8000/api/blabla', { // aa: aa, // bb: bb, // cc: cc, //}) // .then(res => console.log(res)) // .catch(err => console.log(err)) console.log(aa, bb, cc) } render() { return( <div> <Form onSubmit={this.handleFormSubmit}> <Form.Input name="aa" placeholder='...' /> <Form.Input name="bb" placeholder='...' /> <Form.Select name="cc" … -
foreign key and relate name
i made a comment form and i want to attach every comment with the relate body i want to make Blogpost appear in html template enter image description here models: class Comment(models.Model): blogpost = models.ForeignKey( BlogPost, on_delete=models.CASCADE, related_name='img') name = models.CharField(max_length=256) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) views: class CommentView(View): def get(self, *args, **kwargs): form = CommentForm() blogpost = BlogPost.objects.all() comment = Comment.objects.all() return render(self.request, 'blog/comment.html', {'form': form, 'blogpost': blogpost, 'comment': comment}) template: {% csrf_token %} <label for="name">name</label> {{ form.name }} <label for="body">body</label> {{ form.body }} <label for="email">email</label> {{ form.email }} {{ form.blogpost }} <button class="btn btn-primary" type="submit">Submit</button> {% for thing in blogpost %} {{ thing }} {% endfor %} </form> what should i do ? -
Upgrading Django 1.11 to 3.X/Python2.7 to 3.7
I have a fairly old website running Django 1.11 and Python 2.7. I am not sure why it doesn't seem to be updating. I upgraded Python3.5 to Python3.7 just now. Deleted the old virtualenv (by deleting app/bin and creating a new virtualenv with virtualenv --python=/usr/bin/python3 . ) When in the virtualenv, if I do a python -V I get Python 3.7.7. If I run django-admin --version I see 3.0.6. But when I try to run the server, my Traceback says: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) So it's still pointing at apparently an old global install? How can I point it to the new version in the virtualenv I've created? -
Beginner Looking for Advice on How to Progress with Current Project
To combat a personal convenience issue and learn more about APIs, I made a python program that prompts a user for a YouTube playlist and transfers the songs from that playlist into a new or existing Spotify playlist (destination also prompted). I finally was able to get all the functionality working, but now I'd like to continue building the project, but I'm not really sure what to do next. Some things I'm interested in learning are building my own REST API and front and backend development, and wanted to incorporate that in this project by making a website where a user could log into their Youtube and Spotify accounts and complete the transfers in a more aesthetically pleasing interface as opposed to just running a python file. If anyone has advice on what would be best for a beginner to build next, and what technologies would be most relevant for front/back end, it would be greatly appreciated. Thanks! -
Creating a function to open a new folder each time an image is uploaded
I want to create a function where everytime a user uploads an image a new folder is created with their username (designer_name) and associate each title to each uploaded Image is that possible? If it is what is the best way to do it? The model class Post(models.Model): designer_name = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse("score:post-detail", kwargs={"pk": self.pk}) -
How to use annotated (alias) field on the left of values as part of group by (i.e. values) clause in django using ORM?
Having challenge to get a summarized result by using django ORM utilizing an annotated field then apply values with that alias into the values (group by) and followed by other annotations to complete the aggregated field Sample data: >>> >>> models.Sale.objects.values().first() {'id': 93, 'sales_order': 'SON4000006', 'transaction_date': '2020-05-04 00:00:00', 'customer_name': 'Customer No2', 'delivery_note': 'DN200006', 'vehicle_number': 'T101AAA', 'tax_invoice': 'TI900006', 'product_name': 'Pro Cememnt', 'quantity': '100', 'total_value': '50000', 'quantity2': None, 'total_value2': None, 'destination': 'Zambia', 'agent_id': None, 'created_at': datetime.datetime(2020, 5, 9, 6, 48, 26, 59719, tzinfo=<UTC>), 'updated_at': datetime.datetime(2020, 5, 9, 6, 48, 26, 59719, tzinfo=<UTC>)} >>> >>> >>> models.Document.objects.values().first() {'id': 27, 'ref_number': '2019 MATARE75/251', 'description': None, 'doc_type': 'Exit', 'file': 'docs/SKM_Sales20042214362_Msp5YxV.pdf', 'sale_id': 85, 'created_at': datetime.datetime(2020, 4, 25, 16, 11, 24, 847574, tzinfo=<UTC>), 'updated_at': datetime.datetime(2020, 4, 25, 16, 11, 24, 847574, tzinfo=<UTC>)} >>> >>> >>> >>> >>> qs1=models.Sale.objects.annotate(docs_count=Count('docs'), complete=Case(When(docs_count=3, then=True), default=False, output_field=BooleanField())).values('destination', 'complete').annotate(count=Count('id'), qty=Sum('quantity'), value=Sum('total_value')).order_by('destination','complete') >>> >>> >>> >>> print(qs1.query) SELECT "sales_sale"."destination", CASE WHEN COUNT("sales_document"."id") = 3 THEN True ELSE False END AS "complete", COUNT("sales_sale"."id") AS "count", SUM("sales_sale"."quantity") AS "qty", SUM("sales_sale"."total_value") AS "value" FROM "sales_sale" LEFT OUTER JOIN "sales_document" ON ("sales_sale"."id" = "sales_document"."sale_id") GROUP BY "sales_sale"."destination" ORDER BY "sales_sale"."destination" ASC, "complete" ASC Expected output is: SELECT "sales_sale"."destination", CASE WHEN COUNT("sales_document"."id") = 3 THEN True ELSE False END … -
Django Blog - Comment function shows dropdown menu for authors in form
I created a Django Blog and want to add a comment section. So far I created the Comment-models and it is possible to make comments. But for every user it shows a dropdown menu where they can chose the user which will displayed with the comment-posting, which should not be. I tried to modifiy the Comments model and take out the 'author' in forms.py, but nothing works. Does anyone have an idea what I could do here? I assume it must have something to do with the author, I also tried 'author = models.ForeignKey(User, on_delete = models.CASCADE)' but same result. This is how my code looks like: # in forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('text',) #fields = ('author', 'text',) # in models.py class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text #here a part from views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' #<app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post def add_comment_to_post(request, pk): post = … -
Django - How to post all those checkbox ID's which are unchecked as well to views
I have a table ( 7X4 ). First column of a table is checkbox. With the below code, I can get all the checked items in the UI to views, but I wanted to get unchecked ID's as well. Below is my templates file: <table id="tableForm" name="table-data" class="table table-striped table-bordered zero-configuration"> <thead> <tr> <th>Select</th> <th>Week Day</th> <th>Timing</th> <th>Action</th> </tr> </thead> <tbody> {% for row in days_data %} <tr> <td id="{{row.id}}"><input value="{{row.set_name}}" name="checks" type="checkbox"></td> <td> {{row.day}} </td> <td>{{row.set_name}}</td> <td> </tbody> </table> views.py file def weekDays_set(request): if request.method == 'POST': year = request.POST.get('form_year') batch = request.POST.get('form_batch') days = request.POST.getlist('table-data') days1 = request.POST.getlist('checks') print(days1) # I am getting only checked rows ID's I can get only checked row ID's in dictionary, Can someone help me on getting unchecked rows data as well please ? -
How to write this Django HTML template more efficiently?
I have a Django app where users can create their lists and add to-dos. I want to add a new page which will show to-dos that had due dates. Like, in the page, there will be a section called "Earlier" which was feature tasks with missed due dates. Other sections would be "Today", "Tomorrow" and "Later on". Let me show my view class and HTML code now and explain my problem. Class based view to handle this page: class ToDoNextUpView(LoginRequiredMixin, ListView): model = ToDo template_name = "ToDo/next_up.html" ordering = ["-due_date"] context_object_name = "todos" def get_queryset(self): query_set = [] for todo in ToDo.objects.filter(creator=self.request.user, is_checked=False): if todo.due_date is not None: query_set.append(todo) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) today = datetime.datetime.now(datetime.timezone.utc) tomorrow = today + datetime.timedelta(days=1) todos_earlier = [] todos_today = [] todos_tomorrow = [] todos_later = [] for todo in ToDo.objects.filter(creator=self.request.user, is_checked=False): if todo.due_date is not None: if todo.due_date.day == today.day and todo.due_date.month == today.month and todo.due_date.year == today.year: todos_today.append(todo) elif todo.due_date.day == tomorrow.day and todo.due_date.month == tomorrow.month and todo.due_date.year == tomorrow.year: todos_tomorrow.append(todo) elif todo.due_date < today: todos_earlier.append(todo) elif todo.due_date > tomorrow: todos_later.append(todo) context["todos_earlier"] = todos_earlier context["todos_today"] = todos_today context["todos_tomorrow"] = todos_tomorrow context["todos_later"] = todos_later return context And this is … -
ValueError at /user_settings/ ModelForm has no model class specified
I'm creating a user setting page , where user can update his/her profile but after creating a ModelForm is gives this error. ModelForm has no model class specified. code in forms from django import forms from django.forms import ModelForm from blog.models import * from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserForm(ModelForm): class Mata: model=customer fields= '__all__' exclude=['user'] Code in views @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def user_settings(request): users=request.user.customer form=UserForm(instance=users) if request.method == 'POST': form=UserForm(request.POST, request.FILES, instance=users) if form.is_valid(): form.save() context = {'form':form} return render(request, 'blog/account_settings.html', context) Kindly help anyone -
Pointing Django storage to BunnyCDN
So I'm trying to serve /media/ files in a website through BunnyCDN, but I'm not exactly sure if I'm doing it right. From other remote storage implementations that I've seen, like AWS S3, I'm supposed to override the storage file that Django uses in my settings.py and do weird things to my urls file to point it to the server, but I'm kind of confused since the BunnyCDN documentation is very limited, and Django's own docs on writing custom storage systems are not very clear on this. I can't find anything since everyone seems to use AWS for this. -
Initializing manually rendered choice field on validation error
I've got a choice field that I'm manually rendering in my template. template.html <select name="pricing" id="id_pricing"> <option value> Make a selection </option> {% for value, object in form.pricing.field.choices %} <option value="{{value}}" {% if form.pricing.initial == value %} selected {% endif %} > {{object}} </option> {% endfor %} </select> This works 100% with one exception. If there is a validation error that gets thrown on another field due to checks that I have in def clean(), on the reload of the page, the value that populates the choice field isn't the one that the user just selected prior to submitting the form. It's 'Make a selection'. Do you know how I can ensure that the value that populates the choice field on reload of page due to validation error is the one that the user selected? Thanks for your help! -
Django 3.0: Unable to get value in view of selected option in template
I am at beginner level in django. And, I am unable to get the value of user selected option in view. I have to apply some logic there. views.py def shop(request): if request.GET.get('featured'): featured_filter = request.GET.get('featured') print(featured_filter) #debugging purpose else: print("\n\nnone\n\n") #debugging purpose bookz = Book.objects.order_by('title') var = {'books': bookz, 'range': 10} return render(request, 'bookrepo/shop.html', context=var) shop.html <form action="{% url 'bookrepo:shop' %}" method="GET"> <select name="featured" class="custom-select-lg custom-select"> <option selected><h1>Filter</h1></option> <option value="pricelow">Low price</option> <option value="pricehigh">High price</option> <input type="submit" name="featured" value="Filter" /> </select> </form> These option things have nothing to do with models. So right now, I am getting this when I select low price and press button: (in django console) [10/May/2020 00:18:20] "GET /shop/?featured=pricehigh&featured=Filter HTTP/1.1" 200 47486 [10/May/2020 00:18:20] "GET /static/js/js.dom.changer.js HTTP/1.1" 304 0 Filter [10/May/2020 00:18:24] "GET /shop/?featured=pricelow&featured=Filter HTTP/1.1" 200 47486 As u can see "Filter" is getting printed. But i want is featured's value like pricelow or pricehigh. -
How do I add security requirements to the password of my Django custom user model?
I'd like to start saying that I'm a beginner to Django, and I've been following a pretty great tutorial so far from Corey Schafer. In the project Corey uses the default Django User model, but I didn't want the users to log in with their username so I decided to override this as the Django docs say at https://docs.djangoproject.com/en/3.0/topics/auth/customizing/. I updated my registration forms with the new models and everything works fine. I can log in, log out and register properly, but I noticed that the password requirements for registration are gone. Previously Django would check if my password was too similar to the rest of my data, and had a minimum length requirement. I would like to know if there is a way to restore this feature. Here is my code for users/models.py: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from PIL import Image class UserManager(BaseUserManager): def create_user(self, email, name, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password=None): """ Creates and saves a … -
(Django) automatic record creation for checklist?
I would like the user to be able to select a checklist for a project, however I believe the connection needs to be between the project and a checklist's items, not the checklist itself. This is to allow for an additional boolean field to mark whether an item has been completed for a specific project. However I only want the user to select the checklist name - so how would I code the app to automatically create the appropriate junction_project_checks records upon selecting a checklist? project(models.Model): name = models.CharField(max_length=100) checklist = models.ManyToManyField(checklist) checklist(models.Model): name = models.CharField(max_length=100) checks = models.ManyToManyField(checks, through='junction_checklist_checks') checks(models.Model): name = models.CharField(max_length=100) body = models.TextField() junction_checklist_checks(models.Model): checklist_id = models.ForeignKey(checklist, on_delete=models.CASCADE) checks_id = models.ForeignKey(checks, on_delete=models.CASCADE) junction_project_checks(models.Model): checks_id = models.ForeignKey(checks, on_delete=models.CASCADE) project_id = models.ForeignKey(project, on_delete=models.CASCADE) checkbox = models.BooleanField(default=False) -
How to create a selection based (multiple apps) experiment task in Django?
I am working at an experiment design and want to ask about your opinion and the feasibility with Django. We want to simplify our online experiments (university) and want to create a platform for our researchers to select settings for an online task (Picture 1). These are existing apps like a chatbot. There are also different settings / treatments like the collection of badges. Based on the selection, a website with its selected content and one or more links are generated to send out to a test person (Picture 2). I have some questions about this: How can I display all apps/experiments on one homepage (Picture 1) and generate sites for the selection (Picture 2)? How can I generate unique links for the sites to send them out to probands? Is Django the right option? I now that some of these questions are more opinion-based and I appreciate every answer on that! -
I was redirecting to same login page again and again and it's not even authenticating the credentials
my login page: <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>Page Title</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <link rel='stylesheet' type='text/css' media='screen' href='main.css'> <script src='main.js'></script> </head> <body> <form action="login" media="post"> {% csrf_token %} <input type="text" name="username" placeholder="username"><be> <input type="password" name="password" placeholder="password"><be> <input type="Submit"> </form> </body> </html> views.py : from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth from django.contrib.auth import authenticate # Create your views here. def homepage(request): return render(request, 'homepage.html') def login(request): if request.method== 'POST': username = request.POST.get(username) password = request.POST.get(password) user = authenticate(username='username', password='password') if user is not None: auth.login(request, user) return redirect("/") else: messages.success(request,'password not matching') return redirect('home') else: return render(request,'login.html') my urls.py: from django.urls import path from . import views urlpatterns = [ path('',views.homepage, name='homepage'), path('login',views.login, name='login'), path('registration',views.registration, name='registration'), ] every single time this login page is redirecting to same login page, whether I enter wrong credentials or the right one, I think its not even verifying the credentials that whether they are right or wrong. please help me out. -
invalid parameter error on stripe payment creation
In the class below i am trying to create a stripe payment charge but i keep getting an exception that is in the except block (the stripe.error.InvalidRequestError) and it keeps telling me invalid parameters when i try to create a payment. here is the class. class PaymentView(View): def get(self, *args, **kwargs): # equipment_order return render(self.request, "payment.html") def post(self, *args, **kwargs): equipment_order = models.EquipmentOrder.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(equipment_order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, #cents currency="usd", source=token ) # create payment payment = models.Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = equipment_order.get_total() payment.save() # assign payment to order equipment_order.ordered = True equipment_order.payment = payment equipment_order.save() messages.success(self.request, "Your order was successful!") return redirect("create:equipment_home_page") except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") return redirect("create:equipment_home_page") ... except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.error(self.request, "Invalid parameters") return redirect("create:equipment_home_page") ... -
using signals in django application code suggestion
Hello everyone I want to do charts based on my models the count of mail_items sent per countries , in my model you will see Country_origine the idea is I want to do another model that has 2 columns ' country ' and ' mail_items_count ' then I want to make a signal when new item saved to ' mail_items ' the signal will update the ' country+mail_items_count ' increase the ' mail_items_count ' by one , also I want to make a function to sum all counts in the ' mail_item_count ' column . in my views.py I want to make a view that query all countries with their ratio : ( I have to make a dictionary, I have to loop throw each object in the query , and take the country name as the key in the dictionary , and take the counter (integer) divided by the output of the sum function to calculate the ratio of each country , and append in the dictionnary ... to send the response with all coutries and ratio dictionnary) models.py class mail_items(models.Model): mail_item_fid = models.OneToOneField(Mail_item_Event,on_delete=models.CASCADE) Event_code = models.OneToOneField(Mail_item_Event,on_delete=models.CASCADE,related_name="mail_item_event_cd") office_Evt_cd = models.ForeignKey(Office,on_delete=models.CASCADE, related_name='office_Ev') Date_Evt = models.DateTimeField() Country_origine = models.ForeignKey(Pays, on_delete=models.CASCADE ,related_name='paysOrigine') … -
Django comment adding
''' views.py I want to add comment in my blog. It shows problem. How to get rid of ''' class PostDetail(View): def get(self, request, slug): detail = BlogSlider.objects.get(slug=slug) form = CommentForm() return render(self.request, 'blogdetails.html', {'detail': detail, 'form':form}) def post(self, request, *args, **kwargs): form = CommentForm(request.POST, request.FILES or None) if form.is_valid(): message = form.cleaned_data['message'] comment = Comment( message=message, user=self.request.user, ) comment.save() ''' models.py ''' class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(BlogSlider, on_delete=models.CASCADE) message = models.CharField(max_length=1000) def __str__(self): return self.user.username ''' forms.py ''' class CommentForm(ModelForm): class Meta: model = Comment fields = ('message',) -
AttributeError: module 'posts.views' has no attribute 'add_comment_to_post'
hello iam new to python and while adding comment option to my djang project while editing the views.py its show as following: and while typing python3 manage.py runserver **the terminal shows the following:**** File "/home/user/Documents/DJANGO-COURSE-2.xx/DJANGO_COURSE_2.xx/21-Social_Clone_Project/simplesocial/posts/urls.py", line 12 , in path('post//comment/', views.add_comment_to_post, name='add_comment_to_post'), AttributeError: module 'posts.views' has no attribute 'add_comment_to_post' and the views.py and urls.py file is given below: image description is of view.py file image description of urls hope that i will get convenient answer ASAP -
Django url can't find attribute of related view function
I have the following view that returns a user sign up form with an e-mail validation logic. views.py from django.contrib.sites.shortcuts import get_current_site from django.shortcuts import render, redirect from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.template.loader import render_to_string from users.forms import SignUpForm from .tokens import account_activation_token def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: form = SignUpForm() return render(request, 'users/signup.html', {'form': form}) and according url mapping that shall redirect the user upon submitting the registration to the mail activation information page. urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('register/', views.signup, name='signup'), url(r'^account_activation_sent/$', views.account_activation_sent, name='account_activation_sent'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), ] now the url module throws this error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Jonas\Desktop\CFD\CFD\CFD\urls.py", … -
Original exception text was: 'QuerySet' object has no attribute 'client'
I Got AttributeError when attempting to get a value for field client on serializer ClientSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance models.py class Box(models.Model): box = models.IntegerField() controller = models.ForeignKey(Controller, related_name='boxes', on_delete=models.CASCADE) def __str__(self): return str(self.box) class Client(models.Model): client = models.CharField(max_length=30) cpf = models.IntegerField() box = models.OneToOneField( Box, on_delete=models.CASCADE, primary_key=True ) def __str__(self): return self.client serializers.py class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = [ "id", "client", "cpf", "box", ] class BoxSerializer(serializers.ModelSerializer): class Meta: model = Box fields = [ "id", "box", "controller" ] views.py class ClientViewSet(viewsets.ModelViewSet): serializer_class = ClientSerializer queryset = Client.objects.all() def list(self, request, store_pk=None, locker_pk=None, controller_pk=None, box_pk=None): queryset = Client.objects.filter(box=box_pk, box__controller=controller_pk, box__controller__locker=locker_pk, box__controller__locker__store=store_pk) serializer = ClientSerializer(queryset, context={'request': request}) return Response(serializer.data) def retrieve(self, request, store_pk=None, locker_pk=None, controller_pk=None, box_pk=None): queryset = Client.objects.filter(box=box_pk, box__controller=controller_pk, box__controller__locker=locker_pk, box__controller__locker__store=store_pk) client = get_object_or_404(queryset) serializer = ClientSerializer(client, context={'request': request}) return Response(serializer.data) I'm trying to get the object client on lockers/1/controllers/1/boxes/1/client/ which is OneToOneField relations with boxes and It's in a nested router I already tried use decorator @action but yet didn't work Anyone know why it's not finding the correct object attribute -
Enable Django support in IntelliJ?
I saw this question, but it doesn't help. I just made a new project in IntelliJ, (Community 2020.1 EAP). This is a Linux OS (Mint 18.3). In the left-hand panel I chose "Python". When I have created it I go File --> Project structure. I click "Facets" in the left-hand panel. In the middle panel it says "No facets are configured" and under that "Detection". I click the "+" sign and then where it says "Buildout Support facet will be added to the selected module" I click OK. After that, in the middle panel, Buildout Support is highlighted, and in the right-hand part it says "Use paths from script:" (with a blank text field) and under the field "Set to <buildout-dir>/bin/django.py for proper Django support". This leaves me very puzzled. It suggests that there is a setting "buildout-dir", and even supposing I can find a file "django.py" in a directory "bin" I haven't got a clue what I'm meant to enter in that box: the full path to "django.py"? The full path above "bin"? Then I go looking on my machine for django.py: 369] mike@M17A ~/IdeaProjects/TempDjango $ locate django.py /home/mike/.local/share/JetBrains/IdeaIC2020.1/python-ce/helpers/pycharm/teamcity/django.py /home/mike/python_venvs/test_venv369/lib/python3.6/site-packages/django/template/backends/django.py Neither looks at all promising. Naturally I have tried …