Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How is a FieldBlock rendered in wagtail cms 2.13.x?
Since Wagtail 2.13.x, the render_form method is removed from the FieldBlock (A block inherited by most default blocks such as CharBlock, TextBlock etc.) How are these blocks rendered using Wagtail 2.13.x? A test for rendering a block is as follows: def test_form_render(self): block = FormChooserBlock() test_form_html = block.render_form(self.form, "form") expected_html = "\n".join( [ '<select name="form" placeholder="" id="form">', '<option value="">---------</option>', '<option value="%s" selected>Basic Form</option>' % self.form.id, "</select>", ] ) self.assertInHTML(expected_html, test_form_html) Obviously, this test breaks when upgrading to wagtail 2.13.x, because the render_form method is not an attribute of block anymore. -
connect django from one server to another
I have deployed a django application in windows server 2012.This application accesses database in a different server.When I try to load it,it says "The fastCGI process exceeded configured activity timeout. How can I solve this? -
Static files served from localhost but not from remote server (ask credentials)
I have set a virtual directory where I have my static files being served on IIS. the static folder points to a shared drive. when I use the website from localhost the "download" button downloads the file right away, but when I do it from a remote website it asks me for credentials (which are also always invalid) I think it might be a thing about permissions, but I don't get what could be wrong. Authentication Type is set to Windows Authentication Anonymous Authentication to both the website and the static folder in IIS I played around with different combinations of these Auth. types but I couldn't get it to work there is also this setup on the static folder: -
HTML form input field take value from RFID scanner
I have a project on Django. There I have a template with input field 'RFID' which now can only be filled manually and after pressing save button it saves to database. How to make this field listen RFID scanner to make sure when RFID mark will be scanned it writes data to the field in the template? Here are my Django files method which sends request to turnstile in bytes representation request_for_read = b"\x10\x01\xC3\x00\x11\xE5" def send_request(self): return ser.write(request_for_read) method that parses rfid mark def parse_rfid_mark(self): while command.send_request(): response = ser.readline().hex() if len(response) == 28: rfid_tag = response[12:20] print(f'RFID mark: {rfid_tag}') return response html template — https://pastebin.com/seST0RJC I would appreciate any help. Thanks in advance! -
How can I show real product price and also Discounted price
My html : {% for stock in stocks %} <p> size : {{stock.size}}</p> {% for dis in discount %} price : {{stock.price}} and Discount Percent : {{dis.discount_percent}}% {% endfor %} {% endfor %} I used first loop because my product can has two different size, and second loop is just because I used objects.filter(), for example price is 200$ and discount_percent is 25, How can I show discounted price that became 150$ ? -
How to manage concurrency in Django app where user can upload and dowload files?
I develop a Django app with 2 main functionalities: import data from other databases using API -> produce one csv files per model of the database export filtered data in a zip folder from csv files produced by import In "standard use", import is an automatic programmed task using celery (every day at midnight). But some users will be authorized to make import when needed, replacing the csv files of the day. Import can takes time so I may face problems of concurrency when a user is producing a new import (and replacing csv files of the day) while another user try to export the data of the day. How should be manage this concurrency? thanks for help -
I want to use Django to categorize mp3 files into a list and keep playing the mp3 files in the list
I want to classify mp3 files into a list using Django and play the mp3 files in the list continuously. (When playing only one mp3 file, use the html5 audio tag.) Get the length of the mp3 file in front and Should I give it a break for the length of time and execute the next file? Or is there another good way?