Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how could i solve broken this pipe problem?
Quit the server with CTRL-BREAK. [29/Sep/2021 22:19:36] "GET / HTTP/1.1" 200 37607 [29/Sep/2021 22:19:43,135] - Broken pipe from ('127.0.0.1', 56390) [29/Sep/2021 22:19:45,208] - Broken pipe from ('127.0.0.1', 56396) [29/Sep/2021 22:19:45,219] - Broken pipe from ('127.0.0.1', 56411) -
How do add +1 to the PositiveIntegerField model field when adding each new Post?
I have a Posts model. And field Order = models.PositiveIntegerField() has been created for arbitrary sorting. class Post(models.Model): title = models.CharField(max_length=15) create = models.DateTimeField(auto_now_add=True) Order = models.PositiveIntegerField() Objective: in the model, overriding the save method, do add the index +1 (from the last available index of Posts) to this field when adding each new Post. That is, each post must have an Order-index, and if there are already 3 posts on the site, then when the fourth is added - index 4 is added to his the field, and so on. "1" index in Order field (1st post), "2" index in Order field (2nd post) etc 3, 4, 5... similar ID. Help implement this logic im method save. It seems simple, but I don't know how to approach it. I understand that in the model and what I do: def save(self, *args, **kwargs): qs = self.order.objects.all() last_item = qs.latest(self.order) last_item.order += 1 super().save(*args, **kwargs) But this don't work. Help me, please! -
why django post method doesn't work this case?
html file <form action="/input" method="post"> {% csrf_token %} <input type="text" name="data" /> <input type="submit" value="post" /> </form> view.py def a(request): x=request.POST['data'] html='<h1> {} </h2>'.format(x) return HttpResponse(html) it shows Server Error (500) and when i change line 3 in view.py to "html='html=' {} '.format(request.method)" it shows "GET". i want to use "post" but it doesn't work -
I want to build a private chat application
I am trying to build a private chat application using django channels. I created the a chat application by following django channels docs. But I need a system like that- If a logged in user select another user they can chat each other in a private chat room. Here is the code I tried. I am completely new in django channels. So the codes are from the docs Here is my views from django.shortcuts import render # Create your views here. def get_home_page_url(request, *args, **kwargs): args = {} return render(request, 'chat/index.html', args) def get_room_url(request, room_name, *args, **kwargs): return render(request, 'chat/room.html', { 'room_name': room_name }) Here is routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] Here is my models.py class PrivateChatRoom(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user1") user2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user2") is_active = models.BooleanField(default=True) class RoomChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(PrivateChatRoom, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField(unique=False, blank=True) I am trying to implement this models to realtime chat but i dont know what logic should i use. I have no experience in django channels and sockets. ** Need Urgent Help ** -
Just like we have TypeScript for JavaScript, whey do we not have some super set language for Python to introduce type safety?
I felt that type-safety is very important for the development of applications. The absence of type safety is one of the major sources of bugs. So just like Typescript introduces type safety to javascript, why do we not have some like that for python -
Django filter and pagination doesn't display
i created 2 query list, in the first list i created, the filter and pagination is displayed successfully, but when there is no item in the second datatable i created, it appears successfully, but when I add a item to table, it disappears. my models.py; class nagioslar(models.Model): nekip = models.TextField(max_length=100, null=True) nalarmseviyesi = models.TextField(max_length=100,null=True) nr1 = models.TextField(max_length=100, null=True) nr2 = models.TextField(max_length=100, null=True) nr3 = models.TextField(max_length=100, null=True) nkonu = models.TextField(max_length=100, null=True) netki = models.TextField(max_length=100, null=True) ndetaylar = models.TextField(max_length=100, null=True) niletisim = models.TextField(max_length=100, null=True) views.py; def nagios(request): nmembers_list = nagioslar.objects.all() paginator = Paginator(nmembers_list, 1000000000000000) page = request.GET.get('page', 1) try: nmembers = paginator.page(page) except PageNotAnInteger: nmembers = paginator.page(1) except EmptyPage: nmembers = paginator.page(paginator.num_pages) return render(request, 'nagios.html', {'nmembers': nmembers}) html; <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> Nagios Alarmlar <a class="btn btn-sm btn-success" href="{% url 'ncreate' %}" style="padding: 8px; float: right; background-color: green; color: white;">EKLE</a> </div> <div class="card-body"> <div class="table-responsive "> <table class="table table-striped table-bordered text-center dataTable no-footer align-center align-middle " id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Ekip</th> <th>Alarm Seviyesi</th> <th>R1</th> <th>R2</th> <th>R3</th> <th>Konu</th> <th>Etki</th> <th>Detaylar</th> <th>İletişim</th> </tr> </thead> <tbody> {% for nmember in nmembers %} <tr> <td>{{ nmember.nekip }}</td> <td>{{ nmember.nalarmseviyesi }}</td> <td>{{ nmember.nr1 }}</td> <td>{{ nmember.nr2 }}</td> <td>{{ nmember.nr3 }}</td> <td>{{ nmember.nkonu … -
How to get current user id in Django Rest Framework serializer
I have a serializer that gets product date from a table and the inventory data from another table for the user that is logged in. I have set up the serializer to get the product data and added fields which should hold the user's inventory amount. The request returns the correct data structure, however it was returning the inventory amount for all users and then failing. So I have tried to filter these added fields by the current users id, however when adding it it fails. I would like to filter the added fields for the user's inventory by the user id for the user that is logged in. However adding it seems to break the request. class CardsDataSerializers(serializers.ModelSerializer): inventory = serializers.SerializerMethodField() class Meta: model = magic_set_cards fields = ['id', 'name', 'rarity', 'manaCostList', 'convertedManaCost', 'colors', 'number', 'type', 'types', 'imageUri', 'promoTypes', 'hasFoil', 'hasNonFoil', 'inventory'] @staticmethod def get_inventory(self, obj): user_id = self.request.user.id try: standard = inventory_cards.objects.filter(user_id=user_id).filter(card_id=obj.id).values_list('standard').get()[0] except inventory_cards.DoesNotExist: standard = 0 try: foil = inventory_cards.objects.filter(user_id=user_id).filter(card_id=obj.id).values_list('foil').get()[0] except inventory_cards.DoesNotExist: foil = 0 inventory = { 'standard': standard, 'foil': foil, } return inventory Error: get_inventory() missing 1 required positional argument: 'request' Request Method: GET Request URL: http://127.0.0.1:8000/magic/sets/ss1/cards-data/?name= Django Version: 3.2.7 Exception Type: TypeError Exception Value: … -
ImportError: cannot import name 'Index' from 'landing.views'
So I was following a tutorial on Youtube, and here is the link: https://www.youtube.com/watch?v=Rpi0Ne1nMdk and I got to 12:46 when he got to importing Index. I hit run, but I received a Syntax Error instead. Here is a sample of my code: from django.urls import path from landing.views import Index urlpatterns = [ path('', Index.as_view(), name='index'), ] when I hit run, this returned: ImportError: cannot import name 'Index' from 'landing.views' (/home/runner/red-chilli-media/landing/views.py) If it looks weird, it's because I'm using replit. I used the django project, and the language is Python/HTML. if any information is missing, please tell me. The error is in Python, as you can clearly see. -
Django ModelForm with Access to More than One Model
So, i want to know if it possible to have a django modelform access more than 1 django model... i currently have 2 models relating to the product and they are shown below...the reason i made 2 models is to allow each product to have multiple images class Product(models.Model): title = models.CharField(max_length=255) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) thumbnail = models.ImageField(upload_to='uploaded_products/', blank=True, null=True) description = models.TextField(max_length=255, null=True, blank=True) categories = models.ManyToManyField(Category,related_name='products', blank=True, help_text="Select One or More Categories that the product falls into, hold down ctrl to select mutiple categories") tags = models.ManyToManyField(Tag, blank=True) stock = models.PositiveIntegerField(default=1, blank=True) notes = models.TextField(null=True, blank=True) ownership = models.FileField(blank=True, null=True, upload_to='product_files', help_text='Optional : provide valid document/picture to proof ownership (presence of this document increases the reputation of your product).Note: Provided Document if invalid or incorrect can be invalidated after upload') verified = models.BooleanField(default=False, blank=True, null=True) uploader = models.ForeignKey(Account, on_delete=models.CASCADE, blank=True) serial_number = models.CharField(max_length=255, blank=True, null=True) class Meta: ordering = ['-updated'] def __str__(self): return self.title class Product_Image(models.Model): name = models.CharField(max_length=255, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='uploaded_products/') default = models.BooleanField(default=False, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.name: self.name = self.product.title super().save(*args, **kwargs) Now i want to be able to access … -
Django admin url decoding
I have a Django admin panel with simple products view. Each product has it's own ID like "bus", "avia", "bus_24" and "avia_26". Url to products page look like this: /products/<product_id>/. For products with ids like "bus" and "avia" it works just fine. But for "bus_24" and "avia_26" I get HttpRedirect to main page with messages: Product with ID "avia&" doesn’t exist. Perhaps it was deleted? Product with ID "bus$" doesn’t exist. Perhaps it was deleted? I guees there is smth with decoding/encoding url, so "_24" = $ and "_26" = &. I tried to override get_object method of admin.ModelAdmin to decode object_id but it didn't worked out. Maybe someone had same problem? -
How to create a function to pass ajax data when a button is clicked
I want the ajax data to be passed to the add_teacher function in views.py when the "Add Teacher" button is clicked. path('student/add_teacher/', views.add_teacher, name='add_teacher'), If only the code below is executed, the value is output to the console. $(function () { $checkbox = $('.Checked'); $checkbox.click(checkArray); function checkArray(){ var chkArray = []; chkArray = $.map($checkbox, function(el){ if(el.checked) { return el.id }; }); console.log(chkArray); } ); But when I add a button click condition, the function doesn't work. $(function () { $('button.addteacher').on('click',function () { $checkbox = $('.Checked'); $checkbox.click(checkArray); function checkArray(){ var chkArray = []; chkArray = $.map($checkbox, function(el){ if(el.checked) { return el.id }; }); console.log(chkArray); $.ajax({ url: "/student/add_teacher/", type: "post", data: {'chkArray' : chkArray}, headers: { "X-CSRFToken": "{{ csrf_token }}" }, }); } }); }); The html file looks like this: <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Sex</th> <th>Select</th> </tr> </thead> <tbody> {% for student in students %} <tr class="student"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.sex }}</td> <td><input type="checkbox" class="Checked" id="{{ student.id }}"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Add Teacher</button> -
Django object creation from form with nested elements - not behaving as expected
I am using Django 3.2 I am trying to create an object that has child elements, (without using formsets). I have used Javascipt to build a user friendly UI that allows a user to dynamically add the child elements. The post method of the route handler class parses the POST fields and extracts the child elements. This is a simplified version of my codebase: /path/to/myapp/models.py class Question(models.Model): title = models.CharField(max_length=64) start_date = models.DateTime() end_date = models.DateTime() class Choice(models.Model): title = models.CharField(max_length=64) pos = models.PositiveSmallInteger(default=0) question = models.ForeignKey(Question, on_delete=models.CACSCADE, related_name='choices') /path/to/myapp/forms.py class QuestionForm(forms.ModelForm): def clean(self): cleaned_data = super().clean() start_date = cleaned_data['start_date'] end_date = cleaned_data['end_date'] if end_date <= start_date: self.add_error('end_date', ValidationError(_('End date must be greater than the start date'), code=_('invalid_date'))) class Meta: model = Question /path/to/myapp/views.py class QuestionCreateView(CreateView): model = Question form_class = QuestionForm def post(self, request, *args, **kwargs): post_data = request.POST question_choice_data = [x.split('-') for x in post_data.get('question_choices','').split(',')] # <- object is sometimes created on this line! form = self.form_class(post_data) if form.is_valid(): new_question = form.save(commit=False) # set some field attributes # ... new_question.save() for position, choice_name in question_choice_data: Choice.objects.create(question=new_question, title=choice_name, pos=int(position)) When I attempt to save a new question by POSTing, two unexpected things happen: The post() method appears to be … -
Django - How to call Detailview as alternative to UpdateView based on user auth and pk
I need to have user2 (with no authorization) to see a DetailView instead of the UpdateView (that user1 can see) as alternative view in a shared ListView, by calling the appropriate page with object PK(title). Anyone knows what's the best practice to accomplish this or where/what should I look for to reach my objective? Thanks in advance! Details: I can't figure how to do this and call the Detailview correctly. I already created both UpdateView and DetailView and all it is apparently needed but I have to call them both from object pk and doesn't work. HTML {% extends 'base/mybase2.html' %} {% load static %} {% block content %} <h1> List</h1> <a class="btn btn-outline-info " href="{% url 'home' %}">Back to homepage</a> <a class="btn btn-sm btn-outline-primary" href="{% url 'a_add' %}">Add</a> <hr> {{ myFilter.form }} <hr> <ul> <table class="table table-hover table-light table-striped"> <thead> <tr><th scope="col">#Title</th>...</tr> </thead> <tbody> <tr> <caption>Total number of selected objects: {{ page_obj.paginator.count }}</caption> {% for object in object_list %} {% if perms.varmodel.change_atitle %} <th scope="row"><a href="{{ object.get_absolute_url }}">{{ varmodel.a_number }}</a></th> {% else %} <th scope="row"><a href=#>{{ varmodel.a_description }}</a></th> {% endif %} <td> {{ ... }} </td> URLS from django.urls import path from varapp.views import AListView from varapp.views import ACreateView, … -
Possible authorization/authentication for html?
Is it possible do do something like this for the author in HTML? (I want the Author to see the delete and cancel buttons but other users just get the 3 links.) post.html {% if user.is_authenticated and user == post.author %} <!-- Edit Buttons --> <div class="text-center form-group"> <a class="button-delete" type="button" href="{% url 'post_confirm_delete' post.id %}">Delete</a> <a class="button-cancel" type="button" href="{% url 'post' %}">Cancel</a> </div> <br> {% else %} <!-- Action Buttons --> <div class="row my-2"> <div class="col g-2 justify-content-evenly text-center"> <a class="card-link" type="submit" href="#">Save</a> <a class="card-link" type="submit" href="#">Applied</a> <a class="card-link" type="submit" href="#">Hide</a> </div> </div> {% endif %} This is some of the code for view. view.p class PostListView(ListView): model = post template_name = 'posts/post.html' context_object_name = 'posts' ordering = ['-created'] class PostDetailView(DetailView): model = post class PostCreateView(CreateView): model = Post form_class = PostForm template_name = 'posts/create_post.html' def form_valid(self, form): form.instance.author = self.request.user.gig return super().form_valid(form) class PostDeleteView(DeleteView): model = Post success_url = 'posts/my_post.html' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False -
cs50w commerce project : IntegrityError UNIQUE constraint failed
I'm working on cs50w's commerce project, trying to create a new listing, but I keep getting this error: IntegrityError at /new UNIQUE constraint failed: auctions_listings.user_id Here are my models for user and listing: class User(AbstractUser): pass #def __str__(self): #return f"{self.username}" class Listings(models.Model): title = models.CharField(max_length=30) desc = models.TextField() #starting_bid = models.FloatField(validators = [MinValueValidator(1)]) img = models.URLField(blank=True) category = models.CharField(blank=True,max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner", primary_key=True) This is my view for new listing: def new(request): if request.method == "POST": if not request.user.is_authenticated: return render(request, "auctions/new_listing.html", { "message": "Try logging in first" }) user = request.user ###################################################### for u in User.objects.all(): print(f" UID = = {u.pk} | Name = = {u}") ###################################################### title = request.POST["title"] img = request.POST["image"] category = request.POST["category"] #starting_bid = request.POST["starting_bid"] description = request.POST["description"] listing = Listings.objects.create( user = user, title = title, img = img, category = category, #starting_bid = starting_bid, desc = description ) if listing is not None: listing.save() return redirect("index") return render(request, "auctions/new_listing.html") And the form for creating a new listing: <form action="{% url 'new' %}" method="post" class="form-horizontal" style="width: 50%; margin: auto;"> {% csrf_token %} <div class="form-group"> <label for="title">Title: </label> <input type="text" name="title" id="title" class="form-control" autofocus required> </div> <div class="form-group"> <label for="image">Image URL: </label> <input … -
"Show more" button for images
I have a feature that allows users to upload multiple images. The issue is it displays all of the images and forces users to scroll all the way to the bottom if tons of images are uploaded. I want to implement a show more button something like this. code: {% if postgallery|length >= 1 %} <a class="imggallery-title">Image Gallery</a> <div class="row"> {% for images in postgallery %} <div class="col-md-3"> <a href="{{ images.images.url }}" data-lightbox="image-1"> <img class="img-thumbnail" src="{{ images.images.url }}" /> </a> </div> {% endfor %} </div> {% endif %} I understand I could setup and if statement to check to see if there are more than a set amount of posts but im not sure how I would handle the displaying of the rest with a button click -
How to implement (Automate) Updating security group in AWS using webpage
We have a website that is hosted on EC2 instance with public IP, Me and my friends only need access to that website (already google auth login is enabled) but we need to whitelist the IP's on the security group. Since we don't have VPN/tunneling setup it's hard to update every time on AWS.. (login and update the security group). So I'm planning to do something like this Create a webpage (Django) that has an option to update the security group. /access/testserver URL will have some kind of table to update them. But not sure how to do o where to start. Like If i click the button with IP how the value (IP) will parse from HTML page to python and update using boto3. Note: Since we're traveling or most of us are having mobile network to connect the website the ISP keep on changing so hard to whielist the IP -
Create locked object
Let's say I have a model class Foo. The structure doesn't matter. I want: foo = Foo.objects.create(...) # Do some stuff foo.bar = "something" foo.save() This is, of course, unsafe, because another project can fetch the newly created Foo instance and modify it at the same time, with the final save overriding the one that happens earlier. Using update_fields can reduce the risk, but it is still there for processes that modify the same field (bar, in my example above). A workaround for that is: foo = Foo.objects.create(...) with transaction.atomic(): foo = Foo.objects.select_for_update().get(pk=foo.pk) # Do some stuff foo.bar = "something" foo.save() All good, except it feels a bit redundant to have to refetch the object that I already have. Is there a way to select_for_update when creating a new object, or to select_for_update the foo itself after it was created, but without refetching it, or is the above the best approach when one needs to create an object and then do some modifications after the fact? -
AnyMail and MailGun configuration on Django
I'm setting AnyMail + MailGun on a Django project, but I'm getting an unauthorized response calling mail_admins: anymail.exceptions.AnymailRequestsAPIError: Sending a message to mail@gmail.com from mailgun@sandboxe6301378bfe741bf99d5684e65852283.mailgun.org Mailgun API response 401 (Unauthorized): 'Forbidden' These are my settings.py configs: EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" ANYMAIL = { "MAILGUN_API_KEY": os.environ.get("MAILGUN_API_KEY"), "MAILGUN_API_URL": "https://api.mailgun.net/v3", "MAILGUN_SENDER_DOMAIN": "sandboxe6301378bfe741bf99d5684e65852283.mailgun.org"), } SERVER_EMAIL = "mailgun@sandboxe6301378bfe741bf99d5684e65852283.mailgun.org" # SERVER_EMAIL = "mail@gmail.com" # DEFAULT_FROM_EMAIL = "mail@gmail.com" ADMINS = [("Admin", "mail@gmail.com"), ] I'm able to send emails w/ these configs w/ CURL. I must be missing something on Django settings. -
I am trying to sorting data in django the data is coming from different table in different dropdown but It is giving empty page
Basically I am making a search engine for car's selling company in this search engine data is coming from different models when I click the search button then blank page will open no data is showing related to dropdown empty page is opening, how can I get the perfect match I need help to solve this problem I will be very thankful to you home.html <form action="/searchdd" method="GET" id="indexForm" data-cars-url="{% url 'ajax_load_cars' %}"> {% csrf_token %} <div class="col-md-12"> <div class="row"> <div class=" col-md-3"> <label for="" class="white">Make</label> <select id="companyddl" name="companyname" class="searchengine dp-list"> <option disabled selected="true" value="">--Select Make--</option> {% for company in companies %} <option value="{{company.CompanyID}}">{{company.CompanyName}}</option> {% endfor %} </select> </div> <div class=" col-md-3"> <label for="" class="white">Model</label> <select id="carddl" name="carname" class="searchengine dp-list"> <option disabled selected="true" value="">--Select Model--</option> </select> </div> <div class="col-md-3"> <label for="" class="white">From Year</label> <select name="fromdate" id="fromdate" class="dp-list"> <option disabled selected="true" value="">--select Year--</option> {% for manf in manufac %} <option value="{{manf.ManufacturingYMID}}">{{manf.ManufacturingDate}}</option> {% endfor %} </select> </div> <div class="col-md-3"> <label for="" class="white">To Year</label> <select name="todate" id="todate" class="dp-list"> <option disabled selected="true" value="">--select Year--</option> {% for manf in manufac %} <option value="{{manf.ManufacturingYMID}}">{{manf.ManufacturingDate}}</option> {% endfor %} </select> </div> </div> </div> <div class="col-md-12"> <div class="row"> <div class="dropdown my-2 col-md-3 col-sm-12"> <label for="" class="white">Type </label> <select name="typ" … -
How to make unsupported Unicode escape sequence supported in Python?
I'm trying to create an object Listing in my django application but I get the following exception : UntranslatableCharacter: unsupported Unicode escape sequence. How can I solve this issue ? models.py class Listing(models.Model): data = JSONField(null=True, blank=True) dt = models.DateTimeField(null=True) dt_created = models.DateTimeField(auto_now=True) objects = DataFrameManager() # activate custom manager Reproductible example from requests import Request, Session from requests.exceptions import ConnectionError, Timeout, TooManyRedirects import json log.info('Retrieve listing from CMC') url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' parameters = { 'start': '1', 'limit': '5000', 'convert': 'USD' } headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': '5e2d4f14-42a9-4108-868c-6fd0bb8c6186', } session = Session() session.headers.update(headers) try: res = session.get(url, params=parameters) data = json.loads(res.text) if data['status']['error_code'] == 0: dt = timezone.now().replace(minute=0, second=0, microsecond=0) Listing.objects.create(dt=dt, data=data) <--- object creation here log.info('Retrieve listing from CMC complete') else: log.error('Error while retrieving data from CoinMarketCap') log.error("Error: {0}".format(data['status']['error_message'])) except (ConnectionError, Timeout, TooManyRedirects) as e: log.error('Error while retrieving data from CoinMarketCap') log.error("Error: {0}".format(e)) This is the traceback : --------------------------------------------------------------------------- UntranslatableCharacter Traceback (most recent call last) ~/env/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 85 else: ---> 86 return self.cursor.execute(sql, params) 87 UntranslatableCharacter: unsupported Unicode escape sequence LINE 1: ...ata_listing" ("data", "dt", "dt_created") VALUES ('{"raw": {... ^ DETAIL: Unicode escape values cannot be used for code point values above 007F when … -
How to filter only nested related django objects?
I have a model representing a room and a module. A module can have multiple rooms. Here is the get request result for my module object - { "module_id": 4, "rooms": [ { "room_id": 2, "title": "4", "desc": "22", "level": "2", "is_deleted": true, }, { "room_id": 3, "title": "3", "desc": "22", "level": "2", "is_deleted": false, } ], "title": "4", "desc": "sdsdsdss", "is_deleted": false, } Now I want the get request of modules to show all the modules and the rooms contained in each module should have is_deleted=False. In other words, I don't want room with room_id=2 to be shown in the get request. Here is my views.py file - class add_module(APIView): def get(self, request, format=None): module = Module.objects.filter(is_deleted=False, rooms__is_deleted=False) module_serializer = ModuleSerializer(module, many=True) return Response(module_serializer.data, status = status.HTTP_200_OK) Here is my serializer file for module - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(read_only=True, many=True) class Meta: model = Module fields = "__all__" -
Invoke-WebRequest : A positional parameter cannot be found that accepts argument 'Content-Type: application/json'
I am working on simple Django Project for an inventory system. While invoking a post request to my endpoint I am getting the following error in my terminal. Please help me resolve and figure out the issue. Thanks!! class ShoppingCart(View): def Post(self, request): data = json.loads(request.body.decode("utf-8")) p_name = data.get('product_name') p_price = data.get('product_price') p_quantity = data.get('product_quantity') product_data = { 'product_name': p_name, 'product_price': p_price, 'product_quantity': p_quantity, } cart_item = CartItem.objects.create(**product_data) data = { "message": f"New item added to cart with id: {cart_item.id}" } return JsonResponse(data, status=201) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('api_app.urls')), ] curl Command for Post Request curl -X POST -H "Content-Type: application/json" http://127.0.0.1:8000/cart/ -d " {\"product_name\":\"name\",\"product_price\":\"41\",\"product_quantity\":\"1\"}" Error -
Detecting import error when runserver on Django
I'm working on a project in Python 3.8.5 and Django 3.2. In the process of build and deployment, I want to send a notification by detecting an ImportError when running by manage.py runserver. For example, slack message or email. In manage.py, from django.core.management import ... execute_from_command_line(sys.argv) I twisted the import syntax of the views.py file and tried to try-except to the execute_from_command_line(), but I couldn't catch exception. The error is only appearing on the runserver console. Perhaps I think we should modify the utility.execute() within this execute_from_command_line() logic, which is a package modification, so I want to avoid this method. In utility.execute(), def execute(self): """ Given the command-line arguments, figure out which subcommand is being run, create a parser appropriate to that command, and run it. """ try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display help if no arguments were given. # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = CommandParser(usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False) parser.add_argument('--settings') parser.add_argument('--pythonpath') parser.add_argument('args', nargs='*') # catch-all try: options, args = parser.parse_known_args(self.argv[2:]) handle_default_options(options) except CommandError: pass # Ignore any option errors at this point. … -
No Order matches the given query
I am learning Django from book called Django 3 by example. I am following steps given in the book. But I am getting following error: Page not found (404) No Order matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/payment/process/ Raised by: payment.views.payment_process Using the URLconf defined in FlixKart.urls, Django tried these URL patterns, in this order: admin/ cart/ orders/ payment/ process/ [name='process'] The current path, payment/process/, matched the last one. views.py of payments app: def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) total_cost = order.get_total_cost() if request.method == 'POST': # retrieve nonce nonce = request.POST.get('payment_method_nonce', None) # create and submit transaction result = gateway.transaction.sale({ 'amount': f'{total_cost:.2f}', 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # store the unique transaction id order.braintree_id = result.transaction.id order.save() return redirect('payment:done') else: return redirect('payment:canceled') else: # generate token client_token = gateway.client_token.generate() return render(request, 'payment/process.html', {'order': order,'client_token': client_token}) url patterns from settings.py of Project: urlpatterns = [ path('admin/', admin.site.urls), path('cart/', include('cart.urls', namespace='cart')), path('orders/', include('orders.urls', namespace='orders')), path('payment/', include('payment.urls', namespace='payment')), path('', include('shop.urls', namespace='shop')), ] I have tried some solutions from stackoverflow but none worked for me. Please help me solve this error. Thank you.