Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a spefici template to buil-in Login system in django
I can't find anything about how I can add my personal custom template for my login page to the built-in Login system in django. I've tried to make a login view function to can connect my template with the login system but in this way I can't add login with google and facebook and because of that I can't use that function, but with this classed base view from django I can't handle to add my personal template to this class. Any ideas ? Template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Login</title> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet"> </head> <body class="bg-gradient-primary"> <div class="container"> <div class="row justify-content-center"> <div class="col-xl-10 col-lg-12 col-md-9"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-6 d-none d-lg-block bg-login-image"></div> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1> </div> <form class="user"> <div class="form-group"> <input type="email" class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Enter Email Address..."> </div> <div class="form-group"> <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password"> </div> <div class="form-group"> <div class="custom-control custom-checkbox small"> <input … -
Django + React Able to create new user in database, but token-auth returns 400 bad request
So I have an app that I'm writing. It's working, for the most part, so far. I only currently have a login and signup setup, with a 'homepage' that just has a logout button and some text on it so I can test. When I do signup, it posts the user to the database, but then I get this: Bad Request Image Here is my Instructor Model: class Instructor(AbstractUser): displayname = models.CharField(max_length=80, blank=True, null=True) email_address = models.EmailField(blank=True, null=True) grade_taught = models.IntegerField(default = 0) room_number = models.IntegerField(default = 0) Serializer(Instructor and with Token): class InstructorSerializer(serializers.ModelSerializer): class Meta: model = models.Instructor fields = [ 'id', 'username', 'email_address', 'displayname', 'grade_taught', 'room_number' ] class InstructorSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only = True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = models.Instructor fields = [ 'token', 'username', 'password', 'email_address', 'displayname', 'grade_taught', 'room_number' ] Related Views: class InstructorList(APIView): permission_classes = (permissions.AllowAny,) def post(self, request): serializer = serializers.InstructorSerializerWithToken(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) class InstructorViewSet(viewsets.ModelViewSet): queryset … -
Heroku Django value too long for type character varying(20)
The Django website is working fine in development, but on Heroku whenever I create a user instance I get this error django.db.utils.DataError: value too long for type character varying(20) from Heroku logs the error occurs at: try: user = User.objects.get(phone_number=phone_number). # It returns an error here except User.DoesNotExist: user = User.objects.create_user( phone_number=phone_number, username=phone_number) # Then another error here my user model looks like this: from phonenumber_field.modelfields import PhoneNumberField class User(AbstractUser): phone_number = PhoneNumberField(unique=True) username = models.CharField(max_length=30) ... bunch of other fields that are not related to the question And the method looks like this (Postman): { "phone_number": "+200000000000" } As I said it works perfectly In development, and in pythonanywhere. but for some reason, it gives this weird error on Heroku. I can make a guess that it's because PA and Dev servers were using a Sqlite3 DB while Heroku uses Postgres. Any idea about how to fix this? Also if using a MySql database will solve the problem are there any docs about how to use it? I'm a newbie to SQL and the only SQL database I worked with was Sqlite3 My settings.py try: import django_heroku django_heroku.settings(locals()). # for some reason when I run python3 manage.py runserver it … -
Dynamic filter and ignore empty value in Django
Does anybody know how can I ignore empty value when filtering data in django. It consumes time if I make a lot of conditions, the only selected item should be retrieve when contain value What I've already tried, but the problem is that my request Post/name from html is not the same value from my database kwargs = {} for field in ["data1", "data2","data3","data4", "data5","data6", "datefrom","dateto" , "data7","data8","data9","data10"]: try: kwargs[field] = request.POST[field] except KeyError: pass Filter_data = Datas.objects.filter(**kwargs) Also I tried this , I know this should not work data1= request.POST.get('data1', None) data2= request.POST.get('data2', None) data3= request.POST.get('data3', None) data4= request.POST.get('data4', None) data5= request.POST.get('data5', None) data6= request.POST.get('data6', None) data7= request.POST.get('data7', None) from= request.POST.get('from', None) to= request.POST.get('to', None) data8= request.POST.get('data8', None) data9= request.POST.get('data9', None) data10= request.POST.get('data10', None) #if one of this value is None: for example value data9 and data10 is empty or None then the rest contain value and when filtering, the data9 and data10 should not be include in filter . I think it should work using `in` Filter_data = Person.objects.filter( sample1 = data1,sample2 = data2 sample3 = data3,sample4 = data4, sample6 = data6,sample7 = data7, datefrom = from,dateto = to, sample8 = data8,sample9 = data9, sample10 = data10 ) … -
Adding Ajax to comments section not Working
I am trying to add Ajax to my comment section to avoid the page refreshing every time a comment is added. So I load the comments section to the post-details.html from new comments.html and followed the implementing Ajax to posts but my problem is that it is not making any effect and the page needs to refresh to show the new comment I have sub-classed Generic DetailView class in views.py and trying to figure out a way to return data in JSON format based on an argument received in the URL. Here's what I have tried doing: class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment_qs = None comment = Comment.objects.create( post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect("blog/post_detail.html") else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form context["total_likes"] = total_likes context["liked"] = liked if self.request.is_ajax(): html = render_to_string('blog/comments.html', context, request=self.request) return JsonResponse({'form': html}) else: return context But this gave me TypeError as it should be: TypeError: context … -
Django - best approach to generate pdf file with charts and loading bar
my question is not that simple like in the title. First of all on my site I'm uploading a single file, which is Snort/Suricata alert, then it is possible to view some charts with ECharts. I would like to generate PDF file with some data and charts but not from a single file, but all files from a single users. So my questions are: Should I combine multiple files in one or collect data from seperate files ? What's the best package for this task to generate PDF ? (once I used xhtml2pdf but I'm not sure if it's a good option) I know it will take a long time to generate it, so I think about adding loading bar or a spinner, how should it be done ? Using AJAX or anything else ? If you need any of the code just let me know :) The version of Django is 3.1.1 -
image from DRF not loading in react js
My react js app just won't load any image from my DRF. I am suffering quite a while to fix this, but I just can't find a solution. In my react app, I am fetching data from https://randomuser.me/api/?results=20' (mapping the results to "<img.." etc.) and the fetched images are loaded with <img src="https://...." alt='image'> and they are displayed immediately. But when I fetch my DRF api, I get a timeout. <img className='user-avatar-settings' src={ this.state.photo} alt='user-avatar' /> where this.state.photo is https://127.0.0.1:8001/media/user_avatar/user_3.jpg Chrome is saying:127.0.0.1:8001/media/user_avatar/user_3.jpg:1 GET https://127.0.0.1:8001/media/user_avatar/user_3.jpg net::ERR_TIMED_OUT after a little while. *) The first url isn't correct, the second one is. *) When clicking the correct url, the image is not loaded (the click redirects to a new Chrome tab, so I am outside of the app). *) I first need to quit and restart the Django server, afterwards the image is loaded immediately in the Chrome tab - but not inside my react app. Even a GET Request with the image url is running into that timeout. And it's not up to that one specific image. None image from backend /media/ folder is showing up in react js - only that one little "placeholder" image from browser (a mini image). … -
Enable SSO for user authentication in django python project using keycloak as identity broker
I am trying to enable SSO using keycloak as identity broker and Microsoft AD as identity provider(where keycloak will delegate the client's authentication request to AD) in a django python project. Tech stack of application: frontend- React backend - django python For this I am using python-keycloak library in django to communicate with keycloak.What I am able to achieve is : setup a connection with keycloak and get access_token and refresh_token when username and password is provided like this: # Create Keycloak instance self.keycloak = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id, realm_name=self.realm, client_secret_key=self.client_secret_key) # Get WellKnow self.config_well_know = self.keycloak.well_know() # Get Token self.token = self.keycloak.token("user","pwd") # get userinfo self.userInfo = self.keycloak.userinfo(self.token['access_token']) # userinfo returned ok But here i am providing username and password which I should not as I want to enable sso with Microsoft AD(Note: keycloak realm is configured to use Microsoft AD as default IDP) and only username should be sufficient to enable SSO with Microsoft. But it is giving error on passing only username. Question: How to authenticate user from Microsoft AD using keycloak broker and what should be the syntax for the same? -
Adding categories to a django blog
I made a simple django blog and I wanted it to display posts according to the category the post is assigned to. But it doesn't work as intended when I filtere it instead of filtering the posts according to the category it shows the html code in the base.html file. My polls/urls.py file from django.urls import path from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView from .views import DeletePostView, AddCategoryView, CategoryView urlpatterns = [ path('', HomeView.as_view(), name='home'), path('article/<int:pk>/', ArticleDetailView.as_view(), name='article-view'), path('add_post/', AddPostView.as_view(), name='add_post'), path('add_category/', AddCategoryView.as_view(), name='add_category'), path('article/edit/<int:pk>/', UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove/', DeletePostView.as_view(), name='delete_post'), path('category/<str:categories>/', CategoryView, name='category') ] My views.py file from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm, EditForm from django.urls import reverse_lazy from django.shortcuts import render class HomeView(ListView): model = Post template_name = "home.html" # ordering = ["-post_date"] ordering = ["-id"] class ArticleDetailView(DetailView): model = Post template_name = "detail_view.html" class AddPostView(CreateView): model = Post form_class = PostForm template_name = "add_post.html" # fields = "__all__" class AddCategoryView(CreateView): model = Category fields = "__all__" template_name = "add_category.html" def CategoryView(request, categories): category_posts = Post.objects.filter(category=categories) return render(request, "categories.html", {"categories": categories}, {'category_posts': category_posts}) class UpdatePostView(UpdateView): model = Post form_class = EditForm template_name = "update_post.html" # fields = … -
Deploy Django Channels with Apache
I have a django app deployed on the internet using apache in which I would like to add one-to-one chat feature for users. I have developed the chat system using django channels but looking at the documentation isn't helping me a lot. So my question is how can I deploy it? Following is the link to the already deployed app: https://www.SearchOPal.com Thanks in advance. -
Different IP addresses in production and test environment how to handle it automaticaly
I have an app with django backend and react frontend. When testing and coding i run my django app on local server 127.0.0.1:8000 and connecting all my react requests to those endpoints. However in production my django app run on a different ip address and everytime i changed my code and push my reactjs app to production server i have to change all the endpoints ip's. What is the best way to handle it? (as a source control i use git i do not know if it makes any differences) -
Too many templates in Django
I am learning Django and I programming a CRUD for various objects. Currently I need to generate three templates per object: one for creation, one for update and one for a list. Look at how many templates I got in the picture. The process is becoming painful. What I am doing wrong and how to correct it? Thanks. -
How to show local time accorfing to the end user's local time in django?
I have to show the local time according to the endUser's timezone in Django template. I cannot get the current timezone of the end user in Django. I am using {%load tz %} but it shows error me "encountered unknown tag 'load'". What to do in this condition? how can I solve this thing? Thanks in advance. -
Got an offer as integration engineer, confused whether it is good to advance myself in data science?
I am a bit confused with job opportunities. I have been an SQL developer and have also worked on projects in python (developed a web app with flask), and occasionally with ASP.NET. My focus has been to enter the field of Machine learning and i have done courses on ML and done a few projects in kaggle and stuff. All in all i have 9 months experience with programming. My domain has been aeronautics. I got interviewed by an AI firm recently for the position of integration solutions developer with python django and flask. They deal with AI products in logistics domain. I am told that i would get a good exposure of ML as well with the team as i expressed my interests in the same field. I am a 2015 Aeronautics graduate with 3 years in production management and 9 months in SQL development (long story - production was not moving had to change jobs, hit by COVID, took up any SQL job coming my way, wanted to go for ML after leaving production.) Now i want to know whether the new job offered to me i.e. of an integration solutions developer - would that be a step … -
Why does h18 error occur when sending the wrong token to the django server hosted in heroku?
I used djangoreostframework-simplejwt to use jwt as the authentication method of my API server, and even when I hosted it to my local server and Pythonanywhere, I was able to confirm that my authentication method was working properly. But after I moved my server to heroku, when I put an expired token or an incorrect token, 503 error occurred, not a response that the token was wrong. So I took a log and got an error message like this. 2020-11-19T12:23:08.806190+00:00 heroku[router]: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/feed/post" host="our domain" request_id=f716d063-ff6a-4be7-a93c-c296909c3a9a fwd="221.168.22.204" dyno=web.1 connect=1ms service=191ms status=503 bytes=408 protocol=https I wonder if there are such bugs in heroku, django, django-rest-framework or djangoreostframework-simplejwt. If not, is there something wrong with my authentication method? Here's my code. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_SCHEMA_CLASS':'rest_framework.schemas.coreapi.AutoSchema', } views.py class customLoginView (GenericAPIView) : serializer_class = customLoginSerializer def post (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try : user = User.objects.get(email=serializer.data['email']) except User.DoesNotExist : return Response({'message': ['이메일 또는 비밀번호를 확인해주세요.']}, status=401) if user.check_password(raw_password=serializer.data['password']) == False : up = serializer.data['password'].upper() if user.check_password(raw_password=up) == False : down=serializer.data['password'].lower() if user.check_password(raw_password=down) == False : return Response({'message': ['이메일 또는 비밀번호를 확인해주세요.']}, status=401) if not user.is_verified : return Response({'message': ['이메일 … -
Django Ratelimit Not Working with UWSGI + NGINX but works with manage.py runserver
I used django-ratelimit to prevent brute-force attack to the admin login page. When I used python manage.py runserver and browsed using 127.0.0.1:8000, django-ratelimit works flawlessly. But when I started uwsgi and nginx and logined with my server IP, 192.168.31.70:8080 in my case, django-ratelimit doesn't work: there's no login limit on admin login page. I guess it's a CACHING problem, maybe I misconfigured something on uwsgi or nginx... Please help! Thanks in advance. Part of settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'import_export', 'ckeditor', 'ckeditor_uploader', 'easy_thumbnails', 'filer', #新闻管理用到了 'gbzt_coms', 'newspage', 'accounts', 'omsystem', #'config', 'administration', 'notifications', # 待办提醒功能 'statistic', 'debug_toolbar', 'rangefilter', #'django_extensions', 'ratelimit', ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'ratelimit-tests', }, } # CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 'LOCATION': '192.168.31.70:9090', # } # } # RATELIMIT_USE_CACHE = 'default' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'ratelimit.middleware.RatelimitMiddleware', ] uwsgi.ini: ;static-map = /static=var/www/static # clear environment on exit vacuum = true # ... with appropriate permissions - may be needed chmod-socket = 666 # stat server stats = 127.0.0.1:9191 #vhost = true #multi-site mode #no-site = true #no entry module/file when multi-site mode #workers = 2 #sub process … -
Customize only one column admin template
I have simple model like this class Result(models.Model): detail = models.TextField(blank=True) in_file = models.TextField(blank=True) out_file = models.CharField(max_length=2000,blank=True) pub_date = models.DateTimeField('date published',default=datetime.datetime.now()) Now I want to us <audio> tag in admin template For the first try class ResultAdmin(admin.ModelAdmin): list_display = ["in_file","show_out_file","detail","pub_date"] def show_out_file(self,obj): return "<audio>test</audio>" #return "<audio>" +obj.out_file +"</audio>" ## it doesn't work though. It shows <audio>test</autio> directly to the page, tag is parsed. Next, I think I should override the admin template. So I made this file templates/admin/base_site.html and edit. It works, I can customize the main page of admin. However how can I edit model(Result) admin page or only can I change only out_file column??? -
Running npm run build everytime before i can see the changes on my react App
I have a frontend using React and a Backend using Django. Everything was working perfectly after setting up. But I noticed after that if I didn't run npm run build I wouldn't see the changes implemented. Someone to help me with this please as it's very frustrating. -
Django: UpdateView, creating another previous image
If I change something but not imagefield in template and send it, django creating same image with another name. f.e previous_imagename_{random_generated_letters}.jpg... . Django takes previous imagename and creating same imagefile with adding some generated shortcode to previous image. If delete def save() in models it's working (not creating another one) but I need change image size before saving to database. views.py class Edit(UpdateView): model = User_data form_class = EditProfileFormExtra template_name = 'account/edit.html' slug_field = "slug" def get_success_url(self): return reverse('accounts:edit', kwargs={'slug': self.kwargs['slug']}) models.py class User_data(models.Model): username = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(upload_to = get_upload_path, default='default/profile_photo_default.jpg') def save(self,*args, **kwargs): if self.image: #Opening the uploaded image im = Image.open(self.image) if im.mode in ("RGBA", "P"): im = im.convert("RGB") output = BytesIO() w, h = im.size #Resize/modify the image if w > 1000 or h > 1000: d = w//1000 if w >= h else h//1000 else: d = 1 #Resizing im = im.resize((w//d, h//d)) #after modifications, save it to the output im.save(output, format='JPEG', quality=100) output.seek(0) #change the imagefield value to be the newley modifed image value self.image = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(User_data,self).save(*args, **kwargs) -
Override Export maximum recursion depth exceeded
When i override my method EXPORT have an recursionError. I need Break Columns and Lines in EXPORT CSV in django-import-export. Each new object on a new line. I need resolve that problem: problem_image ''' class PlanoResource(resources.ModelResource): quantidade = fields.Field(column_name='quantidade', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='quantidade')) comp = fields.Field(column_name='comp', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='comp')) larg = fields.Field(column_name='larg', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='larg')) lam_comp1 = fields.Field(column_name='lam_comp1', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='lam_comp1')) lam_comp2 = fields.Field(column_name='lam_comp2', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='lam_comp2')) lam_larg1 = fields.Field(column_name='lam_larg1', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='lam_larg1')) lam_larg2 = fields.Field(column_name='lam_larg2', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='lam_larg2')) description = fields.Field(column_name='descricao', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='description')) class Meta: model = Plano fields = ('quantidade', 'comp', 'larg', 'lam_comp1', 'lam_comp2', 'lam_larg1', 'lam_larg2', 'description',) def export(self, queryset=None, *args, **kwargs): dataset = self.export(queryset) output = [] for row in dataset: for col in row: output.append(col) # now you have a flattened list of all output return output ''' -
Apply current user filter to django-filter ListView
I'm learning how to use django-filter and ListView but I'm stuck on how to filter by current user. This my initial view: @login_required def view_techniques(request): """Show all techniques.""" techniques = Technique.objects.filter(owner=request.user).order_by('-date_added') context = {'techniques': techniques} return render(request, 'bjj_log/view_techniques.html', context) and this is my new view: @method_decorator(login_required, name='dispatch') class TechniqueListView(ListView): model = Technique template_name = 'bjj_log/view_techniques.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = TechniqueFilter(self.request.GET, queryset=self.get_queryset()) return context I'm trying to figure out how to apply something like: ".objects.filter(owner=request.user)" to my new version of the view. I will provide more information if needed but I'm assuming this should be enough. Any help will be greatly appreciated, thanks! -
error while add new record The current path, blog_app/android/add/, didn't match any of these. - django
error while add new record in admin panel it say : The current path, blog_app/android/add/, didn't match any of these. i use namecheap hosting how to fix this when i add new record and press save it show this error ... -
Optimization Django ORM
I'm running my own smart house project, using django backend with MySql on raspberry Pi.I've got SensorsData table in DB with thousands records with data from sensors. In my REST API I'm using view which looks like this: @api_view(['GET']) @permission_classes([IsAuthenticated]) def list_of_sensors_data(request, format=None): """ Get list of all sensors data, only for authenticated users :param request: GET :return: list of all sensors data if ok http 200 response """ sensors_data = SensorsData.objects.all() serializer = SensorsDataSerializer(sensors_data, many=True) return Response(serializer.data, status=status.HTTP_200_OK) I've run perfomance test with locust simulating 10 users trying to use my endpoints. After some time, Django keeps returning 504 Timeout using this particular endpoint. My quest is, how can I optimize this queryset? I need to make it faster. -
Extract information from an Excel file and normalize it in a database
I have a question, I'm trying to create in Django an application that extracts info from a Google Spreadsheet file (An Excel on Google drive) and normalizes it into a database with PostgreSQL, and I want that every so often or every time there is a change in the Google Spreadsheet file the data in that database is also updated. I don't know if there is a package or library in Django to do for data extraction, and I have a hard time understanding how to make them update the database data when the Excel file is updated. -
How to render form with errors in generic detail view
I am trying to render a generic detail view page with a form with errors My post method in my generic detail view is def post(self, request, slug): if 'submit-edit-roster' in request.POST: edit_roster_form = EditRosterForm(request.POST, team=self.request.user.playerprofile.team) if edit_roster_form.is_valid(): edit_roster_form.save() return redirect ('tcl-team', slug=self.request.user.playerprofile.team.urlslug) my edit roster form is class EditRosterForm(forms.Form): members = 0 team = None sublist = [] playerlist = [] def __init__(self, *args, **kwargs): self.team = kwargs.pop('team', None) self.members = 0 self.sublist = [] self.playerlist = [] super(EditRosterForm, self).__init__(*args, **kwargs) currentroster = Roster.objects.filter(team=self.team)[0] for member in Playerprofile.objects.filter(team=self.team).order_by('name'): if member in currentroster.players.all(): self.fields[str(member.name)] = forms.ChoiceField(choices=ROSTER_CHOICES) self.initial[str(member.name)] = '1' elif member in currentroster.subs.all(): self.fields[str(member.name)] = forms.ChoiceField(choices=ROSTER_CHOICES) self.initial[str(member.name)] = '2' self.members += 1 def clean(self): cleaned_data = super().clean() i = 0 for member in Playerprofile.objects.filter(team=self.team): if cleaned_data[member.name] == '1': self.playerlist.append(member) elif cleaned_data[member.name] == '2': self.sublist.append(member) i += 1 print(len(self.sublist)) if len(self.sublist) > 2: raise ValidationError("Maximum of 2 subs allowed") if len(self.playerlist) > 5: raise ValidationError("Maximum of 5 players allowed") if len(self.playerlist) + len(self.sublist) > i: raise ValidationError("Team members must be a sub or a player") return cleaned_data def save(self): cleaned_data = self.cleaned_data print(cleaned_data) UpdateRoster(roster=self.team.GetCurrentRoster(), players=self.playerlist, subs=self.sublist) When my form has errors I get The view team.views.TeamEditView didn't return an HttpResponse object. …