Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
spinner not show after submit the button
when i will submit the form data without any error than spinner showing... but when the form have some error (like username is required) and after submit the form than spinner not showing... <script type="text/javascript"> var spinner = $('#loader'); $(document).on('submit', '#payment-form', function(e){ e.preventDefault(); spinner.show(); $.ajax({ type: 'POST', url: "{% url 'post_create' %}", data: { title: $('#id_title').val(), ages: $('#id_ages').val(), zip_codes: $('#id_zip_codes').val(), address_user: $('#id_address_user').val(), phone: $('#id_phone').val(), state: $('#id_state').val(), city: $('#id_city').val(), category: $('#id_category').val(), description: $('#id_description').val(), photo_main: $('#id_photo_main').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, error:function('#card-element'){ spinner.fadeOut(); }, success:function(data){ spinner.fadeOut(); } }); }); </script> -
Django: Comment Section under each post? Two models, one template
I am trying to make a Social Media Platform as a way to better understand Django, and am stuck on the commenting section. I would like to have a comment section, under each post that a user creates. However, I am struggling with handling multiple models on one template. I am not sure where to go from here, and any direction/advice would be appreciated. #views.py class Text_List(LoginRequiredMixin, ListView): model = Text_Post template_name = 'main1/includes/h_post.html' context_object_name = "posts" def get_context_data(self,**kwargs): data = super().get_context_data(**kwargs) return data class Text_Post_P(LoginRequiredMixin, CreateView): model = Text_Post fields = ['T_Post_content'] template_name = 'main1/h_platform.html' def form_valid(self,form): form data has be stated form.instance.T_Post_author = self.request.user return super().form_valid(form) class Commenting_P(CreateView): model = Commenting fields = ['Comment_content'] template_name = 'main1/includes/comment.html' #Not sure what to put here. #models class Text_Post(models.Model): T_Post_content = models.CharField(max_length = 200,verbose_name = "") T_Post_published = models.DateTimeField(default = datetime.now) T_Post_author = models.ForeignKey(User, on_delete = models.CASCADE, default = None, null = True) T_Post_likes = models.IntegerField(default=0) def __str__(self): return self.T_Post_content[:10] class Meta: ordering = ('-T_Post_published',) class Commenting(models.Model): Comment = models.ForeignKey(Text_Post, on_delete = models.CASCADE,related_name="comments", blank = True, null = True) Comment_author = models.CharField(max_length = 100, default = None, null = True, blank = True) Comment_content = models.TextField(default = None) Comment_published = models.DateTimeField(default … -
Django Admin Change List Queryset
I'm adding a total row to django admin following the response here: SO answer. I'm not allowed to show the individual costs on a column, so I can't use django admin totals library or django totalsum, because they require the column to be on list_display. The problem I'm having is that I need to filter or exclude by pay_type but when I try to write the query I get: assert not self.query.is_sliced, AssertionError: Cannot filter a query once a slice has been taken. How can I make this work with a filter? Admin.py - I tried: class MyChangeList(ChangeList): def get_results(self, *args, **kwargs): super(MyChangeList, self).get_results(*args, **kwargs) b_queryset = self.result_list.exclude(cost__paytype_id = 3) b = b_queryset.annotate(total_executed_hours= Sum('cost__bill_hours')) self.executed_hours = b['total_executed_hours'] Also tried: b = self.result_list.exclude(cost__paytype__id = 3)\ .aggregate(total_executed_hours=Sum('cost__bill_hours')) I tried a bunch of other combinations. How can I make this work? Thanks! -
Search bar no content is returned
Hey i am new to Django and I am trying to make a search bar to my first site. My problem here is when I search for any value that I/user entered and on the site, the site only refreshes and doesn't give me anything back but the empty option that i gave the site to display when there is no content to match the search. (That's not all of the Topic model) model.py class Topic(models.Model): content = models.CharField(max_length=200) views.py def search(request): query = request.GET.get('q') if query: result = Topic.objects.filter(content__icontains=query) context = { 'query': query, 'result': result} return render(request, 'learning_logs/topics.html', context) ( That's not all of the topics.html if it help to show all the page i can also put all of the code) topics.html {% block content %} <form method="GET" action="{% url 'learning_logs:search' %}"> {% csrf_token %} <input name="q" value="{{ request.GET.q }}" placeholder="search.."> <button class="btn btn-primary" type="submit"> Search</button> </form> {% for topic in topics %} ...... {% empty %} <h3><li>No topics have been added yet.</li></h3> {% endfor %} {% endblock content %} -
How can I remove folder's name and add www to domain on my .htaccess using .fcgi file?
I'm having trouble figuring out my .htaccess in a shared host for days now because I must keep the index.fcgi, otherwise my django project doesn't work. I'm trying to remove a folder named app from my URL and also make sure that when someone types www.domain.com it goes to my page. I already checked the CNAMEs from my domain and www.domain.com is there, but it doesn't go through with the pages inside my project, only if I type domain.com My .htaccess file: (I must keep the index.fcgi) AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] My index.fcgi file: #!/usr/bin/scl enable rh-python35 -- /home/CONTA/.virtualenv/bin/python import os, sys from flup.server.fcgi import WSGIServer from django.core.wsgi import get_wsgi_application sys.path.insert(0, "/home/CONTA/mydjangoproject") os.environ['DJANGO_SETTINGS_MODULE'] = "mydjangoproject.settings" WSGIServer(get_wsgi_application()).run() Thanks a lot in advance! -
Validating access_token against Azure AD coming from ReactJS
The crux of all the below is this: how do I validate an Azure AD access_token from the Django/DRF API sent to it from the ReactJS FE? My web application is a microservice setup, so completely distinct services between the FE and API. The Django/DRF API serves no static assets and should only be accessible via the FE and the data it is authenticated to consume from it. I have the ReactJS FE successfully getting an access_token from Azure AD and my tenant using react-aad. (Note: This based on msal v1.0 which will be replaced by @azure/msal-react using msal v2.0 hopefully this month at some point). Now I just need to send it to the API where it is validated against Azure AD. This has been a real struggle finding something that works or that is documented well enough. I've tried the following, but ultimately hit this issue with all of them that I can't seem to figure out: social-auth-app-django django-rest-framework-social-oauth2 drf-social-oauth2 This article At any rate, can't get those working properly so now I'm playing with libraries developed by Microsoft: azure-activedirectory-library-for-python... I guess this is deprecated and the next one should be used. Not sure how this correlates to … -
question about "attributes" attribute of a class
This is probably a simple question but I'm wondering why it seems attribute names and values are reversed in the following example: >>> class SelectOne(DjangoChoices): ... cola = ChoiceItem("c", "Coca Cola") ... beer = ChoiceItem("b", "Heineken") ... >>> SelectOne <class 'SelectOne'> >>> SelectOne.attributes OrderedDict([('c', 'cola'), ('b', 'beer')]) >>> for k, v in SelectOne.attributes.items(): ... print (k, v) ... c cola b beer Common understanding should be that "cola" is the key and "c" is the value. where can I find the documentation of "attributes" attribute of a class? -
Configure gunicorn.service with Docker and Django
For the context of my project Currently I am trying to containerize my django app with docker. What goes well are: different services: db, web, nginx can be built and up in my local. The error is The django app seems like cannot find my gunicorn socket file. Here is the exact error: nginx_1 | 2020/11/06 21:07:40 [crit] 6#6: *2 connect() to unix:/run/gunicorn.sock failed (2: No such file or directory) while connecting to upstream, client: 172.27.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "0.0.0.0:1337" nginx_1 | 172.27.0.1 - - [06/Nov/2020:21:07:40 +0000] "GET / HTTP/1.1" 502 576 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36" "-" This is my nginx config file: # define the web service server as upstream upstream web-service { # should use web:8000 rather than the localhost:8000 etc server web:8000; } # for db #0.0.0.0 localhost 157.230.227.115 qmrealestate.co www.qmrealestate.co; server { listen 80; #server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /app/Django-RealEstate; } location /media/ { root /app/Django-RealEstate; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/gunicorn.sock; } } This is my docker-compose.prod.yml … -
object_id in ContentType
I can't seem to find some explanation how to set the field object_id in either the documentation here or this very helpful post here. Since this field is compulsory, how is it set by Django during runtime? If I want to set it from within admin, what caution, if any, should I be taking? Is it supposed to be related to the pk of the related model somehow or is it purely a unique integer that I can just set? Thanks. -
Django Custom Permission method or decorator
I am many views and more than one user type. I want some views that can be seen by specific user types and other users cant see this. For example, only company see this views and for this i did that like this below: @login_required def only_company_can_view(request): if not Company.objects.filter(owner_id=request.user.id).exists(): return HttpResponse('Permission Denied. Only Company can see this') # > rest of the logic return render(request, 'template.html') and above this working very well and solves my problem but i don't like this. coz, i don't want to write every time for the rest of the views for the company related views. So i am finding a solution so that i can use decorator or something else that are best practice Can anyone help me in this case? -
Django OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
I am trying to run an opensource project in my computer. But I am getting this error. Please experienced a person share your thought. I don't understand how I can solve this issue. I am using python 3.6 and django 2.X version. Traceback (most recent call last): File "C:/Users/Asus/Desktop/Fiverr/vulunteer/manage.py", line 37, in <module> execute_from_command_line(sys.argv) File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 598, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 583, in start_django reloader.run(django_main_thread) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 301, in run self.run_loop() File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 307, in run_loop next(ticker) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 347, in tick for filepath, mtime in self.snapshot_files(): File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 363, in snapshot_files for file in self.watched_files(): File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 262, in watched_files yield from iter_all_python_module_files() File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 139, in iter_modules_and_files if not path.exists(): File "C:\Python37\lib\pathlib.py", line 1346, in exists self.stat() File "C:\Python37\lib\pathlib.py", line 1168, in … -
Can I dynamically do a bulk update on a JSON field while referencing a model field?
I am caching some data on my model and this is essentially what I'd like to achieve. Person.objects.all().update(my_links={first_link='https://first_url/{id}'.format(id=F('id'))}) The result I get is: { "first_link": "https://first_url/F('id')" } -
Modeling favorites in Django from two different models
I have a Netflix clone app that I am creating and I am having difficulty with the models. I have a Movie model that has fields for the movie such as a title, duration, rating, etc. I am not sure how I should model my database but what I believe I should be doing is a ManyToMany relationship, such as, a user can favorite many movies and a movie can be favorited by many users. However, if I do it like this I feel that I would end up with a Favorites table that would have many users and movies and possible see this as an issue having to go through each row to find the current user rather than doing maybe a OneToMany relationship, such as, a user can favorite many movies and a movie can be favorited by a user. So first, I am not sure what the proper way of modeling this would be. I also do not know how to add this relationship to my user model because I am using the User model that I brought in from django.contrib.auth.models I am having a lot of trouble trying to think of a solution for this and … -
css + xhtml2pdf : force only one table per page
trying to output one table per page in a pdf document generated with xhtml2pdf. Nothing in the doc really explains how to achieve this and front end stuff is not my strong suit here is what I got so far: {% load static %} <!DOCTYPE html> <html> <head> <style> @page { @frame header_frame { /* Static Frame */ -pdf-frame-content: header_content; left: 50pt; width: 512pt; top: 50pt; height: 200pt; } size: a4 portrait; @frame content_frame {/* Content Frame */ left: 50pt; width: 512pt; top: 230pt; height: 700pt; } } table { width:100%; } table.print-friendly tr td, table.print-friendly tr th { page-break-inside: avoid; } table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 2px; text-align: left; } table#t01 tr:nth-child(even) { background-color: #eee; } table#t01 tr:nth-child(odd) { background-color: #fff; } /* table#t01 th { background-color: black; color: white; } */ body{ font-size: 12px; } h1,h2,h3,h4,h5,h6,p{ padding: 0; margin: 0; } img{ float: left; } </style> </head> <body> <div id="header_content"> <th colspan="5" style="text-align: center;"> <div style="text-align: left"> <h3></h3> <p style="padding-bottom: 2px; margin: 0; font-size: 20px;">{{ my_company.name }}</p> <p style="padding-bottom: 2px; margin: 0; font-size: 10px;">{{ my_company.address }}</p> <p style="padding-bottom: 2px; margin: 0; font-size: 10px;">{{ my_company.city }}, {{ my_company.zip_code }}</p> … -
Pulling data from Django database and populating lists for user input
I'd like to preface this with first - thank you for anyone willing to listen to my question - it may be a bit complex and second I'm very new to web development so I'm sorry if I sound dumb. I'm making a website that essentially allows admins (Professors) to input courses based on specific majors, and allows users (Students) to select what courses they've taken so far - and based on that input - display what courses they must still take to complete their degree. In the Django admin page - it allows admins to create courses offered and one of the parameters is the major affiliated with the specific course. I then want the users (Students) to be able to select one of the majors (there are nine) - and dependent on what major they select - choose from the available courses provided affiliated with that major. After the user selects what courses they've taken it would redirect them to a page that displays all the remaining courses they must take. My question is, how do I take the data inputted by the admins, and based on the major they provide - send that data to a major … -
TypeError: 'class Meta' got invalid attribute(s): constraints
I have a project in django and when I try to do the migrations it sends me the following error: File "C:\andon\f2candon\venv\lib\site-packages\django\db\models\options.py", line 195, in contribute_to_class raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) TypeError: 'class Meta' got invalid attribute(s): constraints The code segment where the error sends me is the following, in the file options.py: # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) -
Django and requirejs issue
i have link problem, i can't link Require js in Django webs app. this is the HTML link: <script data-main="static/assets/js/app" src="static/assets/vendor/require/require.js"></script> and this is Function call: <script> require(['app'], function () { require(['modules/menu']); }); </script> this is the Requirejs code: "use strict"; //scripts availabel require.config({ baseUrl: 'static/assets/', paths: { //PLUGINS 'jquery': 'vendor/jquery/jquery.min', 'plugins/modernizr': 'vendor/modernizr/modernizr', 'plugins/bootstrap_v3': 'vendor/bootstrap/v3/js/bootstrap.min', 'plugins/slick': 'vendor/slick/slick.min', 'plugins/progress': 'vendor/progress/dist/circle-progress.min', 'plugins/magnificPopup': 'vendor/magnificPopup/dist/jquery.magnific-popup.min', 'plugins/bridget': 'vendor/jquery/jquery-bridget', 'plugins/isotope': 'vendor/isotope/isotope.pkgd.min', 'plugins/datePicker': 'vendor/datePicker/js/datepicker', //MODULES 'modules/main': 'js/modules/main', 'modules/player': 'js/modules/player', 'modules/progress': 'js/modules/progress', 'modules/upload': 'js/modules/upload', 'modules/userToggle': 'js/modules/user-toggle', 'modules/menu': 'js/modules/menu', 'modules/statistic': 'js/modules/statistic', 'modules/posts': 'js/modules/posts', 'modules/googleCharts': 'js/modules/google-charts', 'modules/datePicker': 'js/modules/datepicker', }, shim : { //PLUGINS 'plugins/modernizr': { exports: 'Modernizr' }, 'plugins/bootstrap_v3': { deps: ['jquery'], exports: 'Bootstrap' }, 'plugins/datePicker': { deps: ['jquery'], exports: 'datePicker' }, } }); The HTML File in -> home/templates/index.thml The Requirejs Files in -> root/static/assets/js/* -
Is there any function to count a particular choice field from feedback model in django?
I am new to Django framework: The model Feedback I have created is this: class Feedback(models.Model): customer_name = models.CharField(max_length=120) email = models.EmailField() Place = models.CharField(max_length=120) Area_Type = models.ForeignKey(Product, on_delete=models.CASCADE) Electricity = models.CharField(max_length=3, choices=[('1','Excellent'),('2','Good'),('3','Bad')]) Water_Supply = models.CharField(max_length=3, choices=[('1', 'Excellent'), ('2', 'Good'), ('3', 'Bad')]) details = models.TextField() Satisfactory_locality = models.BooleanField() date = models.DateField(auto_now_add=True) From this I want to count number of feedback choices are Excellent for Electricity field. Please also tell about how to view this count. -
Rendering to Home Page when a Slug is not available (DJANGO)
I have created a webpage where an admin can create random pages via admin page using slug adding the name into the slug field. What I am trying to do is if a user tries to render to random page it should to go a "404" page. Model class CustomPage(models.Model): title = models.CharField(max_length=20, blank=True) subtitle = models.CharField(max_length=50, blank=True) slug = models.SlugField(max_length=500,blank=True) content = RichTextField() displayOnFooter = models.BooleanField(default=False) def __str__(self): return f'{self.title}' def get_absolute_url(self): return reverse('custom-page', kwargs={'slug': self.slug}) views.py def custom_page(request, slug): context = { 'all': CustomPage.objects.filter(slug=slug), 'toBePublished': CustomPage.objects.all() } all_querry = CustomPage.objects.all() count = 0; for i in all_querry: if i.slug == slug: return render(request, 'member/custom_page.html', context) elif count < len(all_querry): count += 1; else: return render(request, 'member/home.html',context) urls.py path('register/', views.register, name='member-register'), path('login/', auth_views.LoginView.as_view(template_name='member/login.html'), name = 'login'), path('logout/', auth_views.LogoutView.as_view(template_name='member/logout.html'), name = 'logout'), path('forgot-password/', auth_views.PasswordResetView.as_view(template_name='member/forgot-password.html'), name = 'member-forgot-password'), path('profile/', views.profile, name = 'profile'), path('accounts/login/', auth_views.LoginView.as_view(template_name='member/login.html')), path('groups/', views.groups, name='member-group'), path('groups/<slug:slug>/', views.groups_detail, name='member-group-detail'), path('<slug:slug>/', views.custom_page, name='custom-page'), When I add a random string myself at the end so for example: http://127.0.0.1/dasada/ I get a ValueError at /dasada/ The view member.views.custom_page didn't return an HttpResponse object. It returned None instead. Thanks Onur -
ImportError: cannot import name 'docker_config' from 'geodjango'
I have a settings.py file that I must add the following whitenoise code to it. Whitenoise is just simplifying the deployment of static files for my django application. import socket STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" if socket.gethostname() =="your_laptop_hostname_goes_here": DATABASES["default"]["HOST"] = "localhost" DATABASES["default"]["PORT"] = docker_config.POSTGIS_PORT else: DATABASES["default"]["HOST"] = f"{docker_config.PROJECT_NAME}-postgis" DATABASES["default"]["PORT"] = 5432 # Set DEPLOY_SECURE to True only for LIVE deployment if docker_config.DEPLOY_SECURE: DEBUG = False TEMPLATES[0]["OPTIONS"]["debug"] = False # ALLOWED_HOSTS = ['.your-domain-name.xyz', 'localhost',] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True else: DEBUG = True TEMPLATES[0]["OPTIONS"]["debug"] = True ALLOWED_HOSTS = ['*', ] CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False I also have to create a docker_config.py file with a boolean variable which I have done so. I try to import the file to my settings.py using: from geodjango import docker_config And I get the described error in the title after I run: python manage.py migrations My project folder looks like this: -
Django pass object to model of antother form
I have implemented a python form/view/template that lets you configure different notifications for a product: models.py class PNotification(models.Model): add = models.BooleanField(default=False, help_text='Receive messages when an engagement is added') delete = models.BooleanField(default=False, help_text='Receive class Product(models.Model): forms.py class PNotificationForm(forms.ModelForm): class Meta: model = PNotification exclude = [''] class ProductForm(forms.ModelForm): The PNotification has an own view and template: <h3> Edit Notifications for {{ product.name }}</h3> <form class="form-horizontal" method="post">{% csrf_token %} {% include "dojo/form_fields.html" with form=form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input class="btn btn-primary" type="submit" value="Submit"/> </div> </div> </form> When I call the page (edit/product_id/notifications) to edit an products notifications, the h3 is set correct, so the product is passed to the form/template. My problem is: I need to link PNotification with a product. Can someone help me to pass product.id to my PNotificationForm so I can save it there? This field should be the primary key of PNotification. Thanks a lot :) -
Django User Registration Authentication Problem
Please I am new to Django and user registration is giving me serious headache. The UserCreationForm displays on the page but does not display any errors even when I deliberately pass in wrong and submit passwords.It just refreshes. It does not show errors like password too short etc unlike the login page. Urls.py for Main Project from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/',include('django.contrib.auth.urls')), path('',include('account.urls')), ] Urls.py for account_app from django.urls import path from .views import home,register urlpatterns = [ path('',home,name='home'), path('register/',register,name='register'),] Views.py for account_app from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate,login def home(request): return render(request,'base.html') def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user =authenticate(username=form,password=password) login(request,user) return redirect('home') else: form = UserCreationForm() form = UserCreationForm() return render(request,'registration/register.html',{'form':form}) Template folder looks like this +templates +registration +register.html Register.html code <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Register</title> </head> <body> <h1>Registration Page</h1> <form method="POST" action="{%url 'register' %}"> {%csrf_token %} {% if form.errors %} <p>There are errors in the form </p> {% endif %} {{form}} <button type="submit" name="button">Submit</button> </form> </body> </html> -
Ranking system with ForeignKey in Django
I want to have ranking for university model. There can be several ranking types for each university. Admin should be able to add and delete the ranking type and score as needed. For example: Harvard will have 3 different rankings and different scores in those rankings. But X University will have none. But some other university can have totally different ranking type and more than three. Universities should be filterable according their score in each ranking type. I tried this: class University(models.Model): title = models.CharField(_("title"), max_length=250) about = models.CharField(_("about"), max_length=450) logo = models.CharField(_("logo"), max_length=150) ranking = models.ManyToManyField("program.Ranking") def __str__(self): return self.title class Meta: verbose_name_plural = 'Universities' class Ranking(models.Model): title = models.CharField(_("Title"), max_length=250) scope = models.ForeignKey("program.Scope", on_delete=models.DO_NOTHING) score = models.IntegerField(_("Score")) def __str__(self): return f'{self.title} {self.score}' class Scope(models.Model): title = models.CharField(_("Title"), max_length=350) def __str__(self): return self.title I see it as not well-optimized (because of repetitiveness) and think there should be better way of doing it. Is there better way of doing it? If yes, please add some code and give explanation why it is better idea than mine. -
Is there a way to disable some checkboxes through django view?
In a MultilpleChoiceField form, I'm trying to let enabled only some fields. For example, the customer will send the name that he want to search in the database, after that, I would like that the form bellow shows checked and enabled only the checkboxes where were found information about the customer. #forms.py class ResultadoForm(forms.Form): TRIBUNAIS_FEDERAIS_CHOICES = ( ('trf1', 'Tribunal Regional Federal da Primeira Região'), ('trf2', 'Tribunal Regional Federal da Segunda Região'), ('trf3', 'Tribunal Regional Federal da Terceira Região'), ('trf4', 'Tribunal Regional Federal da Quarta Região'), ('trf5', 'Tribunal Regional Federal da Quinta Região'), ) tribunais_federais = forms.MultipleChoiceField( choices=TRIBUNAIS_FEDERAIS_CHOICES, widget=forms.CheckboxSelectMultiple ) TRIBUNAIS_JUSTIÇA_CHOICES = ( ('tjes', 'Tribunal de Justiça do Espírito Santo'), ('tjmg', 'Tribunal de Justiça de Minas Gerais'), ('tjrj', 'Tribunal de Justiça de Rio de Janeiro'), ('tjsp', 'Tribunal de Justiça de São Paulo'), ) tribunais_estaduais = forms.MultipleChoiceField( choices=TRIBUNAIS_JUSTIÇA_CHOICES, widget=forms.CheckboxSelectMultiple ) I'm trying to do that in the views.py: class ResultadoView(LoginRequiredMixin, FormView, TemplateView): template_name = 'resultado.html' form_class = ResultadoForm success_url = "resultado.html" def get(self, request, *args, **kwargs): cnpjs = request.session['lista'] # cnpjs = pd.read_json(cnpjs) current_user = request.user print(current_user.id, current_user.first_name) form = self.form_class(initial=self.initial) a = pd.read_html(form.as_table()) print(a) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): return render(request, … -
Trying to upload CSV for testCase and getting " MultiValueDictKeyError: "'file'""
trying to upload my csv for testing and I keep getting " MultiValueDictKeyError: "'file'" Not sure what I am doing wrong here. def test_import_existing_order(self): data = File(open('TestCSV - OrderTest.csv', 'rb')) upload_file = SimpleUploadedFile('data.dump', data.read(),content_type='multipart/form-data') request = self.seller_client.put( IMPORT_ORDERS_URL, {'file':upload_file,}, format="multipart", content_disposition="attachment; filename=data.dump") def importOrdersToDict(request): import csv line_count = 0 response_data = {"orders":{}, "orderCount":0, "dropOffLocations":0, "totalCases":0, "locations":{}, } csv_file = request.FILES['file'] csv_file.seek(0) csv_reader = csv.DictReader(csv_file)