Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use objects specified by a manager instead of the default objects in a class based or function view?
My code: models.py class EmployeeManager(models.Manager): def get_queryset(self): return super().get_queryset().exclude(employed=False) class NotEmployedEmployee(models.Manager): def get_queryset(self): return super().get_queryset().filter(employed=False) class Employee(models.Model): objects = EmployeeManager() not_employed = NotEmployedEmployees() name = models.CharField(max_length=250) employed = models.BooleanField(default=True, blank=True, null=True) views.py class EmployeeListView(ListView): model = Employee template_name = 'tmng/employee_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) resultset = EmployeeFilter(self.request.GET, queryset=self.get_queryset()) context['filter'] = resultset return context class EmployeeUpdateView(UpdateView): template_name = 'tmng/employee_update.html' model = Employee fields = '__all__' def form_valid(self, form): self.name = form.cleaned_data.get('name') return super().form_valid(form) def get_success_url(self): messages.success(self.request, f'Employee "{self.name}" changed!') return '/' For all my currently working employees my list and update view works fine. But I also want a list/update-view for my not-employed employees so I can 'reactivate' them ones they rejoin the company. For the list view I found a semi-solution by using a function based view. views.py def not_employed_employee_list_view(request, *args, **kwargs): template_path = 'tmng/employee_not_employed.html' context = {'employees': Employee.not_employed.all()} return render(request, template_path, context) So what I'm looking for is way to see list/update non employed employees. Is there way to say to class based / functions views to use not the default employees but the 'non_employed' employees? -
Django ORM Count Without Duplicate Column
I have a table called Reading History. I want to find the average number of reads in this table. I wrote the following method for this, but I can't get the right result. Records are made in the table once (student-book records with the same values). When the same record comes, the counter value is increased by one. For example, suppose that two different students read two different books. I expect total reads / 2 but the result I get is total reads / 4 because there are 4 rows in the table. How can I calculate this? For example, if a student reads 4 different books once, the average will be 1, but the average should be 4. I tried to use distinct and values but I couldn't get the result I wanted. Maybe I didn't manage to use it correctly. Also I tried to use Avg. When avg didn't give the correct result, I tried to break it down and get the values myself. Normally, Avg was written in Sum. Serializer class ClassReadingHistoryReportSerializer(ModelSerializer): instructor = InstructorForClassSerializer(source="instructor.user") students = StudenListReadingHistoryReportSerializer(many=True, source="student_list_class") avg_read_book = serializers.SerializerMethodField() class Meta: model = Class exclude = [ "created_at", "updated_at", "school", ] def get_avg_read_book(self, obj): … -
Importing data into a 2D array from MSSQL database
I am trying to print a trial balance through a web app. The app currently prints the description but not in a line by line format, I have had a look at the .filter function but I don't know how that would translate to MSSQL queries. If anyone one has any examples for me , that would be a great help. Views.py : def home(request): query = "SELECT Description ,Account, Debit , Credit FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" desc = "SELECT Description FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor = cnxn.cursor(); cursor.execute(desc); description = cursor.fetchall() return render(request , 'main/home.html' , {"description":description}) Home.html: {% extends "main/base.html"%} {% block content%} <h1>HOME</h1> {% for description in description %} <div class="row mb-3"> <div class="col"> <p>{{ description }}</p> </div> {% endfor %} </div> {% endblock %} Output: -
Django allauth problem with setting sessions params and getting them after login
I am using Django allauth to associate already logged in in Django users with their social accounts. For frontend I use Vue js, it sends in body pw and username. My idea was to save Django user id in session parameters after login and grab it back during the allauth flow. As far as I understood it should work: Passing a dynamic state parameter using django-allauth during social login However, by some reason when I am trying to access the session parameter in allauth flow it is empty. The id is set in session and it should be fine. Currently, it is tested on Google OAuth2. My login view: @api_view(('POST',)) def login_user(request): # get credentials from Body request_data = json.loads(request.body) print(request_data) # DEBUG username = request_data['username'] password = request_data['password'] try: # get user instance if not User.objects.filter(username=username).exists(): raise ValidationError("The user does not exist") else: if username and password: # authenticate user user = authenticate(username=username, password=password) if not user: raise ValidationError("Incorrect password or username") if not user.is_active: raise ValidationError("This user is no longer active") print(user) # DEBUG # set session cookie with user id print('SESSION UID', user.id) request.session['user_id'] = user.id # works session_uid = request.session.get('user_id', 'LOGIN NO SESSION UID') # get … -
how to edit, delete row data in one page using django table
I am using Django and I am outputting data to a Table . Modification and deletion of each row implemented the function by passing the argument as the url parameter of the detail page of each row. I want to edit and edit the table itself, which outputs the entire row without going into the detail page. (The detail page is redirected by the table-link function implemented when each row is clicked.) <table id="waitinglist-list-table"> <thead> <tr> <th>name</th> <th>age</th> <th>weight</th> <th>register_date</th> <th>Edit</th> <th>Remove</th> </tr> </thead> <tbody> {% for register in register_list %} <tr class="tr-hover table-link" data-link="/register/detail/{{ register.id}}/"> <td>{{ register.name}}</td> <td>{{ register.age }}</td> <td>{{ register.weight}}</td> <td>{{ register.register_date }}</td> <td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#edit_register">Edit </button> </td> <td> <button data-toggle="modal" data-target="#remove_register" type="button" id="register-remove-button" register-id="{{ register.id }}" class="btn btn-inverse-danger">Remove </button> </td> </tr> {% endfor %} </tbody> </table> In the past, when editing and deleting, the id was requested in the url parameter. def edit_register(request, id): register = Register.objects.get(pk=id) edited_register, errors = Register.register_form_validation(request) if errors: return JsonResponse({'code': 'error', 'error': errors}) register.name = edited_register.name register.age = edited_register.age register.weight = edited_register.weight register.register_date = edited_register.register_date register.save() return JsonResponse({'code': 'success'}) def delete_register(request, id): register= Register.objects.get(pk=id) register.is_deleted = True register.save() return HttpResponseRedirect(f'/register/') Do you need a way to receive … -
modal opening only for the first for loop element?
I have my for loop in django such as its only opening the modal for the first element and nothing happens for other elements? : This is my html file it display all elements in a table with delete button. When clicking delete button a modal is opened but it is opened for the first element only? what should i change in this? <table> {% for card in cards %} <tr class="record"> <td>{{card.number}}</td> <td> <button class="hover:bg-gray-500 duration-500" id="delete-btn" > </button> <div class=" fixed flex justify-center items-center hidden " aria-labelledby="modal-title" aria-modal="true" id="overlay" > ............. #some lines of code <div class=" bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse " > <a href="{% url 'p:delete-card' card.id %}" id="delbutton" > <button type="button" class=" w-full inline-flex justify-center " > Delete </button> </a> </div> </div> </div> </td> </tr> {% endfor %} my js to open the modal on button click: window.addEventListener('DOMContentLoaded',() =>{ const overlay = document.querySelector('#overlay') const delbtn = document.querySelector('#delete-btn') const toggleModal = () => { overlay.classList.toggle('hidden') overlay.classList.add('flex') } delbtn.addEventListener('click',toggleModal) }) call url on clicking delete button: $(document).on("click","#delbutton" ,function(e){ e.preventDefault(); var $this = $(this); $.ajax({ url: $this.attr("href"), type: "GET", dataType: "json", success: function(resp){ $this.parents(".record").fadeOut("fast", function(){ $this.parents(".record").remove(); window.location.reload(); }); } }); return false; }); -
How do I get the orignal name of the file that is uploaded in the filefield in django
I want to access the name of the file uploaded to models.FileField() in my class. Here is my class class extract(models.Model): doc = models.FileField(upload_to='files/') Is there a function or some method, to access the original name of the uploaded file, without modifying the name during upload. like something like this name = doc.filename() -
Django urls points wrong path
I'm writing a production machines management application and I've encountered a strange problem that I can't solve. Previously, I had a "Transactions" subpage with paths under the description with the same name. Everything was working very well. Today I tried to add another sub-page, "Transactions per person" and the problem starts. # Transaction path('transaction/machines', views.transaction_machines_list_view, name="transaction_machines_list"), path('transaction/machine/<int:id>', views.transaction_list_view, name="transaction_list"), # Transaction per-Capita path('per_capita/employees', views.transaction_per_capita_employees_list_view, name="transaction_per_capita_employees_list"), path('per_capita/employee/<int:id>', views.transaction_per_capita_list_view, name="transaction_per_capita_list"), All "transaction" paths works well, per_capita/employees works well too but when I try to reach the last one, for example http://127.0.0.1:8000/per_capita/employee/2 I encounter the following error NoReverseMatch at /per_capita/employee/2 Reverse for 'transaction_list' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['transaction/machine/(?P<id>[0-9]+)$'] Why is my path named transaction_per_capita_list received as transaction_list by Django? The redirect itself is a row in the table and looks like this: <tr class="pointer" onclick="location.href='{% url 'transaction_per_capita_list' id=employee.id %}';"> <td class="cell">{{ employee.username }}</td> <td class="cell">{{ employee.first_name }}</td> <td class="cell">{{ employee.last_name }}</td> </tr> I've tried changing the path, I've tried renaming it and it doesn't do anything. What am I doing wrong? -
Django - Extract hash tags from a post and save them all in a many-to-one relation
So I have this code below that when a user submits a post it extracts all the hash tags from it then creates a new entry in the hash tag table and also creates a new reference in the HashTagsInPost table so people can search posts by hash tags. My primary concerns lay in the Views.py file. Problems: I don't think it's good to iterate over the list of hash tags pulled out and doing a .get() call to see if exists then if it doesn't create it. There should be a better way to do this. Since HashTagsInPost is a one-to-many relation, I don't really know how to store that lists of Hash Tags as the hash_tag attribute in the HashTagsInPost attribute. Do I just pass a list of HashTag objects? Views.py def post(self, request): serializer = PostSerializer(data=request.data) if serializer.is_valid(): post_body = request.data['body'] post_obj = serializer.save() hash_tags_list = extract_hashtags(post_body) for ht in hash_tags_list: try: ht_obj = HashTags.objects.get(pk=ht) except HashTags.DoesNotExist: ht_obj = HashTags.objects.create(hash_tag=ht) HashTagsInPost.objects.create(hash_tag=ht_obj, post_id=) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Models.py class HashTags(models.Model): hash_tag = models.CharField(max_length=140, primary_key=True) class Post(AbstractBaseModel): creator_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post_creator_id", db_index=True) goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE, db_index=True) body = models.CharField(max_length=511) class HashTagsInPost(AbstractBaseModel): hash_tag = models.ForeignKey(HashTags, … -
How to manually customize parameters of DRF views using drf-yasg Swagger?
I am using drf-yasg package to integrate Swagger with DRF. As documentation said I used @swagger_auto_schema decorator to manually customize auto-generated endpoints. After a lot of tries I still can't figure out why there are no any changes. So, I tried to add extra query parameter to RetrieveUpdateAPIView: class MyCustomView(RetrieveUpdateAPIView): ... @swagger_auto_schema( manual_parameters=[openapi.Parameter('test', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_BOOLEAN)] ) def retrieve(self, request, *args, **kwargs): ... After all, nothing seems changed. What exactly I have to do then? -
How to find the right "gas" value in order to send a transaction on Ropsten testnet?
I'm a newby in the Web3/Ethereum world and I'm trying to build an app that can simply write a block onto the Ropsten testnet through Infuria. Unfortunately the following code seems not to work from web3 import Web3 def sendTransaction(message): w3 = Web3( Web3.HTTPProvider( "https://ropsten.infura.io/v3/my_project_id" ) ) address = "https://ropsten.infura.io/v3/my_project_id" privateKey = "my_private_key" nonce = w3.eth.getTransactionCount(address) gasPrice = w3.eth.gas_price value = w3.toWei(1, "ether") signedTx = w3.eth.account.sign_transaction( dict( nonce=nonce, gasPrice=gasPrice, gas=1000000000, to="0x0000000000000000000000000000000000000000", value=value, data=message.encode("UTF-8"), ), privateKey, ) tx = w3.eth.sendRawTransaction(signedTx.rawTransaction) txId = w3.toHex(tx) return txId In particular the field gas seems to create problems. If I add too much zeroes, I'll get the error message 'exceeds block gas limit', whereas with less zeroes the error message becomes 'insufficient funds for gas * price + value'. -
Do you need a csrf token for a get request in Django templates?
Do you need a csrf token for a get request in Django? I know that you need one for a post request like the template below: <form method="post" class="mt-5"> {% csrf_token %} {{ form|crispy }} <button type='submit' class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md"> Update </button> </form> However, I don't know if I need one for a get request like below: <form method="GET" action="."> <div class="form-row"> <div class="form-group col-12"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="title_contains" placeholder="Title contains..." /> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> </div> <button type="submit" class="btn btn-primary">Search</button> </form> I don't want my get request being vulnerbale to attackers, but I don't know if it is okay to add a csrf_token like the one for post request. If you have any questions, please ask me in the comments. Thank you. -
How can i update a specific field using foreign key relationship
I want to update a field which is called level. My relation is like this. i am using django User model. Which is extended to Extended user like this below:- class ExtendedUser(models.Model): levels_fields = ( ("NEW SELLER", "NEW SELLER"), ("LEVEL1", "LEVEL1"), ("LEVEL 2", "LEVEL 2"), ("LEVEL 3", "LEVEL 3") ) user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(null=True, unique=True) contact_no = models.CharField(max_length=15, null=True) profile_picture = models.ImageField(upload_to="images/", null=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True) level = models.CharField(max_length = 120, null=True, blank=True, choices=levels_fields, default="NEW SELLER") I have a field call "Level" which is full of choices. Now i have a model named Checkout This is the checkout model :- class Checkout(models.Model): ORDER_CHOICES = ( ("ACTIVE", "ACTIVE"), ("LATE", "LATE"), ("DELIVERED", "DELIVERED"), ("CANCELLED", "CANCELLED"), ) user = models.ForeignKey(User, on_delete=models.CASCADE) seller = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name='seller') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) package = models.ForeignKey(OfferManager, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=0) price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) total = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) grand_total = models.DecimalField( decimal_places=2, max_digits=10, default=0.00, null=True) paid = models.BooleanField(default=False) due_date = models.DateField(null=True) order_status = models.CharField(max_length=200, choices=ORDER_CHOICES, default="ACTIVE") is_complete = models.BooleanField(default=False, null=True) I have another model which is called SellerSubmit and the checkout is the foreign … -
Really need help for this django formset
To all the pros out there, i really need help with this. 2 days ago my code work. Now its haywire. This line '$('#id_form-TOTAL_FORMS').attr('value', (parseInt (totalForms))-1);' is the issue. 2 days ago, without this line, everything works. The button to control the number of formset and its saved the number of data accordingly. But now without the same line, it cannot even control the counting properly. And to make it worst, it delete the last row of data whenever i saved. Here's what happen in detail: Upon loading the page, user can clone up to additional 3 formsets to key in data. So with the original one. Theres 4 rows in total. If user clicks save, all 4 rows get saved properly. If user never click save but instead click the '-' button on one of the row to remove the one of the row. It becomes 2 additional formsets and the original remaining. Total 3 rows of data. But if at this time user clicks save, it somehow delete one more additional formsets due to the line $('#id_form-TOTAL_FORMS').attr('value', (parseInt (totalForms))-1); But this morning, without using this line everything works perfectly let changeFlag=0; let maxrow = $('#id_form-MAX_NUM_FORMS').attr('value'); let totalForms = … -
How to implement filter and basic authentication in django rest framework?
In my project I use django rest framework. To filter the results I use django_filters backend. There is my code: models.py class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') def __str__(self): return self.robot class assignParameter(models.Model): parameterName = models.CharField(max_length=100, blank=True) assignRobot= models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='param', blank=True, null=True) class jenkinsHistory(models.Model): jenkinsJobName = models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='JenkinJobName', blank=True, null=True) jenkinsBuildNumber = models.CharField(max_length=100,blank=True) jenkinsBuildStatus = models.CharField(max_length=200,blank=True) errorMsg = models.CharField(max_length=500,blank=True) Param = models.CharField(max_length=500,blank=True, null=True) Serializers.py from hello.models import Robot,assignParameter,jenkinsHistory from rest_framework import serializers class assignParameterSerializer(serializers.ModelSerializer): class Meta: model = assignParameter fields = ['id', 'parameterName', 'assignRobot'] class jenkinsHistorySerializer(serializers.ModelSerializer): jenkinsJobName = serializers.SlugRelatedField(read_only=True, slug_field='robot') class Meta: model = jenkinsHistory # list_serializer_class = FilteredAssessmentsSerializer fields = ['id','jenkinsJobName','jenkinsBuildNumber','jenkinsBuildStatus','errorMsg','Param'] class RobotSerializer(serializers.ModelSerializer): param = assignParameterSerializer(many=True, read_only=True) # JenkinJobName = jenkinsHistorySerializer(many=True, read_only=True) class Meta: model = Robot fields = ['id', 'robot', 'short_Description', 'status', 'parameter', 'jenkins_job', 'jenkins_token', 'param'] and here's my view.py: from requests import api from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.filters import SearchFilter from django_filters.rest_framework import DjangoFilterBackend from django_filters import rest_framework as filters from hello.models import Robot,jenkinsHistory from hello.api.serializers import RobotSerializer, jenkinsHistorySerializer @api_view(["GET", "POST"]) def robot_list_api_view(request): if request.method == "GET": rb = Robot.objects.all() … -
django views.py IP recorder append not working
In my https://fr0gs.pythonanywhere.com site, I've created an IP address recorder to record the IP addresses of people coming into the site. But the log file is blank! from django.shortcuts import render from datetime import datetime # Create your views here. from django.http import HttpResponse def get_ip_address(request): """ use requestobject to fetch client machine's IP Address """ x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') ### Real IP address of client Machine return ip def homePageView(request): try: alip = open('alip.txt', 'a') alip.write(f'''{datetime.now()} : {get_ip_address(request)} ''') alip.close() except: alip.close() return HttpResponse(f'''{get_ip_address(request)} : {datetime.now()} Hello, World!''') -
how to take input field from django auth login form for javascript validation
Can I Create a custom user signup form with my own custom fields and do performing signup and signin without taking UserCreationForm? Plz. suggest me -
how to concatenation django query set with And & OR operator
This is my concatenation code but its not working ,how to concatenation django queryset with AND & OR operator enter code here sales_by_branch = OrderItems.objects.values('order__entity__id').order_by('order__entity__id').annotate(total_amount=Sum('total_price')).filter(order__is_approved=True).filter(order__is_success=True) v=0 subset=[] for product_id in product_id: product_id = int(product_id) product_code = ProductCodes.objects.values('flavour_id','product_id','quantity_id').filter(id=product_id) if product_code: for item in product_code: flavour_id =item['flavour_id'] product_id =item['product_id'] quantity_id =item['quantity_id'] if v==0: sales_by_branch = sales_by_branch.filter(flavour_id=flavour_id,product_id=product_id,quantity_id=quantity_id) else: subset = OrderItems.objects.filter(flavour_id=flavour_id,product_id=product_id,quantity_id=quantity_id) ales_by_branch = sales_by_branch | subset v=v+1 -
Wagtail - adding CSS class or placeholder to form builder fields
I'm trying to add css classes (for column width) and placeholder text to my Wagtail form fields via the Wagtail admin form builder. I've tried using wagtail.contrib.forms and also the wagtailstreamforms package to no avail. I know it says here that the Wagtail forms aren't a replacement for Django forms. However, without such basic functionality it's limited in its usefulness. -
DoesNotExist at /cart/ OrderStatus matching query does not exist
[Screenshot of the webpage showing error][1] It is showing that the urls path is not correct despite all the corrections made in the code. [1]: https://i.stack.imgur.com/sAoyV.png`from django.contrib import admin from django.urls import path from django.conf.urls import url, include from .import views from django.contrib.auth import views as auth_views from django.views.generic import RedirectView urlpatterns = [ url(r"^admin/admin_update_quantities/$", views.adminUploadQuantities, name="adminUploadQuantities"), url(r"^accounts?/login/$", views.LoginView.as_view(), name="account_login"), url(r"^accounts?/signup/$", views.SignupView.as_view(), name="account_signup"), url(r"^accounts?/password_change", auth_views.PasswordChangeView.as_view( template_name='account/password_change.html'), name="password_change"), url(r"^password_change_done", auth_views.PasswordChangeView.as_view( template_name='account/password_change_done.html'), name="password_change_done"), url(r"^accounts?/", include("account.urls")), url(r'^$', views.itemList, name='itemlist'), url(r'^getitems$', views.getItems, name='getItems'), url(r'^getitemarray$', views.getItemArray, name='getItemArray'), url(r'^addtocart$', views.addToCart, name='addToCart'), url(r'^setincart$', views.setInCart, name='setInCart'), url(r'^getitemprices$', views.getItemPrices, name='getItemPrices'), url(r'^getcartsum$', views.getCartSum, name='getCartSum'), url(r'^getcart$', views.getCart, name='getCart'), url(r'^getinvoicepdf$', views.getInvoicePdf, name='getInvoicePdf'), url(r'^invoice/$', views.getInvoicePdf, name='getInvoicePdf'), url(r'^getinvoice', views.getInvoice, name='getInvoice'), url(r'^getdelivery', views.getDelivery, name='getDelivery'), url(r'^gettotal', views.getTotal, name='getTotal'), url(r'^getminordersum', views.getMinOrderSum, name='getMinOrderSum'), url(r'^endoforder/', views.endOfOrder, name='endOfOrder'), url(r'^myorders/', views.orderList, name='orderList'), url(r'^cart/$', views.cart, name='cart'), url(r'^item/(?P<itemSlug>\w+)', views.itemPage, name='item'), url(r'^itemlist/$', views.itemList, name='itemlist'), url(r'^itemlist/(?P<cls>\w+)', views.itemListSelection, name='itemlistselection'), url(r'^login/$', RedirectView.as_view(pattern_name='account/login')), url(r'^order/$', views.makeOrder, name='order'), url(r'^about/$', views.about, name='about') ] ` -
Page not found (404) The current path, firstapp/about/, didn’t match any of these
Sorry if there is any problem with my language my English is very bad when i goto http://127.0.0.1:8000/firstapp/about/ page showing this error enter image description here This is my code views.py from django.shortcuts import render from django.http import HttpResponse from . models import * def home(request): student = Student.objects.all() return render(request, 'index.html',{'student':student}) def about(request): student = Student.objects.all() return render(request, 'demo.html',{'student':student}) def service(request): return HttpResponse("<h3>hai this is service page</h3>") firstapp/urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='next'), path('about/', views.about, name='about'), path('service/', views.service, name='service'), ] urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('firstapp', include('firstapp.urls')), ] what am missing or whats the error -
Model instances are not rendering into template
Orders and OrderItems are successfully added to the table, but the products are not being shown to the template. If i use print(order_item.objects.all()) , it gives an error saying : AttributeError: Manager isn't accessible via OrderItem instances. In django-admin database, the products are being nicely added and removed from the cart. Currently, these are my order items: Order item 3 of Saregama Carvaan Earphones GX01 with Mic 5 of JBL Flip 5 3 of Puma Unisex-Adult BMW MMS R-cat Mid Sneaker 4 of Adidas Men's Astound M Running Shoe 4 order items These order items are from admin user. html: {% block content %} <main> <div class="container"> <div class="table-responsive text-nowrap"> <h2>Order Summary</h2> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Item title</th> <th scope="col">Price(₹)</th> <th scope="col">Quantity</th> <th scope="col">Total Item Price</th> </tr> </thead> <tbody> {% for order_item in order.items.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ order_item.item.product_title }}</td> <td>₹{{ order_item.item.sale_price }}</td> <td> <a href="{% url 'remove-single-item-from-cart' order_item.item.slug %}"><i class="fas fa-minus mr-2"></i></a> {{ order_item.quantity }} <a href="{% url 'add-to-cart' order_item.item.slug %}"><i class="fas fa-plus ml-2"></i></a> </td> <td> {% if order_item.item.discount %} ₹{{ order_item.get_total_discount_item_price }} <span class="badge badge-primary">Saving ₹{{ order_item.get_amount_saved }}</span> {% else %} ₹{{ order_item.get_total_item_price }} {% endif %} <a style='color: red;' href="{% url … -
Display MultipleChoiceField in template of django
I have a charField with MultipleChoiceField formfield ! And its perfectly opens a dropdown by which we go do multiple select options. And the problem is that it stores the value as array like ['option1','option2'] When i display this on template, it display the whole array but i want to get the option1 and option2 and display horizontally like option1, option2 ! How to do this ? My code : class Univ(models.Model): education_level = models.CharField(max_length=20) & in form: class Univform(ModelForm): education_level = forms.MultipleChoiceField(choices=EDU_LEVEL) How to deal this and display ? -
Which back-end language I should choose PHP or nodeJS for API creation and for back-end solutions
I am a mobile application developer and I want to learn any back end language for the creation of API. I am in doubt, which language I should learn ? Please give your reviews and suggestions because I am in confusion. -
how to handle message in on_message mqtt paho if multiple message came at same time
return_message = "" def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe(topic) def on_message(client, userdata, message): global return_message print("received data is :") return_message = message.payload client = mqtt.Client("user") client.on_connect=on_connect client.on_message=on_message client.connect(broker,port,60) client.loop_start() the return_message is a global variable. getting the message when there is only one message at a time. but i need to handle multiple messages at a time. how to handle this. if i declared return_message as an array then also i think there will be data loss . is there any better way to do this. i need to pass the return message value to other files also. how to do this