Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send data to backend from React
I'm creating a web application using django with react and I'm curious how to send data to my database in it. I have a function that is invoked when user presses button, I want this function somehow to send data to the database server. Does anyone know how to approach this problem? I need an idea to get me started. So far my reactjs feeds of data from an API, but now i need to save the contents and save them Regards -
Import global module in django if I have the same module in my app
How do i import a module(e.g. mysite/constants.py) defined at my project level while there is one module at my app level also(e.g. mysite/myapp/constants.py). How do i import global constants mysite/myapp/view.py ? -
Error: The SECRET_KEY setting must not be empty
I have seen many other answers but nothing helped. Things I have tried, os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_name.settings") In both manage.py and wsgi.py file. There is a secret key, in the settings file, but still it shows this. I also tried, $ export SECRET_KEY='value of secret key' There is init.py file there also. I don't know what is the issue. Please help. I am using mongodb as database backend, and it is giving me this error. -
having min clause django dont working same way mysql
This is my database id | room_id | date | qty | rate ---------------------------------------- 1 | 1 | 2017-01-01 | 0 | 500 2 | 1 | 0217-01-02 | 3 | 500 3 | 2 | 2017-01-01 | 3 | 500 4 | 2 | 0217-01-02 | 3 | 500 i need when select this date range (2017-01-01 and 2017-01-03), while a query in django, obtain only the rows that correspond room_id 2, because the room_id 1 has not availability one day that are consulting. I am tring with this, but i dont figured out. def sel_rooms(request, id_hotel, check_in, check_out): hotel = Hotel.objects.get(id_hotel=id_hotel) rooms = Room.objects.filter(hotel=hotel) check_in = datetime.datetime.strptime(check_in, '%Y-%m-%d').date() check_out = datetime.datetime.strptime(check_out, '%Y-%m-%d').date() - timedelta(days=1) stock = Stock.objects.filter(hotel=hotel, date__range=(check_in, check_out)) for room in rooms: avail = stock.annotate(min_q=Min('qty')).filter(min_q__gte=1) -
It's possible to store an array in Django model?
I was wondering if it's possible to store an array in a Django model? I'm asking this because I need to store an array of int(e.g [1,2,3]) in a field and then be able to search a specific array and get a match with it or by it's possible combinations. I was thinking to store that arrays as strings in charfields and then, when I need to search something, concatenate the values(obtained by filtering other model) with '[', ']' and ',' and then use a object filter with that generated string. The problem is that I will have to generate each possible combination and then filter one by one until I get a match and I believe that this might be inefficient. So, I hope you can give me another ideas that I could try. I'm not asking code necessarily, any ideas on how to achieve this will be good. -
test by date in django and javascript
i need to do a test before setting values in my list so , i get a selected value from a combobox and i want to do a test between this value and a variable in my data base . the source code is : first in my template : <select class="form-control" id="date_select" onchange="displayAll();"> <option value="">----- </option> {% for v in v_date %} <option id="" value="{{ v.date}}">{{ v.date}}</option> {% endfor %} </select> so i am gonna do a test with the selected value from the combobox in javascript this is the source code in js var date_test = document.getElementById('date_select').value ; var locations = [ {% for v in vs %} {% if v.date = date_test %} ['okok',{{ v.latitude }},{{ v.longitude}}], {% endif %} {% endfor%} ] the problem is that my source code doesn't work in IF conditions , i don't know if this line is correct {% if v.date = date_test %} ['okok',{{ v.latitude }},{{ v.longitude}}], {% endif %} -
How to create a link between HTML/JS and Django Admin
I would like to create a 'select all' button for this booleans and I don't know how to do it. I know it's hard to create a button like this with django admin so I have to use JS and HTML ? How can I integrate HTML button and JS script into the django admin ? Thanks. -
django - form.cleaned_data[] for all fields in model
I am using django to digitalise a form. This form is a little bit complex, and there are a lot of fields in it. I was wondering if Django could do form.cleaned_data[] for all fields, in stead of declaring variables like obj.fieldname = form.cleaned_data['fieldname'] for each field apart. I tried it with a forloop in the views.py, but that won't work This is the forloop I'm talking about: def get_form_naw(request): if request.method == 'POST': form = Form1(request.POST) if form.is_valid(): for x in Model1(): formname = x.name o = Model1() o.formname = form.cleaned_data[formname] o.save() else: form = Form1 return render(request, 'folder/home.html', context=locals()) I'm using a mysql database. My forms are declared like this: forms.py class Form1(forms.ModelForm): class Meta: model = Model1 exclude = ('id') -
Large sql database for testing [on hold]
I want to practice SQL queries via Django ORM. So I want the dump of a large database. Ideally it should contain hunderds of millions to billions of rows. I was wondering if any such databases are publicly available or not. -
Serve static files with django
Setting up a django site but I can't get it to serve static files. In the settings file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SETTINGS_DIR = os.path.dirname(__file__) PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir) PROJECT_PATH = os.path.abspath(PROJECT_PATH) TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates') STATIC_ROOT = os.path.join(PROJECT_PATH, 'angular/js') STATIC_URL = '/static/' In the template <script src="/static/js/angular.min.js"></script> I can serve the template which is in the main directory angular and inside it is the static folder angular/static/js/angular.min.js -
1146 "app_name.django_site missing"
i am using Django 1.11 for making an app 'cnfs', and i am using MYSQL database with it. I am constantly facing this issue where i am getting an error like this when i type the following code: $python manage.py migrate System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: admin, auth, cnfs, contenttypes, sites Running migrations: No migrations to apply. Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/init.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 227, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal **kwargs File "/home/ubuntu/.local/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 193, in send for receiver in self._live_receivers(sender) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/contrib/sites/management.py", line 20, in create_default_site if not Site.objects.using(using).exists(): File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/query.py", line 670, in exists return self.query.has_results(using=self.db) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 517, in … -
Passing object to included template
I have this simple model: class Book(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1500) page_count = models.PositiveSmallIntegerField() author = models.CharField(max_length=50) I would like to render list of this model objects (passed to template as book_copies). My (simplified) templates: # 'books/list.html' <div> {% for copy in book_copies %} {% include 'books/book.html' with book=copy only %} {% endfor %} </div> and # 'books/book.html' <p> {{ book.title }} - {{ book.author }} </p> It seems that the template variable copy is passed to included template as a str representation of Book model. Therefore, I can't access its fields, e.g. title or author. Is it possible to pass model object without conversion to included template? -
How to subtract current date with date from database - DJANGO MYSQL
Hej I have a Donor table with lastAttendance column. How can I subtract current day with selected lastAttendance date? d0 = Donor.objects.only("lastAttendance") d1 = datetime.now() delta = d1 - d0 error: unsupported operand type(s) for -: 'datetime.datetime' and 'QuerySet' Any help appreciated!! -
Django + Docker + virtualenv + Heroku deployment
I would like to use Docker with my existing Django project in virtualenv and MySQL database. It seems to my that my solution is not optimal (BTW it is not working). My app is not finished, but I wonder if it is possible to deploy it on Heroku and working with it without publishing? I will be grateful if you could show me the best solution. To wit this is my docker-compose.yml: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" db: image: mysql environment: - MYSQL_ALLOW_EMPTY_PASSWORD=yes - MYSQL_USER=root - MYSQL_DATABASE=pri Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pri', 'USER': 'root', 'HOST': 'db', } } Structure of my files looks in this way: DockerContainerDirectory: - docker-compose.yml - Dockerfile - requirements.txt - ProjectDirectory In ProjectDirectory I have virtualenv and Project: - bin - include - lib - pip-selfcheck.json - Project In Project I have git repository, back-end and front-end written in Angular2: - backendFolder - frontendFolder backendFolder: -backendProject backendProject: - my project with `manage.py` etc. -
Many django projects with one admin for all
I have many django projects witch looks the same: there are some Config models and some models user actions Results. The task is to make a one point of Config models contol, keep the history of changes and have authorization (let's call this project Control UI). And I think django admin will be good for it and django-reversion for changes history. What is the best architecture for projects and Control UI interaction? My thoughts: 1.For every project make a connection to Control UI database and keep Config models there. I'll set Control UI as a package dependency for each project and use Config models from the app made for current project. 2.The same with a connection to Control UI database but models are kept in projects and Control UI has all the projects as dependencies. This is the easiest to implement, but Conftol UI may have conflicts in dependencies as each project may use different version of some module. 3.Do nothing with DBs. Make a REST API for each project and make models based on API calls in Control UI. I need models to use in admin. I haven't tested yet, but look like django-reversion won't work for Config models … -
Inject custom javascript code in sw-precache generated service-worker.js
My sw-precache config: new SWPrecacheWebpackPlugin( { dynamicUrlToDependencies: { '/offline': ['./edusanjal/templates/base_react.html'] }, staticFileGlobs: [ "./edusanjal/static/bootstrap/bootstrap.css", "./edusanjal/static/bower/font-awesome/css/font-awesome.min.css", "./edusanjal/static/bower/jquery/dist/jquery.min.js", "./edusanjal/static/bootstrap/tether.min.js", "./edusanjal/static/bootstrap/bootstrap.min.js", "./edusanjal/static/img/**.*", "./edusanjal/static/**.js" ], stripPrefix: "./edusanjal", cacheId: 'edusanjal', filename: 'service-worker.js', runtimeCaching: [{ // "urlPattern": /\/media\/logos\/*.*(jpg|jpeg|png)/, "urlPattern": /[.]?(png|jpg|svg|gif|jpeg|woff|woff2|ttf|eot|html|json)/, "handler": "cacheFirst", "options": { "cache": { "name": "media-content", "maxAgeSeconds": 60*60*24*7 // 7 days old cache be deleted } } }], } ), This config generates offline cache url: '/offline?_sw-precache=b937a446c96c129edf1e1f89d210126d' For offline support if network fail service worker responds with event.respondWith( fetch(event.request).catch(function () { return caches.match('/offline?_sw-precache=b937a446c96c129edf1e1f89d210126d'); }) ); Is there a sw-precache config so I don't have hard code network fail response code rather generate from sw-precache config -
not able to use anaconda packages in django app
I m new in python web development. I m using Django framework but i also need machine learning libraries so after installing django and working on it for a while i have installed anaconda distribution of python and i have directed my interpreter in pycharm to anaconda. The problem is when i import libraries like sklearn or pandas and then i run server, it gives me that error in command prompt PS C:\Users\xxx\desktop\intelligent> python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03C62780> Traceback (most recent call last): File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\utils\a utoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ma nagement\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ma nagement\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ma nagement\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ch ecks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ch ecks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\core\ch ecks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\utils\f unctional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\urls\re solvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\utils\f unctional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.10.6-py3.6.egg\django\urls\re solvers.py", line 306, in … -
How do I add @login_required decorator to the builtin django's logout view?
I am trying to add @login_required to the logout view, but how? -
How to get array of values from checkbox form Django
I have HTML form like this: <p>Models Sizes IDs:</p> <input type="checkbox" name="model_size_ids[]" value="1">XS</input> <input type="checkbox" name="model_size_ids[]" value="2">S</input> <input type="checkbox" name="model_size_ids[]" value="3">M</input> <input type="checkbox" name="model_size_ids[]" value="4">L</input> <button>Submit</button> I'm trying to receive an array of checked values on server side in my View: size_ids = request.data['model_size_ids[]'] But, I can extract only one and the last value. So if I check 2-3 values in checkbox form, I receive only last value in my view. I also tried to name input field without braсkets and the result was the same. Can anybody tell me, how can I solve that? Thanks! -
setting up single sign on with django-mama-cas
I am usign django-mama-cas for sso but it is not working. In local, I can login using after run http://app1.com:8000/login/ i got msg 'you are logged in', but after when i call to login using http://app2.com:8000/login/ It i redirect to login page as a anonymous user for mama-cas i follow $ pip install django-mama-cas Add to INSTALLED_APPS and run migrate: INSTALLED_APPS += ('mama_cas',) Include the URLs: urlpatterns += [url(r'', include('mama_cas.urls'))] See the full installation instructions for details. Upgrade Upgrade with pip: $ pip install --upgrade django-mama-cas How can i fix this issue -
Convert encoding function Python35
I'm porting a Django application from Python27 to Python35. I used 2to3 in order to automated the code translation, but I'm in trouble with a function that converts a string in a specified encoding. The function is the following: def convert_encoding(text, source_encoding=None, destination_encoding='utf-8'): if not isinstance(text, unicode): try: text = unicode(text, encoding=source_encoding, errors='ignore') except UnicodeDecodeError as exc: # write log pass try: text = text.encode(encoding=destination_encoding, errors='ignore') except Exception as exc: # write log pass return text More in detail, this function is used when I need to compare db values to some strings. The db tables are encoded in Latin-1, but I should convert the string in UTF-8. I know that in Python3 all strings are Unicode, so based on what I have understood, I should remove the following piece of code from my function: if not isinstance(text, unicode): try: text = unicode(text, encoding=source_encoding, errors='ignore') except UnicodeDecodeError as exc: # write log pass The problem is raised for example in a unit test that inserts in database (latin-1) via sql file this string '°C'. After the insert, the unit test compare the value from database (I see this character as '°C') to a Python string ('°C') calling the convert_encoding function … -
Problems with false positives for unique_together in django admin using Inlines
I have a Gallery class with position and product and I want to add a unique_together constraint to ensure no images are on the same position. The form uses a GalleryImageInline(TabularInline) form on the product with drag and drop functionality to sort the images. After creating the constraint I realize I need to do some fiddling to move images out of the way to move them around without triggering an integrity error. I'm planning to do this in GalleryImageInline.save_formset(). However, when I'm not reaching the save_formset method as something is validating the unique together constraint before it reaches this method and short circuiting displaying an error for the user complaining that the two images are violating (each others) positions. class GalleryImage(models.Model): product = models.ForeignKey(Product) image = models.ImageField() position = models.IntegerField() class Meta(object): unique_together = (('product', 'position'),) Where do I need to override the validation so I'm not hindering myself from rearranging the positions? -
Django form validation doesn't get triggered
I've seen many questions about django validators not giving the correct responses, but I have a different problem. Mine doesn't even trigger despite being copied from the Django docs example. Here's what I have: models.py def content_file_name(instance, filename): ext = ''.join(filename.split())[:-4] foldername = "%s/%s" % (uuid.uuid4(), ext) return '/'.join(['documents', str(foldername), filename]) class Document(models.Model): docfile = models.ImageField(upload_to=content_file_name) class DocumentImage(models.Model): imagefile = models.ImageField(upload_to=content_file_name) image = models.ForeignKey(Document, related_name='Image', null=True, on_delete=models.CASCADE) views.py def documentlist(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = form.save() newdoc.create_documentfiles() messages.add_message(request, messages.INFO, "Saved") return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render( request, 'list.html', {'documents': documents, 'form': form} ) forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('docfile',) def clean_image(self): file = self.cleaned_data.get('docfile') if file: if imghdr.what(file.read()) != "gif": raise forms.ValidationError("Please upload a .gif file") print('complete'); file.seek(0) return file I have even tried setting the forms.py like this: def clean_image(self): print('test') raise forms.ValidationError("Please upload a .gif file") And I still get neither ValidationError nor test printed in console. Did anyone encounter such a problem? -
Use variable in statement in template
I want to use a variable in {% include %} statement in django templates. Specifically, I am trying to include a template in another template and i need to generate and pass url to be used in a button. How can I achieve this? This is my troublesome part of form.html template: <div class="col-md-12"> {% url 'accountant:gp_taxes:delete_rate' pk=field.value as delete_url %} {% include 'includes/formset_inline.html' with delete_url=delete_url %} </div> and formset_inline.html: <a class="btn btn-s btn-danger" href="{{ delete_url }}"> <i class="fa fa-trash-o" aria-hidden="true"></i>&nbsp; </a> When I look at the url in my browser it is empty (I have <a class="btn btn-s btn-danger" href>). How can I pass the url? EDIT clarification for topic added. -
Adding specific permission to users with different roles in django
I am new to django and I am a bit confused on how the permission works, or if that is what I am supposed to use in my case. So, I have my user/model: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): ROLE_CHOICES = ( (0, ('Student')), (1, ('Proffesor')), (2, ('Administration')) ) role = models.IntegerField(choices=ROLE_CHOICES, default=2) And then I have my views in election/views.py: class MainPage(View) class ElectionList(LoginRequiredMixin, View) class ElectionDetail(LoginRequiredMixin, View) #only administration can create elections class CreateElection(LoginRequiredMixin, CreateView) How can I restrict a simple user (student, for example) to create an election?