Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: TypeError - argument of type 'QuerySet' is not iterable
So this error is very cryptic, how can it be that a Queryset object, even if empty, is not iterable? This is the rare error I'm seeing: TypeError: argument of type 'QuerySet' is not iterable And this is the code producing this error: artist_object = Artist.objects.get(id=id) artist_release_groups = artist_object.release_groups.all() if rg not in artist_release_groups: # this is the line where the error is happening artist_object.release_groups.add(rg) I don't know if this is relevant, but this is happening in a celery task and the error is being reported in Sentry (an exception reporting service). -
Django Password Reset - HTML encoded characters not displaying properly in e-mails
I am trying to get my password reset function to send e-mails with Spanish characters, like so: views.py def reset_password(email, from_email, template='registration/password_reset_email.html'): form = PasswordResetForm({'email':email}) return form.save(from_email=from_email, email_template_name=template) password_reset_email.html Para iniciar el cambio de contraseña hacer click aquí E-mails sent to @yahoo.com show up the way I want them to: Para iniciar el cambio de contraseña hacer click aquí E-mails sent to @gmail.com show up like this: Para iniciar el cambio de contraseña hacer click aquí I tried passing in html_email_template_name to the form.save() function and mucking with the content_type, but it still doesn't work. Anyone know what could be going on here? Thanks. -
TemplateDoesNotExist with Django-Fobi
Alright, so I'm not that new to programming, but I still have newbie problems. I'm using Python 2.7 , Django 1.8 I installed django-fobi around 2 days ago and have been pulling my hair since. Things are better now, but one error refuses to resolve: TemplateDoesNotExist at /fobi/forms/create/ the template is: bootstrap3/create_form_entry.html although the loader does find it: project_name/fobi/contrib/themes/bootstrap3/templates/bootstrap3/create_form_entry.html (File exists) However, the other templates of fobi are working. To be honest, I'm not sure if I configuredfobi correctly (newbie issues). Here are my files: project_name/settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [(os.path.join(SETTINGS_PATH, 'templates'))], # 'DIRS': [], # 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', "fobi.context_processors.theme", # Important! "fobi.context_processors.dynamic_values", # Optional "django.core.context_processors.request" ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'admin_tools.template_loaders.Loader', ], # 'debug': DEBUG_TEMPLATE, }, }, ] And I copied the fobi folder from https://github.com/barseghyanartur/django-fobi/tree/master/src and put it at project_name/fobi Initially, when I did not have the full fobi folder copied, I had just a few templates copied to project_name/templates/bootstrap3/create_form_entry.html, and the template loaded, but then the reversed url fobi_theme.create_form_entry didn't work. All migrations are applied and the apps are added in INSTALLED_APPS. Please, help and thank you in advance. -
How to add Django middleware with custom user settings as a Python package?
I'm attempting to create Django middleware that modifies the request object by adding additional data. I want to package this middleware so that it only requires the following steps for setup: Install via PIP Add route to MIDDLEWARE in settings.py. Read custom user settings from some config file. I've been searching for ways to do this but have not found any. There are guides for creating middleware packages, but not for properly packaging them for distribution. So I have the following questions. Is it possible to install middleware via PIP? If this is possible, is there a good cookiecutter-like example to base it off of? I tried (https://github.com/pydanny/cookiecutter-djangopackage), but this assumes the package is a stand-alone app, which seems like overkill for a package that consists of a single class. What's the best way to allow a user to customize the behavior of the middleware object? Ideally, I'd like the user to pass in a callable with the custom behavior, but I'm not sure where a user can define custom settings/functionality that gets passed into the middleware upon instantiation. Thanks in advance. -
Django - Template is not displaying the entire context list that I am passing
This is driving me crazy. I ran my logic in the shell and the list I am filling is holding all the values that should be passed to the template but when the template is rendered it is only displaying the first pass of the "each_role" iteration The shell shows 8 objects being placed into the list and all I am doing is passing that to be rendered in the template. The user I am using for both test cases is my admin user that is assigned to a 'finance' and 'IT' Role hence why it showed all 8 objects. The first 5 objects are 'IT' objects and the remaining 3 are the 'Finance'. Any reason for this behavior and why it will not display all the lines on the webpage? I attached an image of the actual page rendered. Thank yoU! WebPage image Shell >>> for each_role in all_roles: ... if each_role in user_roles: ... list_of_reqs = RequisitionLine.objects.filter(assistance=each_role.id) ... for line in list_of_reqs: ... parent = line.parent_req ... if parent in req_header_list: ... continue ... else: ... req_header_list.append(parent) ... for i in range(len(req_header_list)): ... hold_line_count = RequisitionLine.objects.filter(Q(parent_req=req_header_list[i]) & Q(assistance=each_role.id)) ... for j in hold_line_count: ... req_header_line_list.append(j) ... print(j) ... … -
How to write tests based on django's Settings Module
I have a project where I need to add certain third-party application access keys into settings module, say AWS keys. How do I write tests for them? something like below? def test_it_can_read_aws_keys(self): assert settings.KEY_1 is None assert settings.KEY_2 is None # now somehow i need to add/simulate the keys in settings.py like below # KEY_1 = 'xxx' # KEY_2 = 'yyy' assert settings.KEY_1 is 'xxx' assert settings.KEY_2 is 'yyy' -
Django: generic ListView, only show when in other model via ForeignKey
I have two models: Creator and Piece. Per default every user is a Creator. But only if the user uploads a Piece he actually created something. Hence I would like to show in the generic Creator ListView only those Creators that uploaded a Piece. How can I filter the generic ListView to only show Creators that are present in the model Piece via a ForeignKey? models.py class Creator(models.Model): ... user = models.OneToOneField(User, on_delete=models.CASCADE) ... class Piece(models.Model): ... creator = models.ForeignKey('Creator', on_delete=models.SET_NULL, null=True) ... views.py class CreatorListView(generic.ListView): model = Creator paginate_by = 10 creator_list.html {% block content %} <h1>Creators</h1> {% if creator_list %} <ul> {% for creator in creator_list %} <li> <a href="{{ creator.get_absolute_url }}">{{ creator }}</a> </li> {% endfor %} </ul> {% endif %} {% endblock %} -
Ajax call not updating template django
Below are the details. I am able to get updated "questions_in_topic" variable in views when select option is changed i.e. ajax call is made. Ajax call is updating the "questions_in_topic" variable based on selected value in dropdown. But these changes are not reflected in template. i.e. on template, I still get old values. urls.py url(r'^interview/add/questions/library', recruiter_views.add_question_library, name='add_question_library'), views.py def add_question_library(request): question_topics = QuestionTopic.objects.values('question_id__description', 'topic_id__name','question_id','topic_id').order_by('topic_id__name','question_id__description') all_topics = Topic.objects.all() questions_in_topic = QuestionTopic.objects.values('question_id__description').order_by('question_id__description') if request.is_ajax(): if 'topicId' in request.POST: print("xx") questions_in_topic = QuestionTopic.objects.filter(topic_id=request.POST['topicId']).values('question_id__description').order_by('question_id__description') else: print("yy") questions_in_topic = QuestionTopic.objects.values('question_id__description').order_by('question_id__description') print(questions_in_topic) context = { 'question_topics': question_topics, 'all_topics': all_topics,'questions_in_topic':questions_in_topic,} return render(request, 'recruiter/add_question_library.html', context) add_question_library.html <select id="topic" name="topic_list" class="form-control topic_select"> {% for topic in all_topics %} <option data-topic="{{topic.id}}" value="{{topic.name}}">{{topic.name}}</option> {% endfor %} </select> <ul class="list-unstyled"> {% for x in questions_in_topic %} <li class="list-unstyled">{{ x.question_id__description }}</li> {% endfor %} </ul> ajax var topicId = $(".topic_select option:selected").attr("data-topic"); $(".topic_select").change(function(){ var topicId = $(".topic_select option:selected").attr("data-topic"); $.ajax({ type: "POST", url: "{% url 'recruiter:add_question_library' %}", data: { topicId: topicId, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function(){ // alert("Showing questions from topic " + topicId); } }); }); -
about django's list_fields in making models for friends list, in project about making SNS
i'm amateur django student. i'm making web-SNS like instagram. So, i should make models that contains one user's all friends. so i try to use list for containing user's friends. like this photo enter image description here yeah, i know i can't use and build list by using that way. how to make use list for save user's friends list? or Is there more good idea for saving user's friends list in user(not User, just real user)'s model? -
How to add question mark to the url using django?
I have: urlpatterns = [ url(r'^tools(?:/tool_one=(?P<tool_one>\w+))?/?$', views.ToolsViews.as_view(), name='tools'), ] the print of url like this: tools/tool_one=bags I want to add a question mark to the url like this: tools/?tool_one=bags I was try to write: urlpatterns = [ url(r'^tools(?:/\?tool_one=(?P<tool_one>\w+))?/?$', views.ToolsViews.as_view(), name='tools'), ] but the question mark didn't exists, the print of url: tools/%3Ftool_one=bags Can anyone give me some hint? What is the problem? -
Why Model.add(Model.get()) makes `database is locked` Error in Django?
I met database lock error in my application. (Django, Sqlite3, Window 10) problem.parent_contest.add(Contest.objects.select_for_update().get(pk=contest)) Is this statement make database lock error? I can't understand why that code makes Error. Please help me. There is my codes and error track back. Thanks. apps.py for problem_id in range(1000, 19999, 1): current_problem = parse_problem(problem_id) db_lock.acquire() problem, created = Problem.objects.get_or_create( id=current_problem['id'], defaults={ 'title': current_problem['title'], 'can_submit': current_problem['can_submit'] } ) problem.title = current_problem['title'] problem.can_submit = current_problem['can_submit'] problem.save() for contest in current_problem['parent']: problem.parent_contest.add(Contest.objects.select_for_update().get(pk=contest)) db_lock.release() time.sleep(600) models.py class Contest(models.Model): id = models.IntegerField(primary_key=True) title = models.TextField() parent_category = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: ordering = ('id',) def __str__(self): return 'Contest %s: %s' % (self.id, self.title) class Problem(models.Model): id = models.IntegerField(primary_key=True) title = models.TextField() can_submit = models.BooleanField() parent_contest = models.ManyToManyField(Contest) class Meta: ordering = ('id',) def __str__(self): return 'Problem %s: %s' % (self.id, self.title) Trackback Traceback (most recent call last): File "C:\Users\JongBeom Kim\.virtualenvs\backend-3j_oU1lC\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\JongBeom Kim\.virtualenvs\backend-3j_oU1lC\lib\site-packages\django\db\backends\sqlite3\base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: database is locked The above exception was the direct cause of the following exception: Traceback (most recent call last): File "c:\python36\Lib\threading.py", line 916, in _bootstrap_inner self.run() File "c:\python36\Lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\msys64\home\JongBeomKim\WEB\ps.kajebiii.com\backend\boj\apps.py", line 150, in parse_all_problem … -
How to parse, and render, json for use in Django template
I'm a newbie in Django and trying to learn, but I'm confused about how I can render data pulled from API in a template in Django and display it in the HTML page. The json data sample is: { "docs": [ { "hostIP": "X.X.X.X", "time": "August 13, 2018 13:43:44", "site": [ { "site": "site1", "path": "/path/to/site1", "git_branch": "master", "git_commit_message": "New changes" }, { "site": "site2", "path": "/path/to/site2", "git_branch": "master", "git_commit_message": "add card" } ] } ] } Also how i can loop it using Jinja2? Please someone help me out of this. -
Django: How to create a dynamic related_name for an inherited parent model?
I have 4 models: class User(models.Model): name = models.CharField(max_length=255) class A(models.Model): user= models.ForeignKey("User", related_name="u_a", on_delete=models.CASCADE) title = models.CharField(max_length=255) class B(A): user= models.ForeignKey("User", related_name="u_b", on_delete=models.CASCADE) #isn't the code repeated??? b_field = CharField(max_length=255) class C(A): user= models.ForeignKey("User", related_name="u_c", on_delete=models.CASCADE) #isn't the code repeated??? c_field = CharField(max_length=255) Here, A has a ForeignKey relationsip with User and a reverse relationship as u_a. But B and C are children of A. So It appears to me as if Do not repeat your code is violated. How to overcome this? -
How to use Django Model permissions defined in Meta of the model classes for setting REST_FRAMEWORK DEFAULT_PERMISSION_CLASSES
I have models that define permissions in the Meta class as follows (not just the default view add edit delete) : class FabricInstance(models.Model): class Meta: permissions = ( ( 'sf_fabricinstance_read', 'View Fabric Instances' ), ( 'sf_fabricinstance_manage', 'Manage Fabric Instances' ), ( 'sf_fabricinstance_delete', 'Delete Fabric Instances' ), ) I want the rest framework to pick up on these permissions and return responses and allow opperations based on user's permissions. I have tried this: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissions', ), } But the Rest framework does not pick up on the permissions I define in the Meta class. So I get Read only access to the REST API (to be clear: I am talking of when hitting the REST urls directly. No issue working programatically). Am I missing something? My understanding is that that they should be picked up by simply adding 'rest_framework.permissions.DjangoModelPermissions' in the REST_FRAMEWORK section in settings.py -
DRF: validate a field from another table
I have created an API to upload the file. Now I want to add few checks before user can upload it. So in payload I am asking his email and token to validate him. Now email and token are in separate table. How can I validate them. I am getting errors like TypeError: 'email' is an invalid keyword argument for this function my models file class File(models.Model): filename = models.FileField(blank=False, null=False,upload_to='files') remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) my serializer file class FileSerializer(serializers.ModelSerializer): token = serializers.CharField(label=_("Token")) email = serializers.CharField(label=_('router_macid')) def validate(self, attrs): print("validating params") token = attrs.get('token') email= attrs.get('email') validate(token, email) return attrs class Meta(): model = File fields = ('filename', 'remark', 'timestamp', 'token', 'email') read_only_fields = ('token', 'email') -
Django 2 distinct model field items
I am trying to get a list of distinct items in a field of a module and then display all the items associated with that field. For example, in a school administration system there is a school module and a student model. Each student has a color associated with them as a 'color' field. I want to create a page where the page lists all the distinct colors in the school and then under each color a list of students that belong to that color. Would I write this function in views? Here is what I have so far in views.py: class SchoolColorDetailView(DetailView): model=models.School template_name='school_app/school_color_detail.html def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['colors']=Student.objects.all().order_by('color').distinct('color') This will get me a list of all colors (but not by school). Is there any way to only get the colors by school and then all the students associated with that color? Do I have to create a dictionary for this? Any help would be appreciated. Thanks! -
template inheritance glitch in django
I'm new to Django was following a tutorial and when it comes to template inheritance i keep getting the same error.. When I run my server my homepage duplicates on all of my pages; catalog/product.html and catalog/category.html. What am i doing wrong with my block content Base.html <!DOCTYPE html> <html> <head> <title>Website</title> </head> <body> {% block content %} {% endblock %} Home .html {% extends "base.html" %} {% block content %} <h1>Welcome to Website</h1> {% endblock %} Product.html {% extends "base.html" %} {% block content %} <h1>Products</h1> {% endblock %} Category.html {% extends "base.html" %} {% block content %} <h1>categories</h1> {% endblock %} What should I fix because I watch other tutorials and it works just the way I have it. I just keep seeing base. and catalog.html on all my pages and I want to display products and new things. I also copied the product page onto my front page and it displayed. Soon as I put the code back into product.html it would show again. How can I fix this with block content? How does the block content tags pick the order of it operations? Thanks for the help regardless!! -
Django - download image from url using external script and insert them into imageField
I am working on website (Django 2.1) with embeded videos, I need to fill my DB using external script. I have two tables one is parent (Video) and child table (Thumbnail) where is imageField. I need to download thumbnails from url and programmatically insert image into ImageField. I am fighting with this problem 2 days. I have read several advices here on stackoverflow but nothing work for me, I am giving up here. Can somebody help me please? Here is part of my models: #my models.py class Video(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique = True) video_url = models.URLField(max_length=255, unique = True) class Thumbnail(models.Model): name = models.CharField(max_length=50) thumb = models.ImageField(upload_to='thumb/', null=True, blank=True) thumb_resolution = models.CharField(max_length=50, null=True, blank=True) videos = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='thumbnails') Here is simplified version of my downloading code, I tried several different ways but most of attempts ends without error but no files are in MEDIA folder. But my OneToMany relation between Video and Thumbnail is created successfully. import requests from io import BytesIO from PIL import Image os.environ.setdefault("DJANGO_SETTINGS_MODULE", "video.settings") import django django.setup() from django.core.files import File from django.core.files.base import ContentFile from mainSite.models import Video, Thumbnail def download(url): try: r = requests.get(url) if not r.status_code == 200: … -
The xadmin of Django is wrong to run
I use xadmin to manage my project, and I want to change the langue from English to Chinese, so I add "verbose_name = '用户信息'"to the apps.py, and add "default_app_config = 'users.apps.UsersConfig'"to users.init.py. Finally, It's wrong to start run. Here is my users.apps.py file: from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' verbose_name = '用户信息' Here is my settings.py file: """ Django settings for MuKeOnline project. Generated by 'django-admin startproject' using Django 1.11.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import sys # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'f*@!o)%f)0cs$*&154i-w5(f7jpjtcc_nc99(h22b-_xe$qt4w' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'xadmin', 'crispy_forms', 'reversion', 'users.apps.UsersConfig', 'course', 'organization', 'operation', ] # 使用自定义用户表 AUTH_USER_MODEL = 'users.UserProfile' 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', ] ROOT_URLCONF = 'MuKeOnline.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
Associating the logged in user with the Photo Model
I basically want to associate the logged in user name with the PhotoModel by using models.ForeignKey. I override the safe_model in admin.py but when i execute the views.py class PhotoCreateNew(View) then it stops at print(form) and the form is not validated (if form.is_valid()) skips the entire part which was supposed to set the request.user as photo.user_name and return the empty template. My models.py class Photo(models.Model): user_name = models.ForeignKey(User, on_delete=models.CASCADE) PLACES = (('RD','研发-R&D'),('Warehouse','仓库-Warehouse'),('Gate','门卫处-Gate Guard'),('SecondFloor','2F生产部')) photo = models.FileField() photo_name = models.CharField(max_length=20) date = models.DateField(auto_now="True") quantity = models.CharField(max_length=4) CONDITIONS = (('N','NG'), ('G', 'GOOD')) condition =models.CharField(max_length=1,choices=CONDITIONS) place = models.CharField(max_length=30,choices=PLACES,default='Warehouse') def __str__(self): return self.photo_name def get_absolute_url(self): return reverse('photo:photo_detail', kwargs={'pk':self.pk}) class PhotoForm(ModelForm): class Meta: model = Photo fields =['user_name','photo','photo_name','quantity','condition','place'] exclude= ('user_name',) My admin.py: from django.contrib import admin from photo.models import Photo from photo.models import Supplier class PhotoAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if not obj.pk: obj.user_name = request.user obj.save() admin.site.register(Supplier,) admin.site.register(Photo, PhotoAdmin) My views.py: class PhotoCreateNew(View): form_class = PhotoForm template_name = 'photo/photo_form.html' def get(self, request): form =self.form_class(None) return render(request, self.template_name, {'form':form}) def post(self,request): form = self.form_class(request.POST) print(request.user) print(form) if form.is_valid(): # uploader has been excluded. No more error. print("Przeszlo") photo = form.save(commit=False) # returns unsaved instance photo.user_name = request.user print(request.user) photo.save() # real save to … -
how to exit "python manage.py runserver" in windows
I tryed Ctr+Z to exit "python manage.py run server". But nothing happend. This both happend in cmd and gitbash in win64 -
Django : Unable to access values from a dictionary nested inside another dictionary
I have dictionary item of the form data = {0:'Karthik', 1:{'semester':8,'marks':100,'result':'pass','html':'HTML DATA HERE'}, 2:{'semester':8,'marks':100,'result':'pass','html':'HTML DATA HERE'}, 3:{'semester':8,'marks':100,'result':'pass','html':'HTML DATA HERE'}} and i am passing the above data to a template as below: def showAvailableNonCBCSResults(request,usn): data = {0:'Karthik', 1:{'semester':8,'marks':100,'result':'pass','html':'HTML DATA HERE'}, 2:{'semester':8,'marks':100,'result':'pass','html':'HTML DATA HERE'}, 3:{'semester':8,'marks':100,'result':'pass','html':'HTML DATA HERE'}} return render(request,'result/showresult.html',{'data':data,'dictentries':range(0,len(data))}) Template code is below: {% for i in dictentries %} <table class="table table-responsive table-striped table-hover pt-3" style="margin:auto;"> {{ data.i.html }} </table> {% endfor %} The data from the html field of dictionary is not getting printed. If i use data.1.html or data.2.html, it is working fine and i can see the html data. However, using data.i.html inside the for loop does not print anything. Where am i going wrong? -
Datepicker and FullCalender.io cannot run together datepicker is not a function
I am trying to run instances of both fullcalendar and datepicker in one html file. I can get full calendar working as expected but I cannot get datepicker working along side. When I run datepicker in its own separate html file it works fine. The error that I get in the console is the below: jQuery.Deferred exception: $(...).datepicker is not a function TypeError: $(...).datepicker is not a function and Uncaught TypeError: $(...).datepicker is not a function at HTMLDocument. I am running this through Django but I don't think that is relevant. Below is my code to make this happen, the idea is to open the modal and have a datepicker in there: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link href="{% static 'css/fullcalendar.min.css' %}" rel='stylesheet' /> <link href="{% static 'css/fullcalendar.print.min.css' %}" rel='stylesheet' media='print' /> <script src="{% static 'js/moment.min.js' %}"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="{% static 'js/jquery.min.js' %}"></script> <script src="{% static 'js/fullcalendar.min.js' %}"></script> <link href="{% static 'css/datepicker.css' %}" rel='stylesheet' /> <script src="{% static 'js/datepicker.js' %}"></script> </script> <script> $(document).ready(function() { $('#calendar').fullCalendar({ theme: true, themeSystem: 'bootstrap4', header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay,listWeek' }, navLinks: true, … -
django cores header module not found error
According to my last question I found that i should use django-cors-header but i've faced with a problem. I installed cors header on my system and after refer Enable Django CORS on Github i used this code : INSTALLED_APPS = ( ... 'pipeline', 'corsheaders' ) also i added 'corsheaders.middleware.CorsMiddleware' to my Middleware_classes. in addition i added this code to setting.py too: CORS_ORIGIN_WHITELIST = ( 'http://127.0.0.1:8000', 'http://localhost:8000', ) but when i want runserver ModuleNotFoundError:no module named 'pipeline' appears! which module should i import? -
Javascript for validating if uploaded file is image isn't working
I'm doing some web development using Django. There comes a part where user could upload images to my server. Here is the Javascript side of the code. var uploadField = document.getElementById("file_upload"); uploadField.onchange = function(){ var file_type=this.file[0]['type']; // file_type = 'image/jpg' if (file_type.split('/')[0] !== 'image'){ alert("Not an Image"); this.value = ""; } else if(this.files[0].size > 2097152){ alert("File is too big!"); this.value = ""; } else{ this.form.submit(); document.getElementById('celimsg').innerHTML='Analyzing image...'; document.getElementById('celi').src=gif_url; } } It didn't work. When the files are uploaded, nothing happens. But if I remove the validation part: var uploadField = document.getElementById("file_upload"); uploadField.onchange = function(){ if(this.files[0].size > 2097152){ alert("File is too big!"); this.value = ""; } else{ this.form.submit(); document.getElementById('celimsg').innerHTML='Analyzing image...'; document.getElementById('celi').src=gif_url; } } It started working again. Unlike other web development platform, Django doesn't support debugging for javascript and I can't put print statements on it etiher.