Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
how to make and return graphs with data frames converted to json in django template and view
i would like to know how to draw and add graph in django from pandas dataframes converted to json? after several documentation I really did not have an idea of the steps to follow for the processing of json files in order to create beautiful graphs in django views.py : def parasol_view(request): parasol = function_parasol() parasol_json = parasol.to_json(orient='records') parasol = parasol.to_html(index = False, table_id="table_parasol") context = { 'parasol': parasol, 'parasol_json':parasol_json } return render(request,'parasol.html',context) template {%block content%} <hr> {{parasol| safe}} {{parasol_json}} {%endblock content%} -
how to inset data in a django website in production from admin side
I have hosted a Django webiste on Cpanel. and successfully connected my website with the MySQL database. but I want to insert data like photos and announcements with admin panel, like we use to do with Django admin panel in development. but in production, there is no option for uploading data from the admin side. I need to know how to do this task. -
Django Authentication linking API to the app and integrating social authentication
I have a Django project where I want to create a authentication system .I am also using JWT and DRF and social auth. All the tutorials I can find only involve handling one the above .I was wandering if there is a way to combine social authentication and JWT for the API -
data is not expected in nested serializer
I m making a post request. but the data is not giving me as expected. views.py @api_view(['POST']) def ruleAssignment(request): if request.method == 'POST': data = JSONParser().parse(request) serializer=RuleAssignmentParamsSerializers(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=status.HTTP_200_OK,safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and serializers.py I have create function to split the objects and save the data in different models. class RuleAssignmentParamsSerializers(serializers.ModelSerializer): ruleAssignmentDetails = serializers.SerializerMethodField() targetDefination = serializers.SerializerMethodField() class Meta: model = RuleAssignmentParams fields = ( 'id', 'ruleAssignmentDetails', 'detailSrl', 'parameterName', 'valueType', 'overwriteValue', 'targetDefination', ) def create(self,validated_data): print(f'validated_data',validated_data) ruleAssDetails = validated_data.pop('ruleAssignmentDetails') print(f'ruleAssDetails',ruleAssDetails) def get_ruleAssignmentDetails(self,obj): rule = RuleAssignmentDetails.objects.get(id=obj.ruleAssignmentDetails_id) serial = RuleAssignmentDetailsSerializers(rule) return serial.data def get_targetDefination(self,obj): rule = TargetDefination.objects.get(id=obj.targetDefination_id) serial = TargetDefinationSerializers(rule) return serial.data and the object I m sending: { "ruleAssignmentDetails": { "id": 1, "ruleAssignment": { "id": 1, "empId": 1, "roleId": 1, "empName": "Emp01", "roleName": "CEO" }, "detailSrl": 12, "rule": 4, "validityType": "F", "startDate": "2021-06-14", "endDate": null, "frequency": { "id": 1, "frequencyName": "Test", "frequencyTpe": "Weekly" } }, "detailSrl": 12, "parameterName": "Param1", "valueType": "D", "overwriteValue": null, "targetDefination": { "id": 1, "targetName": "MIN SALES", "displayName": "MIN SALES" } } and when I print(validated_data) in serializer it's giving me: {'detailSrl': 12, 'parameterName': 'Param1', 'valueType': 'D', 'overwriteValue': None} not the whole object. how do I get all the data in serializer -
django How to randomly merge two different querysets (but with some fields in common)
I am using Django 3.2 I have two models that look a bit like this: class A(models.Model): title = models.CharField(max_length=255) caption = models.CharField(max_length=64) image = models.ImageField() # ... other fields unique to this model only class B(models.Model): title = models.CharField(max_length=255) caption = models.CharField(max_length=64) image = models.ImageField() # ... other fields unique to this model only I want to be able to write a function like this: def get_modelA_records_with_randomly_inserted_modelB(criteria_for_A, criteria_for_B, page_num): qs_A = get_records_for_modelA(criteria_for_A, page_num) qs_B = get_records_for_modelB(criteria_for_B, page_num) # Randomly insert records of B into list of records of A new_qs = qs_A | qs_B # how? A trivial way to do this would be to laboriously iterate through qs_A, inserting qs_B elements based on a random boolean flag - but I'm wondering is there a more pythonic or "djangoistic" way to do this?