Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change span value inside dynamically rendered table with Django using AJAX response
So I have a website with Django. I have a products page that when I add to cart that specific item using a "Add to Cart" button, the item gets added as an order item based on the item primary key. Now I have a Cart page where I can view the specific products that are already an order item this is dynamically rendered using this piece of code: My cart.html page <tbody> {% for order in orders %} <tr> <th scope="row"> <div class="order-quantity"> <span id="order_quantity">{{order.quantity}}</span> <button data-url="{% url 'add' order.id %}" class="edit-quantity" id="plus">+</button> <button data-url="{% url 'subtract' order.id %}" class="edit-quantity" id="subtract">-</button> </div> </th> <td><img src="{{order.item.product_image.url}}" alt="" width="70" height="70"></td> <td>{{order.item.product_name}}</td> <td> <span>&#8369;</span> {{order.total_item_price}}</td> </tr> {% endfor %} </tbody> Now notice that I have an add quantity button with a data url because I wanted to change the span quantity automatically with AJAX response. Now I figured out how to console log the specific quantity when an order item is clicked for example if I click on the order item Nike, on my console I will see the order quantity but I can't figure out how to change the span text because it is dynamically rendered. Please help! my Cart page … -
Variable image paths in xhtml2pdf with django
I need to display images with variable path, because, the user input's the image.. If I provide a url like <img height='200px' src="http://127.0.0.1:8000/media/images/photo.jpeg" alt="Image of student"> it works, but then, it does not work when I change it to <img src="{{ result.image_of_student.url }}" alt="Image of student"> How do I make this work, as each url is different. In the tutorial, they used <img src={{ result.image_of_student.path}} alt="Image of student"> which worked for them but not for me -
why does heroku server does not play my mp4 video
here i am using Django in backend. on my local machine there is not an problem but when i upload it on Heroku it shows all the files but video is messing.? <video width="540" autoplay muted loop> <source src="{% static 'home/img/Inbodyshot.mp4' %}" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video> -
Select all fields except one Django
There is a class-based view and I want to know how I can use all fields except the user field in the fields instead of '__all__' and also I don't want to write all the fields in a list because there are too many fields and I want to exclude one item. here is the code: class TaskCreate(LoginRequiredMixin, CreateView): model = Task fields = '__all__' # ! here success_url = reverse_lazy('Tasks') def form_valid(self, form): form.instance.user = self.request.user return super(TaskCreate, self).form_valid(form) many thanks in advance. -
How to zip dynamically generated pdfs using weasyprint then returning it as a response in django?
Here is my view to generate a pdf: def download_pdf(request, id): document = Document.objects.get(id=id) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=document_name.pdf' response['Content-Transfer-Encoding'] = 'binary' html_string=render_to_string('portal/pdf/document.html', {'document': document}) html = HTML(string=html_string, base_url="/") result = html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response Now how do I generate multiple pdfs when I decide to Document.objects.filter(some parameter) then sending it as a zip? -
How can I add an extra property to django-rest-framework's ModelSerializer?
I am creating my first django API with django-rest-framework. I have a list of Posts. Each post can have many Likes. Therefore, I have added a ForeignKey to the Like model, which points to its corresponding Post. When I retrieve the information of a post, I'd like to get the number of likes that this post has. Here is my url: path(BASE_URL + "get/slug/<slug:slug>", GetPost.as_view()), This is my view: class GetPost(generics.RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostSerializer lookup_field = "slug" And this is my serializer: class PostSerializer(serializers.ModelSerializer): likes_amount = serializers.SerializerMethodField(read_only=True) def get_likes_amount(self, post): return post.likes class Meta: model = Post fields = '__all__' Unfortunately, as soon as I add the extra property likes-amount to the serializer, the API endpoint stops working and I get the following error: Object of type RelatedManager is not JSON serializable. I'd like to know how I can extend the ModelSerializer with extra fields like the number of likes of my Post, so that I can get. I have read the documentation but haven't found any information on that topic. -
JavaScript function not working on form submission
I've got an HTML form, and when it is submitted, I want a JavaScript function I have defined to run. However, no matter what, the function I've written is not recognised. Here is the HTML form: <form id="compose-form"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" class="btn btn-primary"/> </form> And then here is my JavaScript code: document.addEventListener('DOMContentLoaded', function() { // #compose is the id of the div the form #compose-form is in document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('#compose-form').addEventListener('submit', () => send_email(event)); }); function send_email(event) { event.preventDefault(); // Note this isn't the actual content of my function, but even this simple code doesn't work alert('Hello'); return false; } function compose_email() { document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Note: this function does work completely. document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; } WHAT I'VE TRIED: I've moved the functions above the event listener in my JavaScript I've alternately removed both the event.preventDefault(); and the return false;, removed both, kept both. I've tried defining the function separately, as I have it here, and doing the code as an anonymous function I've … -
Django image file uploading from URL: django.security.SuspiciousFileOperation.response_for_exception (99) Detected path traversal attempt
I am using Django 3.2 I want the user profile images to be partitioned in the following manner: MEDIA_ROOT /users /profile image.jpg I am allowing users to create a profile, and the profile image is retrieved from a URL. I am able to extract the file from the URL and save it into a temporary file locally, and then to load the binary contents into the ImageFile field. However, I am getting a django.security.SuspiciousFileOperation.response_for_exception error being raised. This is the error message I get: django.security.SuspiciousFileOperation.response_for_exception (99) Detected path traversal attempt in /path/to/user/profile/image This is the code I have so far (imports excluded for brevity): models.py def get_upload_path(instance, filename): user_profile_image_dir = f"{settings.MEDIA_ROOT}/users/profile" #os.makedirs(user_profile_image_dir, exist_ok=True) # Is it ok to dynamically create sub directories under MEDIA_ROOT? return os.path.join(user_profile_image_dir, filename) class MyUser(AbstractUser): profile_pic = models.ImageField(null=True, blank=True, upload_to=get_upload_path) def save_image_from_url(image_field, url): with requests.get(url) as response: assert response.status_code == 200 content_type = response.headers.get('content-type') if 'image' in content_type: file_ext = content_type.split('/')[-1] img_tmp = NamedTemporaryFile(suffix=f".{file_ext}", delete=True) img_tmp.write(response.content) img_tmp.flush() img = File(img_tmp) file_basename = os.path.basename(img_tmp.name) image_field.save(file_basename, img) else: # Not an image file pass I have two questions: Why is the exception being raised, and how can I get rid of it, so that I can load the … -
employee/job/create/ 'str' object is not callable
I don't know where to look for this error in my code: views.py: from django.views.generic import ListView, CreateView, DeleteView, DetailView, UpdateView from .models import Employee,Event,detailEvent,Department, Poste from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse, reverse_lazy # ----------------------------------------------------- Views for postes. class PostelistView(LoginRequiredMixin, ListView): template_name = "postes/post_list.html" context_object_name = "Poste" def get_queryset(self): # initial queryset of leads for the entire organisation queryset = Poste.objects.all() return queryset class PosteCreateView(LoginRequiredMixin, CreateView): template_name = "postes/post_create.html" form_class = "Poste" def get_success_url(self): return reverse_lazy("employee:post_list") def form_valid(self, form): instance = form.save(commit=False) instance.save() self.Poste = instance return super(PosteCreateView, self).form_valid(form) my models.py from django.utils.translation import ugettext_lazy as _ class Poste(models.Model): intitule = models.TextField(_("Name"),max_length=250, default='') Where is a str is called ? error seems ending with: File "/Users/PycharmProjects/gusta/venv/lib/python3.8/site-packages/django/views/generic/edit.py", line 33, in get_form return form_class(**self.get_form_kwargs()) TypeError: 'str' object is not callable -
Django Hashids - Override 3rd Party Serializer
I'm fairly new to Django and I'm experimenting with Hashids in a new project. I'm using django-hashid-field, django-rest-framework, django-allauth, and dj-rest-auth. I've added DEFAULT_AUTO_FIELD = 'hashid_field.HashidAutoField' to settings.py in order to generate hashids for all the models, and I've explicitly declared the primary keys and PrimaryKeyRelatedFields in my serializers as per django-hashid-field documentation. Everything is running fine except when I run the following command docker-compose exec web python manage.py generateschema > openapi-schema.yml to generate the schema, I get this error: File "/usr/local/lib/python3.8/site-packages/hashid_field/rest.py", line 14, in bind raise exceptions.ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: The field 'pk' on UserDetailsSerializer must be explicitly declared when used with a ModelSerializer I've tried to override UserDetailsSerializer in accounts.serializers.py with no luck. After going through the dj-rest-auth package to find UserDetailsSerializer I've tried: from dj_rest_auth.serializers import UserDetailsSerializer class UserDetailsSerializer(UserDetailsSerializer): pk = HashidSerializerCharField( source_field='dj_rest_auth.serializers.UserModel.pk') I get this error: File "/usr/local/lib/python3.8/site-packages/hashid_field/rest.py", line 35, in __init__ raise ValueError(self.usage_text) ValueError: Must pass a HashidField, HashidAutoField or 'app_label.model.field' My files: # accounts.models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models import uuid from django.core.validators import RegexValidator, MaxLengthValidator class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise … -
How to perform more/less than filter based on user choice using django-filter
I'm building an app using Django and django-filter. In the DB I have a table with a column named TOTALOFFERAMOUNT, it has integer values (I'm using -1 value to represent that this total offer amount is indefinite) Now for filtering, I use django-filter to filter results based on three fields, one of them is TOTALOFFERAMOUNT. I want to give the possibility that the user when enters a value for TOTALOFFERAMOUNT can decide if he wants the results to be less than or more than or 'Indefinite' Like the picture below: So I want to know how can I implement this. -
Installing 3 Django applications on a shared web server trough cPanel
I am trying to install my applications on a shared web server running phusion Passenger but after a week I am still unable to complete this "simple" task. I wrote a working Django application and now I hae to upload it on my shared web server so I wrote this simple passenger_wsi.py file: #--------------------------------------------------------------------------- # \file passenger_wsgi.py # \brief # # \version rel. 1.0 # \date Created on 2021-05-16 # \author massimo # Copyright (C) 2021 Massimo Manca - AIoTech #--------------------------------------------------------------------------- from DjHello.wsgi import app application = app and this is my DjHelloWorld.wsgi : """ WSGI config for DjHello project. It exposes the WSGI callable as a module-level variable named app. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ #!/opt/alt/python38/bin/python3.8 import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') app = get_wsgi_application() -
Hello, guys. I trying to run my first app in Django, have followed all instructions but isn't working, don't know where is the problem
Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(file).resolve().parent.parent Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-u%xm5q1bi(6t8iretu5s8(sv(0=ip!x-qk7wu1&ef=bhl^2i' SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] Application definition INSTALLED_APPS = [ 'hello', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Markdowned content not reflected in my html template (<em><strong>)
In my Django project, I am using markdownify to convert my markdown to HTML. I have a problem while rendering the HTML content to my template. some tags like <em>, <strong> are not getting reflected. I have tried using the safe filter as suggested in this stackoverflow post but I find no changes! Is there any other filter I can use or any method to render correctly in settings.py MARKDOWNIFY = { "default": { "STRIP": True, "BLEACH": True, "MARKDOWNIFY_LINKIFY_TEXT": True, "WHITELIST_TAGS": [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'em', 'i', 'li', 'ol', 'p', 'strong', 'ul' ], "WHITELIST_ATTRS": [ 'href', 'src', 'alt', ], "WHITELIST_STYLES": [ 'color', 'font-weight', ], "LINKIFY_TEXT": { "PARSE_URLS": True, "PARSE_EMAIL": True, "CALLBACKS": [], "SKIP_TAGS": ['pre', 'code',], }, "WHITELIST_PROTOCOLS": [ 'http', 'https', ], "MARKDOWN_EXTENSIONS": [ 'markdown.extensions.fenced_code', 'markdown.extensions.extra', ] }, } in my template: <div class="col-8"> {{ entry|markdownify|safe }} </div> the content: #This is the H1 tag for Heading but these are working - paragraph - all the headers - list tag things not getting converted - *Italics not working* - **And also bold text** In my template,this is what i get This is the H1 tag for Heading but these are working paragraph all the headers list tag things not … -
Django Celery Recursive Error With tasks.py, Not With views.py
I've created a recursive function to get all children of a certain object. def get_all_children(self): children = [self] try: child_list = self.children.all() except AttributeError: return children for child in child_list: children.extend(child.get_all_children()) return children It works fine when I call this function in my views.py file. But it gives me a RecursionError: maximum recursion depth exceeded in comparison when I call the same function in my celery tasks.py file -
django.db.utils.DataError: value too long for type character varying(4)
I added fields to my model but it's causing errors on migrate in production. I looked at various proposals on fixing this but couldn't get them working. Possible I'm not implementing them well. Would somebody be knowing the exact cause for this???? This is the error message. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 104, in database_forwards schema_editor.add_field( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 487, in add_field self.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 142, in execute cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", … -
Should I include /data folder created by docker-compose to Git?
I'm new to docker and docker compose. To be quiet honest, I'm new to programming in general. Currently I'm following a course in Web Development with Python (Django) and JavaScript. One of the project hinted that we should try to use docker. I use docker-compose to start Django server and connect them to a Postgres database. This configuration is copied from Docker documentation in Django version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db This resulted in a creation of a folder called /data under the root. Should I add this to the repository? Should I even use volumes for database? (In the course tutorial, the database part only include: services: db: image: postgres Thanks in advanced. -
How do I send QuerySets with Django using AJAX?
So, I have submitted a form using AJAX to a Django application but I am finding it a bit difficult to send the output back to my site... trips = Trip.objects.all() context = { "view":"trip", "listofTrips":zip(tripsData, tripsUserData), "noOfTrips":len(tripsData), "searched":True, } So I have QuerySets as well as ZIP files to send, and I cannot save it anywhere as the zip file is a queryset and saving it then downloading it would reduce my performance greatly. So is there any method by which I can get that done without refreshing...We can't use a JsonResponse since I get a (500) server error...so how can I send my data? Thanks! -
Django ORM substitute a field value with a calculation on it
I have this query in mu Django project: def calc_q(start_d, end_d, pr_code): start_d = start_date end_d = end_date pr_code = proj_code var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", "var_val", ) well i would to substitute the "var_val" value with a calculation on it's value, so i create a method like this one: def test_calc(c_val): return c_val*3 and i modify my ORM code : def calc_q(start_d, end_d, pr_code): start_d = start_date end_d = end_date pr_code = proj_code var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", test_calc(ast.literal_eval("var_val")[0]), ) i use ast becaus my var_val value is a string rappresentation of a list ("[112, 92]" for example) So when i run my code again i get: raise ValueError(f'malformed node or string: {node!r}') ValueError: malformed node or string: <_ast.Name object at 0x0000026C3F986DF0> How can i add a calculated field value diectly on my ORM code? So many thanks in advance Manuel -
Python console input from html form using django
i have a personality analysis python script, but I want to make it runs in html and get the input form from html page, and the shows the result back in html page. I already use a django framework to run html page. But i don't know how to connect it with python script I have have attached the python script. # -*- coding: utf-8 -*- import csv import os import pickle import re import string from collections import Counter import pandas as pd import tweepy from nltk.corpus import stopwords from nltk.stem import * from nltk.stem.snowball import SnowballStemmer from nltk.tokenize import word_tokenize from sklearn.feature_extraction.text import TfidfVectorizer from unidecode import unidecode ckey = 'ld6wr3Gt5ZdrKzQ4NGYCFCVA7' csecret = 'ErvYLR40biJWD0kr4wpjUUBK8vKDhGzdCwyzgiUOKdlyeYmaTG' atoken = '585075150-wFq2hQhw8x7oHEKjS4W9xVpsX3UGOtZvNblvSjuo' asecret = 'CwqO7p3esu6K45fNvQytitvXpCbrnKeRgGajs2qUsu74J' auth = tweepy.OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) emoticons_str = r""" (?: [:=;] # Eyes [oO\-]? # Nose (optional) [D\)\]\(\]/\\OpP] # Mouth )""" emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) "]+", flags=re.UNICODE) regex_str = [ emoticons_str, r'<[^>]+>', # HTML tags r'(?:@[\w_]+)', # @-mentions r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs r'(?:(?:\d+,?)+(?:\.?\d+)?)', # numbers r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and ' r'(?:[\w_]+)', # other words … -
Heroku : gunicon not identifying custom module in Django app
I am using a custom module in my Django app,when I tried to deploy this in Heroku, gunicorn is not detecting this module. Here is my code in manage.py where I have imported the module-relative import from .defs import log_transform Directory structure is below Link This is the build error am geting File "/tmp/build_2aedecf2/manage.py", line 6, in from .defs import log_transform ImportError: attempted relative import with no known parent package ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. Logs are as below return _getattribute(sys.modules[module], name)[0] 2021-06-26T07:11:29.515762+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 331, in _getattribute 2021-06-26T07:11:29.515763+00:00 app[web.1]: raise AttributeError("Can't get attribute {!r} on {!r}"2021-06-26T07:11:29.515763+00:00 app[web.1]: AttributeError: Can't get attribute 'log_transform' on <module '__main__' from '/app/.heroku/python/bin/gunicorn'> 2021-06-26T07:11:29.518944+00:00 app[web.1]: 10.7.237.91 - - [26/Jun/2021:07:11:29 +0000] "GET /result/?csrfmiddlewaretoken=rYlkcjC8Gx6y8zgXZ5cIABjg58UsmjuWzO9MqH3E1frADPTNY4pObgJ9itQMz8vj&FA=10.2&VA=0.32&CA=0.45&RS=6.4&CL=0.073&TSD=13&PH=3.23&SU=0.83&AL=12.6 HTTP/1.1" 500 89852 "https://wineprediction012.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36" -
How to override field name attribute in django model form?
I have a model form similar to the one below: class BookSearchForm(ModelForm): class Meta: model = Book fields = ['publisher', 'authors', 'category' How to override fields name attribute in the above model form? I tried this, but it did not work: class BookSearchForm(ModelForm): class Meta: model = Book fields = ['publisher', 'authors', 'category' widgets = { 'publisher': forms.SelectMultiple(attrs={'name': 'pub'}), 'authors': forms.SelectMultiple(attrs={'name': 'aut'}), 'category': forms.SelectMultiple(attrs={'name': 'cat'}), } -
CSS for TextField Django
I am developing a django website. I would like to know if there were any decent css stylings for text fields for forms in django. Thanks. -
how can i automatically assign user and image through spreadsheet as i'm getting errors in django
-->I'm using the stackoverflow for the first time and sorry for any mistakes. -->HI, there im developing a website as part of my final year project i.e exam hall seating arrangement system using django where the student registers and login to the website using his/her credentials after that they can view their exam hall seating arrangements. -->but the main thing during examinations i have to assign student examination hall and image of the his/her seating allocation. they are nearly 4k students where it is hectic task to done manually so i come through uploading a spreadsheet where it contains all the related details about the student username,examination hall and seating arrangement image i am getting error while uploading the spread sheet. -->how can i assign user and image through spreadsheet in django? errors -
Django server is not starting after importing custom declared class from a python file
I have written a custom class in a python file and trying to import it to another file.But once I import the class, django server is not starting after so much time, here is what I am doing .. helper.py def class GeneriMethod: @staticmethod def afunc1(): return "something" @staticmethod def bfunc2(): pass .... .... tasks/views.py from django_app_name.helper import GenericMethod generic_obj = GenericMethod() #method 1 def tsk_func1(): #call the imported class methods generic_obj.afunc1() #method 2 def tsk_func2(): #call the imported class methods GenericMethod.afunc1() After doing this when i do python manage.py runserver , why it is taking too much time like 5-10 minutes to run the server,when i remove the import then it works faster, i have no idea what is going on, please help me to resolve this