Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pointfield not picking and storing latitude and longitude in Django
The following Location field which is a Pointfield is not picking up and storing the coordinates. It results in giving the default coordinates given i.e (0,0). class CustomerProfile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) fullname = models.CharField(max_length=120,unique=True) choice = ( ('AB+ve','AB+ve'), ('A+ve','A+ve'), ('B+ve','B+ve'), ('O+ve','O+ve'), ('AB-ve','AB-ve'), ('A-ve','A-ve'), ('B-ve','B-ve'), ('O-ve','O-ve'), ) bloodgroup = models.CharField(max_length=100,choices=choice) choicea = ( ('Male','Male'), ('Female','Female'), ('Other','Other'), ) gender = models.CharField(max_length=100,choices=choicea) location = models.PointField(default=Point(0, 0),geography=True) profilepicture = models.ImageField(upload_to='images',default=None) def save(self, *args, **kwargs): self.latitude = self.location.y self.longitude = self.location.x super(CustomerProfile, self).save(*args, **kwargs) def __str__(self): return self.fullname -
django - When fields are flexible at creation time
models.py class MatchingPartner(models.Model): matching = models.ForeignKey( Matching, on_delete=models.CASCADE, related_name="matchingpartner" ) non_user_nm = models.CharField(max_length=45, null=True) non_user_gender = models.CharField( max_length=1, choices=NonUserGenderChoice.choices, null=True ) I want to create a "Matching Partner" model with data called "partner." [request "partner" data] "partner": [ { "non_user_nm": "1", "non_user_gender": "F" }, { "non_user_nm": "2", "non_user_gender": "F" } ] There's multiple instances of it going around the code, and if that's the case, "partner": { "non_user_nm": "Mina"} In this way, when data is passed over, fields other than "non_user_nm" would like to be stored as null. if request.data: partners = request.data["partner"] for partner in partners: MatchingPartner.objects.create( matching=matching_instance, non_user_nm=partner["non_user_nm"], non_user_gender=partner["non_user_gender"], ) What should I do? -
Django Search in Models with 3 fields
I have search fields, keyword, cdate_start, cdate_end. They can be null. What I want is if keyword entered, get results the only keyword contained results. If keyword not entered but cdate_start entered get items only greater than this cdate_start. Or keyword and cdate_end entered then get items only contains this keyword and less than cdate_end, and etc. I have to get all combinations like this. I tried something like this. if self.request.GET.get('feedback_s_keyword') is not None: keyword = self.request.GET.get('feedback_s_keyword') else: keyword = '' name_or = Q(author__name__icontains=keyword) surname_or = Q(author__surname__icontains=keyword) feedback_or = Q(feedback__icontains=keyword) if self.request.GET.get('feedback_s_cdate_start') is not None: cdate_start = self.request.GET.get('feedback_s_cdate_start') cdate_start = cdate_start.split('/') try: year_s = cdate_start[0] month_s = cdate_start[1] day_s = cdate_start[2] except: year_s = 2001 month_s = 1 day_s = 1 else: year_s = 2001 month_s = 1 day_s = 1 cdate_gte = Q(cdate__gte=datetime.date(year_s, month_s, day_s)) if self.request.GET.get('feedback_s_cdate_end') is not None: cdate_end = self.request.GET.get('feedback_s_cdate_end') cdate_end = cdate_end.split('/') try: year_e = cdate_end[0] month_e = cdate_end[1] day_e = cdate_end[2] except: year_e = 3000 month_e = 12 day_e = 31 else: year_e = 3000 month_e = 12 day_e = 31 cdate_lte = Q(cdate__lte=datetime.date(year_e, month_e, day_e)) feedbacks = Feedback.objects.filter(name_or | surname_or | feedback_or | cdate_gte | cdate_lte).order_by( "-cdate") But of course, if cdate … -
How to get UserProfile to reference the fields from UserModel?
Just an fyi, I'm pretty new to programming & Django in general. I've been teaching myself. Before I get into the problem, I'll share my Django code: models.py : class User(AbstractUser): # DATABASE FIELDS email = models.EmailField(("email address"), unique=True) REQUIRED_FIELDS = ['username'] USERNAME_FIELD = 'email' # META class Meta: verbose_name = "User" verbose_name_plural = "Users" # TO STRING METHOD def __str__(self): return "User " + str(self.id) + " - " + self.email class UserProfile(models.Model): # RELATIONSHIP user = models.ForeignKey( to = User, on_delete = models.CASCADE, related_name = "user_account" ) # DATABASE FIELDS first_name = models.CharField(max_length=100, verbose_name="First Name") last_name = models.CharField(max_length=100, verbose_name="Last Name") date_created = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Profile Created On") role = models.CharField(max_length=255, verbose_name="User Demographic") # META class Meta: verbose_name = "User Profile" verbose_name_plural = "User Profiles" # TO STRING METHOD def __str__(self): return self.first_name forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import User class AbstractUserCreationForm(UserCreationForm): class Meta: model = User fields = ('username', 'email') class AbstractUserChangeForm(UserChangeForm): class Meta: model = User fields = UserChangeForm.Meta.fields serializers.py from rest_framework import serializers from djoser.serializers import UserCreateSerializer, UserSerializer from . import models from .models import User, UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ('id', 'email', 'username', … -
Django - Relationship Model
I need some help for database relationship and assignment. For instance, we have an employee model class EmployeeModel(models.Model): email = models.EmailField(max_length=150, unique=True) employee_no = models.IntegerField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50) def __str__(self): return str(self.first_name + ' ' + self.last_name) And let say an employee can have a group of task. But before that, we have to create a task in order to group it. This is a task model: class Task(models.Model): id = models.AutoField(primary_key=True) task_code = models.CharField(max_length=150, unique=True, editable=False) name = models.CharField(max_length=150) type = models.CharField(max_length=20, editable=False) description = models.CharField(max_length=250) def __str__(self): return self.name We then now group the tasks. class GroupTask(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=150) group_code = models.CharField(max_length=150, unique=True, editable=False) task = models.ManyToManyField(Task, blank=True) def __str__(self): return self.name So after grouping, we now have a list of task in group task model. For example, in Group 1, we have Task 1, and Task 2. This group of task should also be in a project, so we have to connect this group of task in a project model. Because each projects should have a group of task. class Project(models.Model): code = models.CharField(max_length=20, editable=False, default=auto_generated_code) name = models.CharField(max_length=100) description = models.CharField(max_length=250) group_task = models.ManyToManyField(GroupTask, blank=True) def … -
django celery vs multithreading vs asyncio
I have a Django application that allows users to upload a file and my application will convert the file to the user's specifications. Currently, if multiple users try to convert files at the same time, the process will go something like this Process user 1s files converting... done Process user 2s files converting... done It's essentially acting as a queue. Clearly, this is inefficient when multiple users are trying to convert files. I have looked into things like multithreading, celery, asyncio, etc. I can't seem to pick out the differences between the 3. What is the difference and which would be best so users on my site can convert files without waiting for other users' files to finish? Thanks :) -
Clear all data of certain fields for all objects?
I'm trying to clear all the data of a certain field within a model for all of the objects. Something like this: #models.py class A(models.Model): someProperty = models.ManyToManyField(SomeModel) #views.py object = A.objects.all() object.someProperty.all().clear() I understand this is probably simple but I have been looking through the django documentation and haven't been able to find a good way to do this. Any help is greatly appreciated :) -
Django order_by Property gives error undefined
i am trying to order by (descending) average_score, but when i run it i get error: name 'average_score' is not defined. What am i doing wrong here? error: name 'average_score' is not defined model: def _get_average_rating(self): reviews = Ratings.objects.filter(post=self) average = reviews.aggregate(Avg('score'))['score__avg'] average = round(average, 1) return average average_score = property(_get_average_rating) view: if sort == 'Average Rating': Posts = Posts.order_by(-average_score) -
how to toggle only one element of a loop in a Django template using JavaScript/Jquery?
I'm trying to implement a toggle to display a hidden DIV for every element in my loop statement on a Django template. Problem is I only manage to make it work just on the first element of the loop, or in all of them at once (one buttom triggers every hidden DIV to show). How can I make this possible using vanilla JS or in worst case scenario Jquery? here is the html in my template {% for comment in comments%} <div class="comment"> <p><strong>{{comment.author}} {% if comment.author == article.author%}[Seller]{% endif %}</strong> said:</p> <p>{{comment.commentary}} {% if user.is_authenticated and article.status == "Active" and article.author == user %}<button id="test" class="test" onclick="myFunction()">Reply>></button></p> <div class="reply_box_container" id="reply_box_container" style="display:none"> <p><strong>Reply:</strong></p> <form> <div id="reply_textarea_container"><textarea name="comment_textarea" rows="2" cols="50" placeholder="Write your reply here"></textarea></div> <div id="reply_btn_container"><button class="btn btn-secondary" type="submit" name="comment_btn">submit</button></div> </form> </div> {% endif %} {% if reply%} <span class="reply"> <p><strong>{{article.author}}</strong> replied:</p> <p>{{reply}}</p> </span> {% endif %} <hr></hr> </div> {% endfor %} and here the Jquery I tried to use: <script> $(document).ready(function(){ $(".test").click(function(){ $(".reply_box_container").toggle(); }); }); </script> -
Django:[ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'test'. (18456)
I used Django to connect to SQL Server 2016 and I started executing Python3" manage.py Runserver 8000 terminal prompt: django.db.utils .InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'test'. (18456) (SQLDriverConnect)")” enter image description here I don't know where the problem is。 This is my database configuration: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME':'testDB',#db name 'USER':'test',#db longin user 'PASSWORD':'test#2021',#db longin pwd 'HOST': '10.32.9.51',#db host 'PORT': '1433',#port,default1433 'OPTIONS': {#odbc driver 'provider': 'SQLOLEDB', # Have also tried 'SQLCLI11' and 'SQLOLEDB' 'driver': 'ODBC Driver 17 for SQL Server', 'MARS_Connection': True, }, } } But I use pyodbc to connect to the database and query. At this time, the query is successful。 import pyodbc try: conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=10.32.9.51;PORT=1433;DATABASE= testDB;UID=test;PWD=test#2021') cursor=conn.cursor() cursor.execute("select getdate()") row=cursor.fetchone() while row: print("sqlserver date:%s"%(row[0])) row=cursor.fetchone() print(row) conn.close() except Exception as e: print("DB Error") print("DB Error:"+str(e)) enter image description here System environment: System:Centos 7 python: 3.7.9、 Django:2.1.15、 django-mssql:1.8、 django-pyodbc:1.1.3、 django-pyodbc-azure:2.1.0.0、 django-sqlserver:1.11、 djangorestframework:3.12.2、 pip:21.0.1、 pymssql:2.1.5、 PyMySQL:1.0.2、 pyodbc:4.0.30、 sql server configure: enter image description here enter image description here enter image description here -
Django admin list_display is not displaying model method return item
I'm not able to get the list_display of admin to show the information from a model method, but the same method displays fine in the fieldsets on the change page. I think I've fixed all my mistakes that are present in other questions/answers on this topic, but I just can't seem to figure out what I've done. Any help will be much appreciated. Admin: class StudentAdminConfig(admin.ModelAdmin): list_dispaly = ('name', 'get_total_funds') fieldsets=( (None, {'fields': ('name', 'get_total_funds')}), ) readonly_fields = ('get_total_funds',) admin.site.register(Student, StudentAdminConfig) Models: class Student(models.Model): name = models.CharField(max_length=255) def get_total_funds(self): events = self.get_funds_events() total = float(0) for event in events: if event.income: total += float(event.amount) else: total -= float(event.amount) return f'${total:.2f}' get_total_funds.short_description = "Total Funds" def get_funds_events(self): return FundsEvent.objects.filter(students_attended=self) def __str__(self): return self.name The annoying thing about this list_display issue is that it's not giving any errors I can traceback, it's just displaying the page with no column for the "Total Funds". Also, I've sunk so much time into this and it's not even that vital of a feature, just a convenience for me, as I'm literally the only one who will ever look at this display on this particular project, but I'm invested enough that I really want to figure … -
How to access Django admin page without is_superuser property?
I want to know how to access the admin page with the is_admin property instead of the is_superuser property of django. here is my code is_superuser = True # django default is_admin = True # my custom property def create_superuser(self, email, username, password): user = self.create_user( email = self.normalize_email(email), username = username, password = password ) user.is_active = True user.is_staff = True user.is_superuser = True -> i want to change -> is_admin = True user.save(using=self._db) return user Changing is_superuser to is_admin prevents access to the admin page. How can I access the admin page with the is_admin property? -
How to get objects who contain all of the tags in a query with Django Taggit?
I'm trying to get all objects that are tagged with all of the query parameters that I send. For example, if the query is tags=tag1,tag2, I need to get all objects that are tagged with both tag1 and tag2. tags = Final_Content.objects.filter(tags__name__in=self.request.query_params.get('tags').split(",")).distinct() However, this doesn't work as the in condition is satisfied even if only tag is present. -
Database connection object is not callable exception thrown with Python Django SQL Alchemy database pooling. Why?
What I'm trying to achieve Create a database connection pool in Django. The connection pool is connected to a PostgreSQL database by using SQLAlchemy's connection pooling with django-postgrespool2. Thrown exception 'psycopg2.extensions.connection' object is not callable is thrown when running the following line of code poolConnection = dbPool.connect(). Printing the dbPool object and type displays <sqlalchemy.pool.impl.QueuePool object at 0x00000171832A72B0> <class 'sqlalchemy.pool.impl.QueuePool'> Code Database helper class which creates the connection to the PostgreSQL database and creates the connection pool: import psycopg2 from sqlalchemy import pool import traceback dbPool = None class DbPoolHelper: def ensurePoolCreated(self): global dbPool if dbPool != None: return self.createPool() def dbConnect(self): dbConnection = psycopg2.connect(user="...", password="...", dbname="...", host="...",port="...") return dbConnection def createPool(self): dbConnection = self.dbConnect() global dbPool dbPool = pool.QueuePool(dbConnection, max_overflow=10, pool_size=5) def execute(self, sql, sqlParams): try: global dbPool self.ensurePoolCreated() poolConnection = dbPool.connect() cursor = poolConnection.cursor() cursor.execute(sql, sqlParams) poolConnection.commit() result = cursor.fetchall() cursor.close() poolConnection.close() return result except Exception as e: print(e) return e The code using the DbPoolHelper to fetch some data by using the execute method and giving some sql and sql params as arguments: def poolTest(): sql = "SELECT * FROM sysproductcontainers;" sqlParams = () db = DbPoolHelper() result = db.execute(sql, sqlParams) Question Why does the code throw … -
How to send a key value with an empty list in a django RequestFactory? or drf APIRequestFactory?
I have a method that I must not change, that expects a request as a QueryDict. It does some logic with a parameter that receives like this: request.POST.getlist("process") So, I need to send a fake request with all the data and that key value. I need to send that value as an empty list, like this: <QueryDict: {'process': [], 'foo': 'bar'}> So I tried with django RequestFactory like this: from django.test.client import RequestFactory rf = RequestFactory() request = rf.post('/submit/', {'foo': 'bar', 'process':[]}) But I got: print(request.POST) <QueryDict: {u'foo': [u'bar']}> Also with drf APIRequestFactory like this: from rest_framework.test import APIRequestFactory rf = APIRequestFactory() request = rf.post('/submit/', {'foo': 'bar', 'process':[]}) I got: print(request.POST) <QueryDict: {u'foo': [u'bar']}> I expect to get: <QueryDict: {u'foo': [u'bar'], 'process':[]}> Important: process value must be [] and not [[]]: <QueryDict: {u'foo': [u'bar'], 'process':[[]]}> # I dont want this (It doesn't matter if foo value is a list, but I need process as []) So, It's possible to get an empty list in a fake request with django RequestFactory? or drf APIRequestFactory? Thanks for any help -
How to get the data out of that special json?
I want to make it short. I want to do a table, which contains data from a django api stream via angular. Im using the http get method from angular to do so, and it works absolutely fine with the following examples: https://jsonplaceholder.typicode.com While this cant be extracted. Even when i go into results with sth like results: { id: any; } I cant provide a link because its changing sometimes at the moment (thats not the reason why i cant parse it into my table) Im new to Front end and programming in generally so please be precisely and comprehensive, i just want a solution and never wanna see frontend again at anytime :D. Can there be any difference between those jsons, that i cant see or google? I think, its pointless giving the code for the get request, because its actually working but just in case: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Tutorial } from '../models/tutorial.model'; const baseUrl = 'https://jsonplaceholder.typicode.com/users'; @Injectable({ providedIn: 'root' }) export class TutorialService { constructor(private http: HttpClient) { } getAll(): Observable<Tutorial[]> { return this.http.get<Tutorial[]>(baseUrl); } I really wanna get this … -
Why can't I render my editform but I can render my addform?
I keep getting this Error when I attempt to render the editform.html. Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['contacts/edit/(?P<cur_id>[0-9]+)/$'] I'm not sure what I'm doing wrong, I was able to render my addform.html without an issue, but this editform is being pesky. I feel like I need to pass something somewhere but I'm not completely sure where or what. urls.py from django.urls import path from . import views app_name = 'contacts' urlpatterns = [ path('', views.index, name='index'), path('list/', views.list, name='list'), path('add/', views.add, name='add'), path('edit/<int:cur_id>/', views.edit, name='edit'), path('delete/<int:cur_id>/', views.delete, name='delete'), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from django.template import loader from .models import Contact def index(request): return HttpResponse("Hello, world. You're at the contacts app.") def list(request): contacts_list = Contact.objects.all() return render(request, 'index.html', {'contact_list':contacts_list}) def add(request): if request.method == 'POST': new_contact = Contact( firstname = request.POST['firstname'], lastname = request.POST['lastname'], age = request.POST['age'], phone = request.POST['phone'], email = request.POST['email'], gender = request.POST['gender'], ) new_contact.save() return redirect('/contacts/list/') return render(request, 'addform.html') def edit(request, cur_id): return render(request, 'editform.html') def delete(request, cur_id): pass editform.html <html> <head> <title> Contacts App </title> {% load static %} <script src="{% static '/contacts.js'%}"></script> {% load static %} <link rel='stylesheet' type='text/css' href="{% … -
Check if a user leaves a view function
Lets say I have a realArray and a tempArray. I want to add all the data in the tempArray into the realArray if a user clicks something that would cause them to leave the view they are currently on. This could be closing the browser, searching something in their browser, clicking a bookmark, or clicking a different link within the website. Any thoughts would be appreciated:) -
Page not found (404) django.contrib.admin.options.add_view
On the production server, when I try to edit/create an object then saving fails, returning Page not found (404).This only occurs for POST requests, GET requests (loading the page) work fine. Django is deployed via cPanel and WSGI, DEBUG is False (though it does not work even when it's set to True) Request Method: POST Request URL: https://example.com/admin/[APP Name]/[Model]/add/ Raised by: django.contrib.admin.options.add_view Using the URLconf defined in General.urls, Django tried these URL patterns, in this order: admin/ [name='home'] stores/ [name='allstore'] site/<slug:slug>/ [name='store'] code/<slug:slug>/ [name='cate'] category/ [name='category'] deals/ [name='api'] offer/ [name='offer'] ^media/(?P<path>.*)$ The current path, Hotel/slider/add/, didn't match any of these.``` **setting.py** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } **I will try a different Database But showing the same erorr** Mysql Postgresql STATIC_URL = '/static/' STATIC_ROOT = '/home/username/domainname.com/static' MEDIA_URL = "/media/" MEDIA_ROOT = "/home/username/domainname.com/media" -
What are the benefits of having multiple front-ends?
TL;DR When should a project have multiple front-ends? I'm unsure if we should extend our existing front-end or make another one with additional functionalities. We have an Ionic-React app that interfaces with a Django back-end. We've reached a point where we need the following: An admin front-end (with some admin-level permissions). Think support desk, account overview, and analytics. A desktop app (with limited permission). Think account overview, but with less permission than the mobile app. Would it be better to merge these 2 solutions into our main mobile app (and use ionic to generate a PWA) or should we have a dedicated solutions for these? Disadvantage of merging: The app will be heavy. Ionic is known to be slow (and sometimes buggy). User permission will be quirky. Admin and desktop app have the most overlap in functionality, so it would keep the code much cleaner. 2nd front-end could double as landing page. Advantages of merging: Less code to maintain, less front-ends to deploy. I honestly can't think of another advantage for this. This might be really messy... Which solution do you think would work best? As you can tell, I want separate apps, but I have a project manager to … -
NOT NULL constraint failed: products_order.user_id when trying to save serializer django rest frame work
django rest framework gives me this error when i am trying to perform a post request to create a new order even though i specified the usr value in my serializer.save method. here is my view class OrderListCreateAPI(generics.ListCreateAPIView): serializer_class = OrderSerializer permission_classes = [IsOwner] def get_queryset(self): user = self.request.user return Order.objects.filter(user= user) def perform_update(self, serializer): instance = serializer.save(user = self.request.user) order = Order.objects.get(id = instance['id'].value) order.item.quantity -= order.quantity order.save() my models.py payment_methods = ((1,'credit card'),(2, 'cash'),(3, 'paypal')) class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to = 'images/', height_field=300, width_field=300) price = models.IntegerField() quantity = models.IntegerField() seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='products') date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Order(models.Model): item = models.ForeignKey(Product, on_delete= models.CASCADE, related_name='orders') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') quantity = models.IntegerField() payment_options = models.CharField(choices=payment_methods, max_length=50) Delivery = models.CharField(max_length=200) my serializers class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'title', 'description','image', 'price', 'quantity', 'seller', 'date'] read_only_fields = ['date', 'seller'] class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' read_only_fields = ['user'] -
Django Multiple Files Upload
I would like to upload multiples files in my model in Django. I am struggling on the HTML part. I would like to include it part of my detail view without having to create a special view to upload the files. When I click on the button, it open the file upload, I select them but they don`t seem to be attached to the model. Any ideas please? models.py class Quote(models.Model): name = models.CharField(max_length=30) class Attachment(models.Model): quote = models.ForeignKey(Quote, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=30) file = models.FileField(upload_to='quotes/%Y/%m/%d',blank=True, null=True) def __str__(self): return self.name forms.py class AttachmentForm(forms.ModelForm): class Meta: model = Attachment fields = ('file', ) widgets = { 'file': ClearableFileInput(attrs={'multiple': True}), } # widget is important to upload multiple files views.py @login_required(login_url="/login/") def add_attachment(request, quote_id): form = AttachmentForm(request.POST or None, request.FILES or None) quote = get_object_or_404(Quote, pk=quote_id) if form.is_valid(): quotes_attachments = quote.attachment_set.all() attachment = form.save(commit=False) attachment.quote = quote attachment.attachments = request.FILES['attachments'] file_type = attachment.attachments.url.split('.')[-1] file_type = file_type.lower() attachment.save() return render(request, 'quotes/quote_detail.html', {'quote': quote}) context = { 'quote': quote, 'form': form, } return render(request, 'quotes/quote_detail.html', context) quote_detail.html <div class="card-block"> <form action="/static/assets/plugins/fileupload/js/file-upload.php" method="post" class="dropzone" enctype="multipart/form-data" > <div class="fallback"> <input name="file" type="file" multiple style="display: none;" data-url="{% url 'projects:add_attachment' quote.id %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token … -
How to safely remove a column from a Pandas dataframe in a web environment(Django)?
I am building an interactive data science dashboard and I encounter a situation where deleting a column doesn't result in the predicted behavior: if action == 'COLUMN_REMOVE': name = payload['name'] print('#\t', name) df = df.drop(columns=[name], axis=1) df.to_csv(document.path.path) The original column set is something like this: [a, b, c, d, <name>] After running the code snippet above inside a Django request view, the column is not being deleted but the resulting dataframe has renamed it/added a new column with the name (Unnamed: 0.0) [a, b, c, d, Unnamed: 0.0] Is the way I am deleting the data frame correct? I tried multiple ways (e.g., del df[name]) but it produces equivalent results. -
Need help I want correct explanation for that, Class and Inherit
class MovieSerializer(serializers.ModelSerializer): #MovieSerializer = it's a class name #serializers = it's a Inherit #ModelSerializer = ???? please help me -
Djago dependent dropdown list using AJAX jQuery not working in Template
im doing a django dependent form and it works for my create view but not in update view. I tink the problem is the jQuery cdn library, i think its a conflict with the bootstrap cdn. The AJax call does not fire. Any idea maybe there is a simpler way to do dependent forms in django? If you have a solution i gladly want your help thx Theo Models view: class Profession(models.Model): name = models.CharField(max_length=30) profession_icon = models.ImageField(_("profession icon"), upload_to='profession_icon/%Y/%m/%d/', height_field=None, width_field=None, max_length=None, blank=True, validators=[validate_image_file_extension]) def __str__(self): return self.name class Professioncategory(models.Model): profession = models.ForeignKey(Profession, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Skills(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(_('Active'), default=True) profession = models.ForeignKey(Profession, on_delete=models.SET_NULL, null=True) professioncategory = models.ForeignKey(Professioncategory, on_delete=models.SET_NULL, null=True) posted_on = models.DateTimeField(_('Registrerad'), auto_now_add=True) updated_on = models.DateTimeField(_('last updated'), auto_now=True) years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True) def __str__(self): return self.user.email def get_absolute_url(self): return reverse("users:detail", kwargs={"user_id": self.user.id}) def geticon(self): return self.profession.profession_icon Forms.py class SkillsForm(forms.ModelForm): class Meta: model = Skills fields = ['profession','professioncategory', 'years_of_exp','active'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['professioncategory'].queryset = Professioncategory.objects.none() if 'profession' in self.data: try: profession_id = int(self.data.get('profession')) self.fields['professioncategory'].queryset = Professioncategory.objects.filter(profession_id=profession_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to …