Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DoesNotExist at /delete/4/ Employee matching query does not exist
When I'm deleting from the Patient table I'm getting this error: DoesNotExist at /delete/4/ Employee matching query does not exist. views.py def delete_emp(request, pk): if request.method == 'POST': pi = Employee.objects.get(id=pk) pi.delete() return redirect('/employee') def delete_pat(request, pk): if request.method == 'POST': pi = Patient.objects.get(id=pk) pi.delete() return redirect('/patient') this is html page: <td> <form action="{% url 'home:delete_pat' p.id %}" method="post"> {% csrf_token %} <input type="submit" class="btn btn-primary btn-sm" value="Delete"> </form> </td> models.py class Patient(models.Model): name = models.CharField(max_length=200) phone=models.CharField(max_length=17,default='') age=models.IntegerField(default='') gender = models.CharField(max_length=20) doctor_name = models.CharField(max_length=200) def __str__(self): return self.name urls.py path('delete/<int:pk>/', views.delete_pat, name='delete_pat'), Please, can any one help me to get out from this, any help would be greatly appreciated. -
Django-Heroku app not saving data on JawsDB mysql (Long polling)
so I created a django project to imitate an asynchronous data stream using ajax and long polling. Everything works fine on the local server however it doesn't after I deployed it on heroku. There is still buttons to control LED (IoT) however there's no readings. The error said failed to load resource which i believed that it has smtg to do with database connection. I'm not using sqlite3, in fact i'm using mysql. I know that it's not possible to call a local database on heroku app so I'm using the jawsdb mysql add ons and i configured my settings.py according to the user, password and also host. I am able to connect to it using xampp however I can't see it auto saving data which it should be doing whenever my esp32 send a data to it. Would be great if someone could provide me some answers. I have a thoughts that could be the issue. The initial postgresql is the main database? I added the add ons and configured it on my django settings.py and pushed on heroku. However I'm not sure do i need to use heroku to sort of like set the mysql as my main … -
how can I pass the id of the item selected from the dropdown in django form action url?
Problem In this I want to pass the id from the transactions items from the dropdown to the form action URL cart_add. From the value selected in the dropdown, I have taken the id but now I don't know how to pass that id to the script and then to the form of adding to the cart. If someone knows please help. {% block main-content %} <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <script> $(document).on("change", '.Price', function (event) { event.preventDefault(); $('#id_price').text($(this).children(":selected").attr("price")); $('#id_sale_price').text($(this).children(":selected").attr("sale_price")); $('#transactionIDValue').val($(this).children(":selected").attr("transID")); }); </script> <div class="container my-5"> <div class="row"> <div class="col-sm-6 text-center align-self-center"> <img src={{product.product_image.url}} alt="" class="img-fluid img-thumbnail"> <span class="status">{{product.discount_percentage}} %</span> <div class="overlay"></div> </div> <div class="col-sm-5 offset-sm-1"> <h2>Product Title: {{product.name}}</h2> <hr> <p>Description: {{product.description}}</p> <br> <div class="d-flex"> <div class="pricing"> <p class="price"><span class="mr-2 price-dc" id='id_price'>Rs. </span><span class="price-sale" id='id_sale_price'>Rs. </span></p> </div> </div> <h4> <select class="Price" style="width: 250px;"> <option value="none" selected disabled hidden> Select an Option </option> {% for item in transaction %} <option transID={{item.id}} price={{item.Price}} sale_price={{item.get_sale}} >{{item.AUID.unit}} - {{item.Description}}</option> {% endfor %} </select> <!-- <small class="fw-light text-decoration-line-through">Rs. {{product.selling_price}} </small> --> </h4> <br> <form id='transactionIDValue' action="{% url 'cart:cart_add' %}" class="d-inline" method="post"> {{cart_product_form}} {% csrf_token %} <input type="submit" class="btn btn-primary shadow px-5 py-2" value="Add To Cart"> <!-- <button type="submit" class="btn btn-primary shadow px-5 py-2">Add to Cart</button> --> </form> <!-- … -
Django 500 Error page doesn't load CSS file
The 500 error handler template won't load CSS even if typed everything correctly. For example, my home template loads CSS properly using the same method Here's the 500.html template <html> <head> {%load static%} <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>500</title> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"/> </head> <body> html code here </body> </html> This should load the style.css file from the static folder <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"/> In the terminal it looks like everything is OK, but it still doesn't load. "GET /static/style.css HTTP/1.1" 200 734 if I try to access 127.0.0.1:8000/static/main.css (the one for the homepage) it shows it how it should if I try to access 127.0.0.1:8000/static/style.css it gives me an error I don't know if it matters but I'm doing this with DEBUG = False -
Django does not let me pass empty fields
In my forms I have a table with the following columns: type = models.CharField(max_length=11, blank=False, null=False) name = models.CharField(max_length=50, blank=False, null=False) profile_image = models.ImageField(max_length=100, blank=True, null=True) terms = models.CharField(max_length=1000, blank=True, null=True) bio = models.CharField(max_length=1000, blank=True, null=True) but when I don't enter anything for bio, it gives me an error message with "[23000][1048] Column 'bio' cannot be null". Why is this? -
Force Download existing JSON file instead of displaying it with Django
My webpage has a functionality that lets users request fairly large json files (3MB+) to be generated. The generation process takes some time and I send them an email with a download link once it is ready. My problem is that clicking the download URL will open the content of the json file in the browser instead of starting a download dialog. I have found this question: Serving .json file to download but the solution reserialize the json file into the response: mixed_query = list(invoices) + list(pcustomers) json_str = serializers.serialize('json', mixed_query)) response = HttpResponse(json_str, content_type='application/json') response['Content-Disposition'] = 'attachment; filename=export.json' As the JSON file already exists, I do not want to rewrite it entirely within the response. I just want users to download the already generated file. How can I force the URL to start a download when reached? I am using Django 3.1, with Python 3.6 -
How to create custom session variable in Django 3.2?
I want create custom partner login on my website use only mobile phone number. Need your help friends. What is best practice in this question? -
Could not resolve URL for hyperlinked relationship using view name "user-detail"
I'm new to Django and trying to add to my User Authentication fields with a profile model. I'm using a HyperlinkedModelSerializer but when I go to my url - localhost:8000/api/user/, I get this error: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) hello = models.CharField(max_length=50, blank=True) def __str__(self): return self.user serializers.py from rest_framework import serializers from django.contrib.auth.models import User from .models import Profile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') extra_kwargs = {'rooms': {'required': False}} class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ['hello', 'user', 'user_id'] views.py from rest_framework import generics, viewsets from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer, ProfileSerializer from .models import Profile class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class UserProfileAPI(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer urls.py (Project) from django.contrib import admin from django.urls import path, … -
Fields required although sent in the payload in Djnago Rest framework
I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. But I got the following error. Although I am sending all the required data. I have a made a custom parser, but cant extract all the data. The data is sent like this My custom parser looks like this. class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # for case1 with nested serializers # parse each field with json for key, value in result.data.items(): if type(value) != str: data[key] = value continue if '{' in value or "[" in value: try: data[key] = json.loads(value) except ValueError: data[key] = value else: data[key] = value return parsers.DataAndFiles(data, result.files) Seems like the parser is not able to excract brand & collection id from the data, because there is a '' inside the id. Now I have to remove '' , and exctract only id.How to do this?? My view: class ProductAddAPIView(APIView): permission_classes = [IsAuthenticated] parser_classes = [MultipartJsonParser, JSONParser] def post(self,request,*args,**kwargs): data = request.data # print(data) serializer = AddProductSerializer(data=data) # print(serializer) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors) -
How to set up the random map Id generated by Folium Python
I am using folium to create a map and it generated me an html page. Inside this html I found a div with an id="map_6d1d4987e27f4fa1a16bc19423d0cdbe". The problem is the id is changing everytime the page is refreshed. <body> <div class="folium-map" id="map_6d1d4987e27f4fa1a16bc19423d0cdbe" ></div> <script type="text/javascript" src="scripts.js"></script> </body> How can I fixe it inside may python code? def create_map(): m = folium.Map(location=[9.934739, -84.087502], zoom_start=7 ) ..... -
unresolved import "home". How do I fix this? The views file and the urls file are int the same "home" folder
enter image description here unresolved import "home". How do I fix this? The views file and the urls file are int the same "home" folder. enter image description here -
Django templates - pass data outside for loop
I have a table of users and one table data is a button that opens up a modal, I am including the modal in the tamplate with the include tag. How do I pass the user from the row in which the button was clicked to the include tag? {% for user in users %} <tr> <td> <button class="btn btn-lg device-select-button"> <span>Select Device</span> </button> </td> </tr> {% endfor %} {% include 'app/admin/users/device_select_modal.html' user={{add here user}} %} In other implementation I have generated a modal for each row, and it works but slow, So I want to reimplement that -
forms validationerror sends me to a ValidationerError page
Ive been struggling with this problem for days now. As you se the validation error works but i want the error to show in the form and not redirect the user to the ValidationError page. What am i missing? I use django Alluth def custom_signup(self, request, user): user.profile.pid = self.cleaned_data[_("pid")] data = User.objects.filter(profile__pid=user.profile.pid) if data.exists(): raise forms.ValidationError( _('This user exists in our system. Please try another.'), code='unique_pid' ) else: user.save() return user -
How to call a child of CreateView multiple times within another view
I am trying to write a view that receives an Excel file from an HTML form and then inserts the values into the database. I am already having a CreateView and I want to call it multiple times to insert the Excel file contents into the database. Here is my code: class AView(TemplateView): template_name = '/path/to/template/upload.html' def post(self, request): file = request.FILES['file'] wb = load_workbook(file) for ws in wb.worksheets: for value_1, value_2 in zip(worksheet['A'], worksheet['B']): value_1 = value_1.value value_2 = value_2.value The part of reading the excel file is correct, and I am not asking about it. My question is how to call my CreateView multiple times for each iteration. Is it possible? -
django model creates extra table for same relation
I am having an issue with django model that creates multiple tables for same class, it creates two table, it should create 3 table i.e users, groups, and user_groups but I having an extra table with name users_groups(note: an extra 's'). Seems an issue with verbose_name, db_meta or related_name Full Code: from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser, BaseUserManager from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" pass class CustomUser(AbstractUser): """Model representing a User with some extended fields and email as username field""" username = None email = models.EmailField(max_length=100, unique=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: ordering = ['email'] db_table = 'users' objects = UserManager() def __str__(self): """String for representing the Model object.""" return self.email class Group(models.Model): """Model representing a Group""" name = models.CharField(max_length=200) members = models.ManyToManyField(settings.AUTH_USER_MODEL, through='UserGroup', related_name='user_groups') class Meta: ordering = ['name'] db_table = 'groups' def __str__(self): return self.name class UserGroup(models.Model): """Model representing a User's Group""" group = models.ForeignKey(Group, on_delete=models.CASCADE, verbose_name = 'group') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name = 'user') class Meta: db_table = 'user_groups' -
I have deleted a table from models but django still looking for it
I have deleted a model name controlapproval from my database by commenting the model and Running python manage.py makemigrations but when i try to migrate by using python manage.py migrate It throws an error as below Any help or guidance will be a great help -
I am new at Django and kept being stuck at the ERROR 404 (Page Not Found)
Using the URLconf defined in firstProject.urls, Django tried these URL patterns, in this order: index/ [name='main-view'] admin/ The empty path didn’t match any of these. from django.contrib import admin from django.urls import include,path from firstApp import views urlpatterns = [ path('index/',views.index, name = 'main-view'), path('admin/', admin.site.urls), ] -
Heroku Postgres Database is not working in my Django project
I created a Django project and tried to deploy it on Heroku and was working at first. But after adding another model in my models.py this new model does not show up on the admin-side on the heroku deploy but it works locally (when I run python manage.py runserver) I am using Heroku Postgres for the database on Heroku. I also already ran heroku run python manage.py makemigrations and heroku run python manage.py migrate , and I reseted the database completely, but still only two of the three models are showing up on the admin-side. -
Rendering a pivottable in Django
I am trying to render a pivottable which I made using django_pivot. The table has loan grade (A, B, C, D, E, F) as rows, term as columns (amount of months) and sum of loan amount as values. views.py: from django_pivot.pivot import pivot from django.db.models import Sum def data(requests): pivot_table = pivot(loan, 'grade', 'term', 'amount', aggregation=Sum) print(pivot_table) context = { "pivot_table": pivot_table, } return render(requests, 'dashboard/data.html', context=context) models.py: class loan(models.Model): loanid = models.CharField(max_length = 200, null=True) amount = models.IntegerField(null=True) term = models.IntegerField(null=True) interest = models.FloatField(null=True) borrower = models.CharField(max_length=200, null=True) grade = models.CharField(max_length = 200, null=True) status = models.CharField(max_length = 200, null=True) def __str__(self): return self.loanid I am stuck on how to render this table in HTML. For my "normal" table I am using the normal jinja django way to render a table like this (please forgive me for messy indentation): <div class="col-sm-8 grid-margin stretch-card"> <div class="card table-card" style="width: 105%"> <table id="MyTable" class="table table-striped table-bordered mydatatable"> <thead> <tr> <th scope="col-sm">name</th> <th scope="col-sm">email</th> <th scope="col-sm">gender</th> <th scope="col-sm">income</th> <th scope="col-sm">yearsworked</th> <th scope="col-sm">ficoscore</th> <th scope="col-sm">dti</th> </tr> </thead> {% for i in borrower_data %} <tr> <td>{{ i.name }}</td> <td>{{ i.email }}</td> <td>{{ i.gender }}</td> <td>{{ i.income }}</td> <td>{{ i.yearsworked }}</td> <td>{{ i.ficoscore }}</td> <td>{{ i.dti … -
How to Display SubCategory Products in Django?
I have a relation between category, subcategory, and sub child category, and product is related to sub child category, but I want to display the list of subcategory products. Please let me know how I can do it. here is my models.py file... class Category(models.Model): cat_name=models.CharField(max_length=225) cat_slug=models.SlugField(max_length=225, unique=True) class SubCategory(models.Model): subcat_name=models.CharField(max_length=225) subcat_slug=models.SlugField(max_length=225, unique=True) category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True) class SubChildCategory(models.Model): subcategory=models.ForeignKey(SubCategory, related_name='SubChildRelated', on_delete=models.CASCADE, default=None, verbose_name='Sub Category') name=models.CharField(max_length=50, default=None) slug=models.SlugField(unique=True, max_length=50) here is my product models.py file... class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ManyToManyField(SubChildCategory, related_name='pro_subchild', verbose_name='Select Category') here is my views.py file, where I am trying to display the SubCategory product... def home(request): subcat_product = Product.objects.prefetch_related('subcategory') return render(request, 'frontend/index.html',{'subcat_product':subcat_product} but the above function is displaying all the products which are available in SubChildCategory, I want to display products according to the SubCategory on my homepage. Please let me know what is the process to display these products. -
Django MPTT Model REST API not refreshing without server restart
I'm having some strange issue withe the MPTT model. the changes to the MPTT instances does not reflect on the rest apis unless the apache server is restarted. models.py class Category(MPTTModel): title = models.CharField(max_length=50, unique=True) slug = models.CharField(max_length=250, blank=True,null=True) type = models.CharField(max_length=250, default="grocery") parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['title'] def __str__(self): return self.title def parent_name(self): if(self.parent): return self.parent.title else: return None serializer.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'id', 'title', 'slug', 'type', 'icon', 'parent', 'parent_name', 'children', ] def get_fields(self): fields = super().get_fields() fields['children'] = CategorySerializer(many=True) return fields Views.py class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.filter(parent__isnull=True) serializer_class = CategorySerializer def get_queryset(self): queryset = self.queryset query_set =queryset return query_set the api shows updated data when i restart the server only. please help -
Django. "python manage.py runserver <my-ip>:<port>" getting "resource (<my-ip>) is online but isn't responding to connection attempts." on chrome
I am new to Django and am trying to run the server using python manage.py runserver <my-ip>:<port> command. This starts the development server but when I try to open the server link in chrome it takes too long to open and shows the error for the same. When I ran the troubleshooter, I got the following response resource (<my-ip>) is online but isn't responding to connection attempts I have tried the following: ALLOWED_HOSTS = ['*'] changing port to 80, 8080, 8000, etc. removing adblockers restarting everything disabling firewall -
Need to know where is the problem with bulk import and how to fix it
I'm building an app with Django and I need to import data using django-import-export. I'm using the bulk import of this last package. I can import the data the first time, but when I try to import it the second time an error occurred. The expected behavior is to not import data and don't cause an error. My view looks something like this(I simplified the code below since in the actual view I have four resources and four files to import) def complete_import(request): if request.method == 'POST': offering_resource = OfferingResource() issuer_resource = IssuerResource() offering_dataset = Dataset() issuer_dataset = Dataset() offering = request.FILES['offering'] issuer = request.FILES['issuer'] offering_data = offering_dataset.load(offering.read().decode('utf-8'), format='csv', delimiter='\t', headers=True) issuer_data = issuer_dataset.load(issuer.read().decode('utf-8'), format='csv', delimiter='\t', headers=True) offering_data.append_col(get_quarter, header='quarter') issuer_data.append_col(get_quarter, header='quarter') offering_result = offering_resource.import_data(offering_data, dry_run=True) issuer_result = issuer_resource.import_data(issuer_data, dry_run=True) if not offering_result.has_errors() and issuer_result.has_errors(): offering_resource.import_data(offering_dataset, dry_run=False, raise_errors=True) del offering_result issuer_resource.import_data(issuer_dataset, dry_run=False, raise_errors=True) del issuer_result else: print('an error occurred') return render(request, 'index.html') My resource looks like this: class OfferingResource(ModelResource): accession_number = Field( attribute='company', column_name='ACCESSIONNUMBER', widget=ForeignKeyWidget(Company, 'accession_number')) quarter = Field(attribute='quarter') # other fields class Meta: model = Offering use_bulk = True skip_diff = True batch_size = 1000 import_id_fields = ('accession_number', 'quarter') def before_import_row(self, row, row_number=None, **kwargs): total_offering_amount = row.get('TOTALOFFERINGAMOUNT') try: row['TOTALOFFERINGAMOUNT'] = … -
Django Admin panel displays object(like Category Object ) instead of using def __str__(self) function
Code from models.py class Category(models.Model): STATUS = ( ('True', 'True'), ('False', 'False'), ) parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=30) keywords = models.CharField(max_length=255) description = models.TextField(max_length=255) image=models.ImageField(blank=True,upload_to='images/') status=models.CharField(max_length=10, choices=STATUS) slug = models.SlugField() create_at=models.DateTimeField(auto_now_add=True) update_at=models.DateTimeField(auto_now=True) def __str__(self): return self.title when add category in DB it shows as : code from admin.py # Register your models here. from product.models import Category admin.site.register(Category) I want to display category by their title not by model object, Thank you in advance -
Django returns 503 server error. More in description
I have deployed a Django app on Azure App Services. In it, there are 3 apps with 3 models 1 in each. I'm using djongo to connect my Django app with a MongoDB database, which is hosted on Azure CosmosDB. The structure of my models is like this: Course --Courses Subject --Subjects University --Universities And the collections in MongoDB are: course_course subject_subject university_university The data are linked to one another. Course depends on subject and university; and subject depends on university; and university is independent. I created an entry in the Universities model, and then in the Subjects and then in the Courses. When I open up the list of entries: the part where you can see all data/entries in List views along with filters and search, Course and Subjects work fine, but Universities return Server error (503). However, when I run and serve the Django on my local machine, it works fine (it's is connected to the CosmosDb, not my local mongo). Everything is as it's supposed to be. So it doesn't look like an issue of code or DB, but of somewhere in the server-side of Azure. Also, when I deleted the collection of university_university, the page opened …