Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DetailView additional checks based on object
Which method should be overridden to add additional checks and redirect accordingly? i.e. I've a DetailView for my product page, and if this product is not published (and brand has more products) I want to redirect to the brand page. I added this check to get method and I'm calling get_object() manually and then doing my checks, but in the end I'm also calling the super().get() which calls get_object() as well, this makes the SQL run twice. The solution I've found is overriding the get_object() method as following.. def get_object(self, queryset=None): if not hasattr(self, 'object') or not self.object: self.object = super().get_object(queryset=queryset) return self.object This doesn't feel right though, what is the best way to do checks without triggering get_object twice? My code that calls get_object twice looks like this: without the hack above. def get(self, request, *args, **kwargs): product = self.get_object() if not product.published: if product.brand and #more products from brand exists# return redirect(reverse('brand', args=(product.brand.slug,))) else: return redirect(reverse('pages:home')) return super().get(request, *args, **kwargs) -
Django Rest Framewrok Token Authentication for Custom User Model
I'm new to using Django Rest Framework. I have inherited a Django project that has 2 user models: mods.User tied to AUTH_USER_MODEL and players.Member. For reasons I can't get into here, they both inherit from AbstractBaseUser but involve different information, with only an email field common between them. I am trying to use token authentication for users in players.Member. I have created an endpoint /players_endpoint/register which successfully adds players to the database. However, after adding the player to the database, the json response comes back with Cannot assign "<Member: offworld_321>": "Token.user" must be a "User" instance. My create view is as follows: class MemberCreateView(generics.CreateAPIView): queryset = Member.objects.all() def post(self, request, format='json'): serializer = MemberCreateSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: token = Token.objects.create(user=user) json = serializer.data json['token'] = token.key return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I was following the tutorial here How can I make it such that upon registration, a player receives a token which will be used for authentication? -
Why am I receiving this error about app name in my django unittest?
When running manage.py test, I receive the following error. ====================================================================== ERROR: Failure: RuntimeError (Model class app.pipeline.models.Product doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/nose/failure.py", line 39, in runTest raise self.exc_val.with_traceback(self.tb) File "/usr/local/lib/python3.5/site-packages/nose/loader.py", line 418, in loadTestsFromName addr.filename, addr.module) File "/usr/local/lib/python3.5/site-packages/nose/importer.py", line 47, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/local/lib/python3.5/site-packages/nose/importer.py", line 94, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/local/lib/python3.5/imp.py", line 235, in load_module return load_source(name, filename, file) File "/usr/local/lib/python3.5/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 693, in _load File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/src/app/pipeline/tests.py", line 9, in <module> from .views import job_details File "/usr/src/app/pipeline/views.py", line 37, in <module> from .models import (Product, Platform, CdTool, File "/usr/src/app/pipeline/models.py", line 9, in <module> class Product(models.Model): File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 113, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class app.pipeline.models.Product doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. settings.py INSTALLED_APPS = [ 'pipeline.apps.PipelineConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_nose', 'bootstrap3', 'bootstrap_pagination', 'mobilereports', 'rest_framework', 'api' ] This error only gets thrown when I run … -
Django audit packages with django 1.11 and python 3 compatibilty
I am making a project where if the student changes some data in his profile , the teacher should be notified about the same and should have history of all changes . So i am looking for audit packages. I found some but they do not support python 3 . I need to use this changed data so can anyone help me out here ! Thank You -
Comparison between DateField and date.today()
I have a method inside a Django Model class for a Task, that must return the risk situation of such, based on the comparison of expected start and finish dates with today, but I get an error when I try to compare start_date and finish_date models.DateField with date.today() this is the code of the method: def get_todo_situation(self): if self.finish_date == None: return 'unassigned' elif date.today() < self.start_date: return 'warning' elif date.today() < self.finish_date: return 'danger' else: return 'normal' and this is the error I get: File "/home/hugolvc/Code/TaskManagerProject/TaskManager/TaskManagerApp/models.py", line 63, in get_todo_situation elif date.today() < self.start_date: TypeError: '<' not supported between instances of 'datetime.date' and 'NoneType' I have seen examples where this works, but I think I am failing to grasp something. -
Django Deployment Server serving Static Files with only uWSGI
im trying to get my Django App to run using only uWSGI. The project is not that big, so i would really prefer to leave nginx out. I just can't get uWSGI to show my static files though. I've gone through the settings multiple times and can't find the problem. I have the STATIC_URL set to 'module/static/' STATIC_ROOT set to '/module/static_files/' (i read somewhere that they should not be the same) and my uwsgi.ini looks like this: [uwsgi] module=Module.wsgi:application master=True http=:80 processes=4 threads=2 static-map /static= /module/static_files/ the projects file structure is set up in the following way: -- Project: ---init.py ---settings.py ---urls.py ---wsgi.py -- Logs -- module ---static ---static_files ---[... module template, model, urls etc] -manage.py -db.sqlite3 I can run collectstatic and generate all the static files in the correct folder. But when i run the uwsgi script, it wont work and gives me a 404 file not found for all static files. I would really appreciate any help, I've been stuck on this for an entire week now... (i have checked out Deployment with Django and Uwsgi but as far as i can tell, my static-map is set correctly) -
pycharm not loading css files
ok I know this question was asked and I tried every solution. I am using pycharm (community edition) and trying to make use of css files but the project not affected . my project files organization : enter image description here and the codes from files I think the problem is some code in these 2 files because all the project works fine index.html <!DOCTYPE html> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'music/bootstrap /css/bootstrap.min.css' %}" /> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'music:index' %}">Vibber</a> </div> </div> </nav> <body> {%if all_albums%} <h3>Albums</h3> <ul> {% for album in all_albums %} <li> <a href="{% url 'music:detail' album.id %}">{{album.album_title }}</a> </li> {% endfor %} </ul> {%else%} <h3>No Albums</h3> {%endif%} </body> </html> here is setting file """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'utj^)r1l2nso_upv#k+dlb$385x*zo4fdy1n7egwuhgria4hc+' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
How do I make a website which show graphs of sentiment analysis of tweets using Twitter API?
how to make a live website which show graphs of sentiment analysis on tweets based on a specific topic by using python and text-blob library . Iam new to web-development , have moderate knowledge in python . please suggest the resources that i should follow ? -
Allowing HTTP access to Django API that is being authenticated by gmail login
I have an existing web app written in django (python). I have some endpoints that I would like to expose for a new app that we are creating, and we are writing it in ReactJs. In the current web app, where django serves the client pages, we verify authentication via python-social-auth dependency. How can use the gmail authentication for pure REST api calls? do I need to create a new mechanism? -
js to realtime listen to an existing django StreamingHttpResponse
I have been looking for previous answers to similar questions but could not find a clear solution for the frontend part. A view is generating a StreamingHttpResponse upon POST request views.py class streamPredictions(LoginRequiredMixin): def __init__(self,the_thread,the_stream,the_array,the_estimator): self.the_array = the_array[:] self.the_stream = the_stream self.the_thread = the_thread self.the_estimator = the_estimator def predict(self): while self.the_thread.isAlive(): aux_sample,aux_timestamp = self.the_stream.read('AUX') if aux_sample != [0.0,0.0,0.0] and 'nan' not in str(aux_sample): self.the_array = np.roll(self.the_array,-3) self.the_array[0][-3] = aux_sample[0] self.the_array[0][-2] = aux_sample[1] self.the_array[0][-1] = aux_sample[2] X = self.the_array[:] new_val = '{},{}'.format(self.the_estimator.predict(X)[0][0],self.the_estimator.predict(X)[0][1]) yield new_val # def LaunchPredictions(request,pk): ... if request.method == 'POST': the_preds = streamPredictions(t,the_stream,temp_arr_pred,rfr) return StreamingHttpResponse(the_preds.predict()) Here the post request in a js file activated by the click of a button : predict_button function receive_predictions(the_info,the_type,the_fbID,the_URL){ var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value; var data = new FormData(); var initTime = Date.now(); data.append("csrfmiddlewaretoken", csrftoken); data.append("info", the_info); data.append("type", the_type); data.append("id", the_fbID); // Feedback ID data.append("date", initTime); $.ajax({ url: window.location.pathname.replace("acc_calib",the_URL), method: "POST", data: data, contentType: false, processData: false, enctype: 'multipart/form-data', }); } predict_button.click(function() { receive_predictions('Predict','R_FOREST_REG',1,"launch_predictions"); } so that the corresponding url is in urls.py url(r'^launch_predictions/(?P<pk>\d+)/$',views.LaunchPredictions,name='launch_predictions') So far the generated data is streamed as expected from the middleware side but I would need my js to keep listening to it so that I can update graphics generated … -
Django Filter with Pagination
I'm attempting to follow the following tutorial for pagination with django filters, but the tutorial seems to be missing something, and i'm unable to get the pagination to show using the function based views method. https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html My users_list.html is the following: {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-4"> <label/> User ID {% render_field filter.form.employeeusername class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> First Name {% render_field filter.form.employeefirstname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Last Name {% render_field filter.form.employeelastname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Status {% render_field filter.form.statusid class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form> <table class="table table-bordered"> <thead> <tr> <th>User name</th> <th>First name</th> <th>Last name</th> <th>Status</th> <th></th> </tr> </thead> <tbody> {% for user in filter.qs %} <tr> <td>{{ user.employeeusername }}</td> <td>{{ user.employeefirstname }}</td> <td>{{ user.employeelastname }}</td> <td>{{ user.statusid }}</td> <td><input type="checkbox" name="usercheck" />&nbsp;</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} </tbody> </table> {% if users.has_other_pages %} <ul class="pagination"> {% if users.has_previous %} <li><a href="?page={{ users.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} … -
Formatting display of floats in django-tables2?
I have a column of floats in a table, and want them to be shown to just two decimal places (so, 10.238324 would be shown as 10.24). In Django templates, I do this using {{number||floatformat:2}}. Is there a similar formatting convention available for columns in django-tables2? Potentially relevant docs: http://django-tables2.readthedocs.io/en/latest/pages/column-attributes.html. -
Django Filtering queryset for use in a form in Heroku
I'm new to this stack so thought I would ask for help on what I think is a simple operation. I have a user model class: class UserProfile(models.Model): SA = 0 TA = 10 PA = 20 DA = 30 US = 1000 ACL_CHOICES = ( (SA, 'Super Admin'), (TA, 'Top Admin'), (PA, 'Parish Admin'), (DA, 'Parish Data Admin'), (US, 'User'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL) access_level = models.IntegerField(choices=ACL_CHOICES, default=US) associated_parish = models.ForeignKey('Parish', null=True, blank=True, default=None) associated_church = models.ForeignKey('Church', null=True, blank=True, default=None) contact_address = models.TextField(max_length=1000, blank=True, null=True) contact_number = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return "%s's Profile" % self.user.username def username(self): return self.user.username def userid(self): return self.user.pk def is_superadmin(self): return self.access_level == UserProfile.SA def is_topadmin(self): return self.access_level == UserProfile.TA def is_parishadmin(self): return self.access_level == UserProfile.PA def is_parishdataadmin(self): return self.access_level == UserProfile.DA and an admin class for use in creating gui components on heroku: class EventAdmin(admin.ModelAdmin): exclude = () list_display = ('title', 'start_time', 'end_time') def get_queryset(self, request): qs = super(EventAdmin, self).get_queryset(request) if request.user.userprofile.associated_parish: return qs.filter(church__parish=request.user.userprofile.associated_parish) return qs def save_model(self, request, obj, form, change): super(EventAdmin, self).save_model(request, obj, form, change) if request.user.userprofile.associated_parish: obj.parish = request.user.userprofile.associated_parish obj.save() def get_form(self, request, obj=None, **kwargs): if request.user.userprofile.associated_parish: if 'exclude' not in kwargs.keys(): kwargs['exclude'] = [] kwargs['exclude'].append('parish') form = … -
Django test client POST command not registering through 301 redirect
I'm writing Django tests for a live Heroku server, and am having trouble getting Django to recognize a POST request through a redirect. On my test server, things work fine: views.py def detect_post(request): """ Detect whether this is a POST or a GET request. """ if request.method == 'POST': return HttpResponse( json.dumps({"POST request": "POST request detected"}), content_type="application/json" ) # If this is a GET request, return an error else: return HttpResponse( json.dumps({"Access denied": "You are not permitted to access this page."}), content_type="application/json" ) python manage.py shell >>> from django.urls import reverse >>> from django.test import Client >>> c = Client() # GET request returns an error, as expected: >>> response = c.get(reverse('detectpost'), follow=True) >>> response.status_code 200 >>> response.content b'{"Access denied": "You are not permitted to access this page."}' # POST request returns success, as expected >>> response = c.post(reverse('detectpost')) >>> response.status_code 200 >>> response.content b'{"POST request": "POST request detected"}' However, when I move over to my production server, I encounter problems. I think it's because my production server has SECURE_SSL_REDIRECT, so all pages are redirecting to an SSL-enabled version of the same page. Here's what happens when I try to run the same test code on my production server: heroku … -
Django 1.11: ImportError: cannot import name [view]
I'm trying to add ChartsJS as an extra view in my Django App but I keep getting an Import Error. I have no idea why. I don't have any circular dependencies as far as I can find. Similar StackOverflow questions don't seem to match the problem. I'm totally stuck. The problematic view is Analytics view. project/app/urls.py: # -*- coding: utf-8 -*- from __future__ import ( absolute_import, division, print_function, unicode_literals ) from django.conf.urls import url from future import standard_library from survey.views import ConfirmView, IndexView, SurveyCompleted, SurveyDetail, AnalyticsView from survey.views.survey_result import serve_result_csv standard_library.install_aliases() urlpatterns = [ url(r'^$', IndexView.as_view(), name='survey-list'), url(r'^(?P<id>\d+)/', SurveyDetail.as_view(), name='survey-detail'), url(r'^csv/(?P<pk>\d+)/', serve_result_csv, name='survey-result'), url(r'^(?P<id>\d+)/completed/', SurveyCompleted.as_view(), name='survey-completed'), url(r'^(?P<id>\d+)-(?P<step>\d+)/', SurveyDetail.as_view(), name='survey-detail-step'), url(r'^confirm/(?P<uuid>\w+)/', ConfirmView.as_view(), name='survey-confirmation'), url(r'^analytics/$', AnalyticsView.as_view(), name='analytics-view'), ] project/app/views/analytics_view.py: # -*- coding: utf-8 -*- from __future__ import ( absolute_import, division, print_function, unicode_literals ) from builtins import super from future import standard_library from django.views.generic.base import TemplateView from django.contrib.auth.models import User standard_library.install_aliases() import arrow class AnalyticsView(TemplateView): template_name = "survey/analytics.html" ... I've read it may be to do with Settings, but I can't see any configuration problems there - project/settings.py: ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/bootstrap_admin/static/' STATICFILES_DIRS = [ os.path.normpath(os.path.join(ROOT, '..', "survey", "static")), ] Traceback: Unhandled exception in thread started by <function wrapper at 0x05CBB9F0> … -
NOT NULL constraint failed: teams_team.user_id
When I submit a new team as a authenticated user, I get this error is showing. I searched a lot of answers but they say do it null=True or default=1 but I don't want to be it null or something I want to be user's id it. Plus I imported and tried settings.AUTH_USER_MODEL and get_user_model from django.contrib.auth.models import User #models.py class Team(models.Model): creator = models.ForeignKey(User, related_name='teams', on_delete=models.CASCADE) name = models.CharField(max_length=20, unique=True) rank = models.IntegerField(default=0) #views.py class TeamsCreateView(generic.CreateView): model = Team form_class = TeamCreationForm #forms.py class TeamCreationForm(forms.ModelForm): class Meta: model = Team fields = ('name',) -
How to save local image to Django's model?
I've got some images in static dir which is located in 'apps/app_name'. I want to save this images while model instance creation. def save(self, *args, **kwargs): if not self.logo: self.logo = ... super().save(*args, **kwargs) I tried this: file = FileIO(os.path.join(settings.STATICFILES_DIRS[0], 'app_name/image.png')) but i've got an error: The joined path (/home/.../image.png) is located outside of the base path component (/home/.../media) Here is my settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Thousand separator not applied in Django admin
I registered my model in the Django Admin, but the Integer fields (they are read-only) show up without thousand separators; this happens in the admins list view and also in the admins model form. I am using Django 1.11.9, with Python 3.6. In my 'settings.py' I have the following: USE_I18N = False USE_L10N = False DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' USE_THOUSAND_SEPARATOR = True NUMBER_GROUPING = 3 Is there a way for the django-admin to apply thousand separators to my read-only fields? -- EDIT -- This similar question (from sep 2015) does not have a simple answer that applies to all fields automaticly. -
Mocking models used in a Django view with arguments
For the life of me I cannot figure this out and I'm having trouble finding information on it. I have a Django view which accepts an argument which is a primary key (e.g: URL/problem/12) and loads a page with information from the argument's model. I want to mock models used by my view for testing but I cannot figure it out, this is what I've tried: @patch('apps.problem.models.Problem',) def test_search_response(self, problem, chgbk, dispute): problem(problem_id=854, vendor_num=100, chgbk=122) request = self.factory.get(reverse('dispute_landing:search')) request.user = self.user request.usertype = self.usertype response = search(request, problem_num=12) self.assertTemplateUsed('individual_chargeback_view.html') However - I can never get the test to actually find the problem number, it's as if the model does not exist. -
Unable to add ajax post data to div
I am creating an ajax function that sends data to server and upon success receives html data and this HTML data will be added to a particular div element. However, i am unable the the data onto the div. Below is my HTML and jQuery Code. Further, i am using Django Framework. {% block content %} <div class="row"> <div class="col-md-8 col-lg-8 col-sm-10 col-xs-10 offset-lg-2 offset-md-2 offset-xs-1 offset-sm-1"> <div class="card"> <div class="card-header text-center"> No of Floors </div> <div class="card-header"> Project Name: {{ project_details.name }} <br> Location: {{ project_details.location }} <br> PIN: {{ project_details.pin }} <br> User: {{ project_details.user }} </div><br> {% for project in project_status %} <div class="col-md-12 text-center floor-container"> <h6>Floor No: {{ project.floor_no }}</h6> <input type="hidden" id="project_detail" value="{{ project_details.id }}"> <input type="hidden" id="floor_no" value="{{ project.floor_no }}"> <input type="hidden" id="floor_detail" value="{{ project.id }}"> <div id="progress"></div> <div class="card-footer text-muted text-right"> <a href="{% url 'single_project' id=project.project_detail.id floor_no=project.floor_no %}" class="btn btn-primary">View</a> </div> <br> </div> {% endfor %} </div> </div> </div> {% endblock content %} {% block script %} <script type="text/javascript"> $(document).ready(function(){ $('.col-md-12 .text-center .floor-container').each(function(){ $.ajax({ url: '{% url "progess_bar" %}', method: 'POST', data: { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'project_detail_id': $(this).children('#project_detail').val(), 'floor_no': $(this).children('#floor_no').val(), }, success: function(data){ $(this).children('#progess').html(data) } }) }); }); </script> {% endblock script … -
How to get the request object in Django?
I want to access the request.user and request.session deep in my Django project. As I didnt want to pass the request object (from the view) in tons of methods on the way, I created a thread local middleware to accomplish this. But later I came to know that this is not a fail proof/safe method (Why is using thread locals in Django bad? and https://www.pythonanywhere.com/forums/topic/710/). It is mentioned there that one thread can process multiple API requests. (How is this even possible?-not my main issue right now) Anyways, I have to accomplish this in a new way. Help appreciated. Thank you in advance! -
Django + Active Directory Using Current Data
I have a Django project with MS SQL Server as the backend. I also have Active Directory information (i.e. username, first name, last name and email) in a table that is updated daily and not currently related to the Django project. Is there a way to just write that information to the Django auth_user table and use that to provide Active Directory "integration"? I understand I could use a third-party package to actually integrate Active Directory, but I'm wondering if it's possible to take advantage of the existing data stream. The part I don't know is how Active Directory passwords would work if I was just writing users (without passwords) to the auth_user table. Update: The third-party package I would use says to map these fields: LDAP_AUTH_USER_FIELDS = { "username": "uid", "first_name": "givenName", "last_name": "sn", "email": "mail", } I currently have all those fields in my unrelated table. However, the package also says "When a user attempts to authenticate, a connection is made to the LDAP server, and the application attempts to bind using the provided username and password.". My intuition tells me that writing from the unrelated table would mimic syncing Active Directory users to the auth_user table, but … -
Django 1.10 upload file. form is not valid
I try upload file from Form in Django. I use Django 1.10. my form <form id='form_' enctype="multipart/form-data"> {% csrf_token %} <input id="fileupload" data-url="{% url 'analyzer:upload_files' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}' type="file" name="file" multiple> <p>Drag your file(s) here or click in this area.</p> </form> my views def upload_files(request): print(request.FILES, request.user.username) if request.POST: print('ok') form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print('YEEEES') return JsonResponse({'data':'ok', 'is_valid': True}) else: return JsonResponse({'data':'Bad', 'is_valid': False}) my forms.py from django import forms from .models import File class UploadFileForm(forms.ModelForm): class Meta: model = File fields = ('file_upload','user',) my model from django.db import models def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return ('user_%s/%s' %(instance.user.id, filename)) class File(models.Model): id = models.IntegerField(primary_key=True) id_user = models.IntegerField() user = models.TextField() uploaded_at = models.DateTimeField(auto_now_add=True) file_upload = models.FileField(upload_to='files/') file_size = models.IntegerField() file_name = models.TextField() I do not know what I'm doing wrong. My form is not valid. Please, help me! P.S. Still, I'm trying to save the file for each user separately, but examples from the Internet do not help -
django admin readonly_fields = 'some_filed' But create or add can not edit the same, what is a good way
django admin: readonly_fields = 'some_filed' But create or add can not edit the same, what is a good way -
how to set default group for new user in django?
how can I set default group for new users that I create? I didn't create custom model of user and My django version is 1.11.