Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add header to SOAP request
The project on Django 1.99 and it use SOAP client suds 0.4. from suds.client import Client client = Client('wsdl') msg = """some messege""" rq = url.service.SomeService(__inject={'msg':msg}) Everything works fine, but i need to add header to this request "Accept-Encoding:gzip, deflate" so i edit the line : client= Client('wsdl', headers={'Accept-Encoding': 'gzip, deflate'}) or add new line: client.set_options(headers={'Accept-Encoding': 'gzip, deflate'}) but i've the same error: SAXParseException: <unknown>:1:0: not well-formed (invalid token) Does any body knows how to add header to request that look like that. I undestand that SUDS no longer supported but maybe someone knows how to deal with it. Or maybe someone can advice another SOAP Client on python to deal with it. -
How to update a ModelForm's initial values dynamically?
I'm trying to create a dynamic form which pre-populates the initial attribute of a certain field (title) when another field (checkin_type) is selected from a drop-down menu. I'm using Django's generic CreateView, and the way I'd like to go about it is by overriding the view's post() method such that if it receives an AJAX request (which is triggered by a jQuery .change() in the aforementioned drop-down menu and contains the id of the selection option), it updates the initial property of the form's title. Here is the view I've tried so far (in views.py): from django.views import generic from .models import CheckIn, CheckInType class CheckInCreate(generic.CreateView): model = CheckIn fields = '__all__' def post(self, request, *args, **kwargs): if request.is_ajax(): checkin_type = CheckInType.objects.get(pk=request.POST['id']) form = self.get_form() form['title'].initial = checkin_type.title self.object = CheckIn.objects.create(checkin_type=checkin_type) return self.render_to_response(self.get_context_data(form=form)) else: return super().post(request, *args, **kwargs) Here is how the AJAX request is made in the form's template, called templates/dashboard/checkin_form.html in accordance with Django's naming convention (dashboard is the name of the app): <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script> $(document).ready(function(){ var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { … -
How do I build a formset dependent on another model?
So I basically have three models: FileUpload, Lecture and Course. I was wondering how could I build a formset that for any of the lectures that there are in a course, I could allow a student to upload a document. I tried something, but I only managed to display the FileUpload fields. Also, a teacher has its specific courses. Here is what I tried: #models.py class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures', ) lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses', ) lecture_title = models.CharField(max_length=100, blank=True, null=True) content = models.TextField(blank=False, default=None) def __str__(self): return str(self.lecture_title) class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) lecture = models.ForeignKey('Lecture', related_name='files', on_delete=None, default=None) def __str__(self): return str(self.files) #forms.py class LectureForm(forms.ModelForm): lecture_title = forms.CharField(max_length=100, required=True) course = forms.ChoiceField() def __init__(self, *args, **kwargs): user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['course'].choices = self.get_courses(user) @staticmethod def get_courses(teacher): teacher_data = TeacherData.objects.get(teacher_ID=teacher.teacher_ID) return [(x.id, x.name) for x in Course.objects.filter(Q(teacher1=teacher_data) | Q(teacher2=teacher_data))] def clean_course(self): course_id = self.cleaned_data.get('course') course_obj = Course.objects.get(pk=course_id) return course_obj class Meta: model = Lecture fields = ('course', 'lecture_category', 'lecture_title', 'content') class FileForm(forms.ModelForm): class Meta: model = FileUpload fields = ('files',) #views.py FileFormset2 = inlineformset_factory(Lecture, FileUpload, fields=('lecture',)) formset = FileFormset2(request.POST, request.FILES, prefix='files') if formset.is_valid(): formset.save() … -
Trying to prevent Dropzone to upload files if they already exist on the server
I am trying to use Dropzone JS with Django and need the dropzone not to upload files if they already exist on the server. It used to work with a simple filefield before with a similar structure, however does not seem to be working now. views.py if request.method == 'POST': form = UploadFileForm1(request.POST, request.FILES) if request.FILES: upload_exists = UploadForThisMonthExists() print upload_exists if upload_exists == True: return render(request, 'dependencies/upload.html', {'file_exists': True}) # here it should reload the page and trigger jquery popup for key in request.FILES: handle_uploaded_file_1(request.FILES[key]) forms.py class UploadFileForm1(forms.Form): file = forms.FileField() html <script type="text/javascript"> Dropzone.options.myAwesomeDropzone = { paramName: "file", // The name that will be used to transfer the file maxFilesize: 4, // MB parallelUploads: 8, uploadMultiple: true, maxFiles: 8, acceptedFiles: ".xlsx", init: function () { this.on("complete", function (file) { if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) { console.log('upload is done'); } }); } }; </script> <form action="#" class="dropzone" id="my-awesome-dropzone"> {% csrf_token %} </form> So Unfortunately even if UploadForThisMonthExists() returns True, the page does not get reloaded. It does not reupload, but the page does not get reloaded. Thank you. -
Django / Python - Using ManyToMany field In Object Creation
Is there any way to create an object in a model using a ManyToManyField? Here are the models: class Booking(models.Model): tour_ref = models.CharField(max_length=30) customers = models.ManyToManyField(Customer) class Customer(models.Model): name = models.CharField(max_length=40) email = models.EmailField() The task is to create a new Booking object. But how do I do this using specific customers from the Customer table? (I would be identifying them by email). (Obviously more than one customer would be likely). Many thanks! -
How can I use Date Picker with django-filter?
I am trying to figure out how can I use datepicker with django-filter.I have tried a bunch of widgets but it's not working out.Any suggestions will be appreciated! I want to use datepicker for the row_date search filter. filters.py from home2.models import AvailstaticCopy from django import forms import django_filters class DateInput(forms.DateInput): input_type = 'date' class AvailFilter(django_filters.FilterSet): class Meta: model = AvailstaticCopy widgets = {'row_date': DateInput(),} fields = ['row_date', 'director','manager','analyst',] This is my template {% load widget_tweaks %} <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-3"> {{ filter.form.row_date.label_tag }} {% render_field filter.form.row_date class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.director.label_tag }} {% render_field filter.form.director class="form-control" %} </div> <div class="form-group col-sm-8 col-md-6"> {{ filter.form.manager.label_tag }} {% render_field filter.form.manager class="form-control" %} </div> <div class="form-group col-sm-8 col-md-6"> {{ filter.form.analyst.label_tag }} {% render_field filter.form.analyst class="form-control" %} </div> <div class="form-group col-sm-8 col-md-6"> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </div> </div> </div> -
Django: Translations not working on S2. Path issue?
I have added some translation for my website (running django 1.8) that work fine locally but are not working when deployed. I've checked if the .mo and .po files were commited (They were) and if the MIDDLEWARE_CLASSES had been setup correctly (they were / see below) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) Since its working just fine locally (and I've commited the .mo and .po' files) I am beginning to suspect that the issue is that DJango is unable to find the files on the server, but I cannot see how - as my settings should account for this. Here is my LOCALE_PATHS setting: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'),) and below is the folder structure on my locale computer src | |- root |- locale | |---fr | |-LC_MESSAGES | | | |- django.mo | |-django.po | |-static |-app1 |-app2 Does anyone have an idea what I am doing wrong? -
in Django, what should I put in TIME_ZONE for Los Angeles time?
The subject just about says it all, but here's some background: I'm about to go live with some software that's been complaining I'm using unaware log timestamps. Everything is happening in California, so all users will be in USA Pacific Time. I've tried reading the documentation but keep getting frustrated by references to other documentation that seems to be an endless self-referential graph of theoretical treatises on stuff I probably but not certainly don't need to know. I just want the minimum I need to be using aware timestamps where I now write record = Log(timestamp=datetime.now(), .... I probably now have the wrong thing is TIME_ZONE in settings, but I don't know what it should be. -
django manage.py runserver fails to run
Im new to django, i started a project inside a virtualenv and whenever i try to runserver i get this message: Performing system checks... System check identified no issues (0 silenced). March 01, 2018 - 13:22:34 Django version 2.0.2, using settings 'PollApp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x03BBF7C8> Traceback (most recent call last): File "C:\Users\Sebastian\Desktop\Desarrollo\HelloWorld1\lib\site- packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Sebastian\Desktop\Desarrollo\HelloWorld1\lib\site- packages\django\core\management\commands\runserver.py", line 143, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\Sebastian\Desktop\Desarrollo\HelloWorld1\lib\site- packages\django\core\servers\basehttp.py", line 163, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Sebastian\Desktop\Desarrollo\HelloWorld1\lib\site- packages\django\core\servers\basehttp.py", line 66, in __init__ super().__init__(*args, **kwargs) File "c:\users\sebastian\appdata\local\programs\python\python36- 32\Lib\socketserver.py", line 453, in __init__ self.server_bind() File "c:\users\sebastian\appdata\local\programs\python\python36- 32\Lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "c:\users\sebastian\appdata\local\programs\python\python36- 32\Lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "c:\users\sebastian\appdata\local\programs\python\python36- 32\Lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 7: invalid continuation byte I dont realy know where to start solving this error, i have a WAMP server installed, should i check if im using the 8000 port? -
FOREIGN KEY constraint failed in django admin panel when creating/editing/deleting a user. (Using custom user model.)
So I'm using a custom user model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, full_name, address, number, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') if not full_name: raise ValueError('Users must have an email address') if not address: raise ValueError('Users must have an email address') if not number: raise ValueError('Users must have an email address') if not password: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email.lower()), full_name=full_name, address = address, number=number, ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, full_name, address, number, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, full_name, address, numbe, password = password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, full_name, address, number, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, full_name, address, number, password = password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank = False, null = False) address = models.CharField(max_length=255, blank = … -
AngularJS and Django file upload from
I am trying to upload a file, to my REST-Api (writen with Django). Next to the file there are serveral other form data, linke name, description and stuff like that. I am new with AngluarJS figured out, that there is no basic support for file uploads. After googleing I am try to integrate this solution in may. file-modul.directive.js (function () { 'use strict'; angular .module('thinkster.layout.directives',) .directive('fileModel', fileModel); function fileModel($parse) { var directive = { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ modelSetter(scope, element[0].files[0]); }); }); } }; return directive; } })(); layout.module.js (function () { 'use strict'; angular .module('thinkster.layout', [ 'thinkster.layout.controllers', 'thinkster.layout.directives', ]); angular .module('thinkster.layout.controllers', []); angular .module('thinkster.layout.directives', ['$parse']); })(); But I am getting this error: Error: [$injector:modulerr] Failed to instantiate module thinkster due to: [$injector:modulerr] Failed to instantiate module thinkster.layout due to: [$injector:modulerr] Failed to instantiate module thinkster.layout.directives due to: [$injector:modulerr] Failed to instantiate module $parse due to: [$injector:nomod] Module '$parse' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. http://errors.angularjs.org/1.3.20/$injector/nomod?p0=%24parse minErr/<@http://127.0.0.1:8000/static/bower_components/angular/angular.js:63:12 module/<@http://127.0.0.1:8000/static/bower_components/angular/angular.js:1778:17 ensure@http://127.0.0.1:8000/static/bower_components/angular/angular.js:1702:38 module@http://127.0.0.1:8000/static/bower_components/angular/angular.js:1776:14 loadModules/<@http://127.0.0.1:8000/static/bower_components/angular/angular.js:4131:22 forEach@http://127.0.0.1:8… Can someone … -
Using multi left join in Django QuerySet
I trying to use left join in Django QuerySet but can't achieve it. I attach my models which would be the base of my left join: class House(models.Model): id = models.IntegerField(primary_key=True) short_name = models.CharField(max_length=4) class Meta: managed = False db_table = 'house' class Table(models.Model): id = models.ForeignKey('House',models.DO_NOTHING, primary_key=True) time_stamp = models.DateTimeField() table = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'table' unique_together = (('house', 'time_stamp'),) class Chair(models.Model): id = models.ForeignKey('House',models.DO_NOTHING,primary_key=True) time_stamp = models.DateTimeField() chair = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'table' unique_together = (('house','time_stamp'),) My attempt: I tried select_related but it didn't join the tables. Chair.objects.all().select_related('table') -
How to serialize ForeignKey in Django rest?
I'm using the latest version of django rest framework. I have this model: class Subscriptions(models.Model): subs_list = models.ForeignKey(SubsList, verbose_name='Subscription list', on_delete=models.CASCADE, related_name='subs_list') # идентификатор подписного листа subscriber = models.ForeignKey(Subscribers, verbose_name='Subscriber', on_delete=models.CASCADE) # идентификатор подписчика created_date = models.DateTimeField(verbose_name='Created date', auto_now=True) # дата добавления подписчика в подписной лист deleted = models.NullBooleanField(verbose_name='Deleted') # True-удален из подписного листа, False/null-в подписном листе How do I serialize it? The main question is how to serialize ForeignKey, that would be associated with the query related data, i.e. NOT: "id": 29, "created_date": "2018-03-01T14:28:41.237742Z", "deleted": false, "subs_list": 1, "subscriber": 1 but like this "id": 29, "subs_list": { "id": 1, "uuid": "d183bab7-af26-48f8-9ef5-ea48e09a95a9", "name": "TEST", "description": "TEST", "created_date": "2018-03-01T13:15:18.808709Z", "deleted": null, "user": 6 }, "subscriber": { "id": 1, "bot_id": "1", "name_messenger": "11", "username": "1", "first_name": "1", "last_name": "1", "created_date": "9999-03-01T16:47:51.440000Z", "subscribed": true, "chat_bot": "1", "phone": "1", "user": 1 }, "created_date": "2018-03-01T14:28:41.237742Z", "deleted": false I have such a serializer: ... class SubscriptionsSerializer(serializers.ModelSerializer): subs_list = SubsListSerializer(read_only=True) subscriber = SubscribersSerializer(read_only=True) class Meta: model = Subscriptions fields = '__all__' When get requests everything is ok, but how to update and add data is not clear, error: IntegrityError at /subscriptions/subscriptions/ null value in column "subs_list_id" violates not-null constraint DETAIL: Failing row contains (41, 2018-03-01 16:10:02.383625+00, f, … -
Django Caught ViewDoesNotExist while renderin
I removed URL "apihget" from my urls list and view function. My current site work, but I cannot open admin URL. Error: Caught ViewDoesNotExist while rendering: Tried apihget in module handapp.views. Error was: 'module' object has no attribute 'apihget' When I return url and view, error left. If I set debugging=true and go to incorrect url -> I see the removed url in list. In forums I find that django save all urls in memory. How I can remove this url? How I can refresh memory? -
django2: How to use different templates?
Say I created a django project called django_site. I created two sub-projects: site1 and polls. You see that I have two index.html in two sub-projects directories. However, now, if I open on web browser localhost:8000/site1 or localhost:8000\polls, they all point to the index.html of polls. How can I configure so when I open localhost:8000/site1 it will use the index.html of site1? Thanks My settings.py in django_site directoryy: .. 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', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] .. My directory structure: E:. | db.sqlite3 | manage.py | tree.txt | tree1.txt | +---site1 | | admin.py | | apps.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | __init__.py | | | +---templates | | \---site1 | | \---templates | | index.html | | | \---__pycache__ | models.cpython-36.pyc | urls.cpython-36.pyc | views.cpython-36.pyc | __init__.cpython-36.pyc | +---django_site | | settings.py | | urls.py | | wsgi.py | | __init__.py | | | \---__pycache__ | settings.cpython-36.pyc | urls.cpython-36.pyc | wsgi.cpython-36.pyc | __init__.cpython-36.pyc | \---polls | admin.py | apps.py | models.py | tests.py | urls.py | views.py | … -
Group a large list of dictionaries by key value in django
I have a list of dictionaries that looks like this: [{'grade': '1', 'past_student_sum': 1611}, {'grade': '2', 'past_student_sum': 1631}, {'grade': '3', 'past_student_sum': 1598}, {'grade': '1', 'current_student_sum': 1611}, {'grade': '2', 'current_student_sum': 1631}, {'grade': '3', 'current_student_sum': 1598}] I got this list by combining 2 query sets in the following fashion: grade_list = list(past_enrollments) + list(current_enrollments) Is there a way for me to combine these in such a way to get a list that looks like this: [{'grade': '1', 'past_student_sum': 1611, 'current_student_sum': 1621}, {'grade': '2', 'past_student_sum': 1511, 'current_student_sum': 1521}] -
Django auth registraion views login redirect
i'm using Django's auth views. I didnt want the 'accounts/' in my registration urls, so changed the them from this: accounts/password_change/ [name='password_change'] accounts/login/ [name='login'] To : from django.contrib.auth import views as auth_views urlpatterns = [ path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('login/', auth_views.LoginView.as_view(), name='login'), ] Now, when a user who is not signed in attemps to access this view, it redirects to: 127.0.0.1:8000/accounts/login/?next=/password_change/ How to I get it to redirect to this instead: 127.0.0.1:8000/login/?next=/password_change/ -
Django login in modal window
all. Can you please help me? I have a small problem. How can i create login with django in popup modal window? For login/registration I use package django-registration-redux, for popup modal window i use jquery form plugin. In the older version of django-registration-redux everything worked, but now i dont know why it is not working. Look please at my code -> JS: function initModalWindowPage() { $('a.modal-form-link').click(function(event){ var link = $(this); $.ajax({ 'url': link.attr('href'), 'dataType': 'html', 'type': 'get', 'success': function(data, status, xhr){ if (status != 'success') { return false; } var modal = $('#myModal'), html = $(data), form = html.find('#content-column form'); modal.find('.modal-title').html(html.find('#content-column h2').text()); modal.find('.modal-body').html(form); initModalWindowForm(form, modal); modal.modal({ 'keyboard': false, 'backdrop': false, 'show': true }); }, }); return false; }); } function initModalWindowForm(form, modal) { form.ajaxForm({ 'dataType': 'html', 'error': function(){ return false; }, 'success': function(data, status, xhr) { var html = $(data), newform = html.find('#content-column form'); modal.find('.modal-body').html(html.find('.alert')); if (newform.length > 0) { modal.find('.modal-body').append(newform); initModalWindowForm(newform, modal); } else { setTimeout(function(){location.reload(true);}, 500); } } }); } $(document).ready(function(){ initModalWindowPage(); }); base.html: <a class="modal-form-link" href="{% url 'login' %}">{% trans "Login" %}</a> ... <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel"</h4> … -
DjangoCMS - Adding a custom field to Aldryn Category
I'm working with Aldryn NewsBlog and Aldryn Categories apps in DjangoCMS and want to add a Category Image field to the Category model and I'm getting confused as to how to make the field show up in the admin panel. All the SO articles I'm finding are on modifying the User or Page model, but that's not what I'm doing. Here's what I have so far: models.py from filer.fields.file import FilerFileField from aldryn_categories.models import Category class CategoryExtension(Category): image = FilerFileField() admin.py class CategoryImageAdmin(admin.ModelAdmin): pass I can't find clear instructions on how to add this additional field to the Category form in admin to allow users to select an image. I was able to create the field just fine I think. I added the models.py code and it made migrations without error. But I'm just struggling to comprehend how to add this field to the existing fields for Categories. -
How to change the django v2.0 admin clores from my application or project
I'm new to django, and I need to change the admin colors of django v2.0, if possible exemplify how a project or application should look. I know that it is possible to modify directly in the installation of django, but it is not convenient. How it should be from my project, where to locate the files. Thanks in advance. -
Django oscar: PermissionError at /dashboard/catalogue/products/1/ [Errno 13] Permission denied: '/media/images'
I recently just started off with django-oscar. I've been checking and testing it out since yesterday and after installing, configuring my settings.py in accordance to the documentation and migrating. I tried to upload a product. But it keeps giving me a Permission denied error. I dont know where I've gone wrong and its really frustrating, been at it for almost 8 hours and I haven't found any solution that works for me. I use a Linux system. Ubuntu 17.10, if that'll help. This is my settings.py (Static and media settings) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'media') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/static/') # Media files where django stores media uploaded by users MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' This is the error I get: PermissionError at /dashboard/catalogue/products/1/ [Errno 13] Permission denied: '/media/images' Request Method: POST Request URL: http://127.0.0.1:8000/dashboard/catalogue/products/1/ Django Version: 1.11.10 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: '/media/images' Exception Location: /home/user/Documents/projects/new- site/sva/venv/lib/python3.6/os.py in makedirs, line 220 Python Executable: /home/user/Documents/projects/new- site/sva/venv/bin/python3.6 Python Version: 3.6.3 Python Path: ['/home/user/Documents/projects/new-site/sva/vogue', '/home/user/Documents/projects/new-site/sva/venv/lib/python36.zip', '/home/user/Documents/projects/new-site/sva/venv/lib/python3.6', '/home/user/Documents/projects/new-site/sva/venv/lib/python3.6/lib- dynload', '/usr/lib/python3.6', '/home/user/Documents/projects/new-site/sva/venv/lib/python3.6/site- packages'] Server time: Thu, 1 Mar 2018 14:44:51 +0000 -
Always include checkbox in filtered result set
I've been exploring Django filters and think the extension works great, but i'm not sure if it can handle what I need. Unfortunately being a new developer i'm not sure what extensions are available. Searching Django filters and the documentation can only get me so far. I have an employee model that has several fields the user will need to be able to search on. Right now i'm using filters and it works great if the user only does a single search and checks a box. I can get the values to POST correctly for a single search, but if the user checks a box and tries to search again the checkbox in the result set is cleared. What I want is for the checkbox to always be included even if the user searches again. Is there an django extension that will perform in this way, if not how about a javascript extension? -
Django makemigrations keeps making the same alteration
I have a django project built with Django 1.10.7 and mysql 14.14 Distrib 5.5.54 If I do: $ python manage.py makemigrations my_app I get: Migrations for 'my_app': my_app/migrations/0023_auto_20180301_1419.py: - Alter field reference on league Then: $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, my_app, sessions Running migrations: Applying my_app.0023_auto_20180301_1419... OK Then, just after, I do: $ python manage.py makemigrations my_app I get: Migrations for 'my_app': my_app/migrations/0024_auto_20180301_1421.py: - Alter field reference on league It seems that django does not make the migrations well, or does but does not detect anything. In models.py, the class is as follows: class League(models.Model): name = models.CharField(max_length=50) id_creator = models.ForeignKey('auth.User', on_delete=models.CASCADE) id_tour = models.ForeignKey('Tour', on_delete=models.CASCADE) step = models.IntegerField(default=0) creation_date = models.DateTimeField(default=timezone.now) reference = models.CharField(max_length=20, default=id_generator()) def __str__(self): return self.name What have I done wrong ? -
How do airbnb and couchsurfing website search host's address in database?
Recently I try to make the feature of search hosts with user input address. I would like to utilize google place Id. And here is my point: Hosts upload their address with google autocomplete and I can store the place id for host's place into my database. Obviously, the place id for UK and London would be different. And what if user search with 'UK' which give one place id to database? How can I show hosts in UK including London? -
django 2.0 pass pk into another template
So basically what I want to do is by using a generated link with the pk: lets say 127.0.0.0:8000/27/ Get access to that pk for use it in another template with an if statement for example: {% for book in Books %} {% if book.pk == category.pk %} <!-- Generate some HTML here--> In my project I generate the links by passing the pk of an object as a variable for example: {% for category in Categories %} <a href="{{ category.pk }}"> in my main urls.py: ... path('<int:pk>/',v.BookList.as_view(slug="pk")), ... in my app/views.py: class BookList(LoginRequiredMixin, ListView): login_url = 'accounts/login/' template_name = 'ListsViews/BookList.html' model = Book context_object_name = "Books" slug = "pk" def get_object(self, queryset=None): return queryset.get(slug=self.slug) (also,the Book model has a ForeignKey that links it to a category)