Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error Message in request.POST Form not showing up
I've written a normal contact POST-form: def emailView(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): context = {'form': form} return redirect('success_contact') else: form = ContactForm() Then in my form this template tags: <form id="contact_form_post" method="post"> {% csrf_token %} {{ form.name }} {{ form.name.errors }} {{ form.message }} {{ form.message.errors }} <div class="form-actions"> <button type="submit">Submit</button> </div> </form> With this setup, no error message is showing up if the required fields are not filled out. When I'm changing the last line in emailView into form = ContactForm(request.POST) every error message shows up before submitting -> "This Field is required". -
Tables with editable cell in django
How can i make a table view with input boxes and after adding all rows finally save the data together in django. I am using bootstrap table in HTML and dict object is renter on request. i want to build a form with editable table having multiple rows -
New way of implementing enumeration type (choices) in Django 3.0
I've seen a new way to implement enumeration type in the upcoming Django 3.0. The given example is: class Student(models.Model): class YearInSchool(models.TextChoices): FRESHMAN = 'FR', _('Freshman') SOPHOMORE = 'SO', _('Sophomore') JUNIOR = 'JR', _('Junior') year_in_school = models.CharField( max_length=2, choices=YearInSchool.choices, default=YearInSchool.FRESHMAN, ) I used to put my enumerate list in the __init__.py to have a more readable code in models.py because the list (like status or other things can be long). So I was wondering if this new way of implementing could be safely rewritten as following: from my_app import YearInSchool class Student(models.Model): @cached_property def years_in_school_choices(): return YearInSchool Not sure here neither if cached_property is relevant. -
Got an error Django internal server error
Got this error while trying to create a view on Django: raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to h ave any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Tried many solutions online both on deleting one of the url.py folders but none worked out -
how to auto login to a my django app with old credentials
I want to login to my django app using details from another web applications Have tried googling but no clear solution. I thought a rest api could do. -
Django search on date field with MySQL DB
I have a date field in one of my models. I want to develop a search service, which in user sends a query param as search key, for example '?search=2018' and the response would be all rows in data base that their date's year is 2018. Or if the user sent '?search=11' the response would be all rows that either their date's month is 11, or their date's day is 11. I am using django 2 and MariaDB version 10.3.18 -
When i deploy my django app to heroku the site stops working
i have done everything right following a youtube tutorial(https://www.youtube.com/watch?v=MoX36izzEWY) and it's alright but when i push my project to heroku the site stops working and when i run the heroku logs --tail command this is what it gives to me: 2019-12-01T11:40:18.921974+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2019-12-01T11:40:18.921976+00:00 app[web.1]: mod = importlib.import_module(module) 2019-12-01T11:40:18.921978+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module 2019-12-01T11:40:18.921980+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2019-12-01T11:40:18.921982+00:00 app[web.1]: File "", line 994, in _gcd_import 2019-12-01T11:40:18.921984+00:00 app[web.1]: File "", line 971, in _find_and_load 2019-12-01T11:40:18.921986+00:00 app[web.1]: File "", line 941, in _find_and_load_unlocked 2019-12-01T11:40:18.921988+00:00 app[web.1]: File "", line 219, in _call_with_frames_removed 2019-12-01T11:40:18.921990+00:00 app[web.1]: File "", line 994, in _gcd_import 2019-12-01T11:40:18.921992+00:00 app[web.1]: File "", line 971, in _find_and_load 2019-12-01T11:40:18.921994+00:00 app[web.1]: File "", line 953, in _find_and_load_unlocked 2019-12-01T11:40:18.922001+00:00 app[web.1]: ModuleNotFoundError: No module named 'BlogProject' 2019-12-01T11:40:18.922117+00:00 app[web.1]: [2019-12-01 11:40:18 +0000] [10] [INFO] Worker exiting (pid: 10) 2019-12-01T11:40:18.950480+00:00 app[web.1]: [2019-12-01 11:40:18 +0000] [4] [INFO] Shutting down: Master 2019-12-01T11:40:18.950634+00:00 app[web.1]: [2019-12-01 11:40:18 +0000] [4] [INFO] Reason: Worker failed to boot. 2019-12-01T11:40:19.030596+00:00 heroku[web.1]: Process exited with status 3 2019-12-01T11:40:21.000000+00:00 app[api]: Build succeeded 2019-12-01T11:40:24.514282+00:00 heroku[web.1]: Starting process with command gunicorn BlogProject.wsgi 2019-12-01T11:40:27.042695+00:00 heroku[web.1]: State changed from starting to crashed 2019-12-01T11:40:26.888453+00:00 app[web.1]: [2019-12-01 11:40:26 +0000] [4] [INFO] Starting gunicorn 20.0.4 … -
Get available time slots for appointment booking using Django REST framework
I am trying to develop an API for scheduling appointments for several salons. Right now I have models and serializers for the Salon and the Appointment. All appointments can have different durations. The Appointment model looks like this: class Appointment(models.Model): date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() salon = models.ForeignKey(Salon, on_delete=models.CASCADE) How can I return all salons and their available time slots (no appointment at that time) for a given date. So say if a salon is open from 10:00-16:00 and has only one appointment from 11:00-11:30 we would get something like: { "id": 3, "name": "My Salon", "city": "London", "time_slots": [ { "date": "2019-12-01", "start_time": "10:00:00", "end_time": "11:00:00", }, { "date": "2019-12-01", "start_time": "11:30:00", "end_time": "16:00:00", } ] } Right now the only way I can think of is by adding a new TimeSlot model with Salon as Foreign key and saving all time slots in the database and changing them once an appointment is made? However, this does not seem very efficient. Is there a better way of calculating and returning the time slots? -
Am working on a site using django framework and i got this AttributeError telling me 'str' object has no attribute 'get'
`AttributeError at /polls/ 'str' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 2.0.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'get' Exception Location: C:\Python34\lib\site-packages\django-2.0.2-py3.4.egg\django\middleware\clickjacking.py in process_response, line 26 Python Executable: C:\Python34\python.exe Python Version: 3.4.1 Python Path: ['C:\Users\WUESE PHILIP\Desktop\vibezt', 'C:\Python34\python34.zip', 'C:\Python34\DLLs', 'C:\Python34\lib', 'C:\Python34', 'C:\Python34\lib\site-packages', 'C:\Python34\lib\site-packages\setuptools-33.1.1-py3.4.egg', 'C:\Python34\lib\site-packages\django-2.0.2-py3.4.egg', 'C:\Python34\lib\site-packages\pytz-2019.3-py3.4.egg']` polls urls.py from django.urls import path from . import views `urlpatterns = [ path('', views.index, name='index'), ]` views.py from django.shortcuts import render `from django.http import HttpResponse def index(request): return("<h2>Welcome to my First Python Django Project</h2>")` vibezt urls.py `from django.contrib import admin from django.urls import include, path` `urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ]` -
Is there a way of printing user id in uwsgi django log?
I think it would be very convenient to have a user-id in the uwsgi request/response log. I know there's logformat option available in uwsgi. And I don't think user-id could be handled by logformat since it's not something uwsgi natively knows, it's app (my case django)'s data that runs inside uwsgi (if that expression makes sense) On the other hand, there's django logger's format and I guess I could make a middleware that prints a request/response data with user-id although this would be duplication of what uwsgi itself is logging. (although uwsgi's log don't have user-id) -
Call custom function after pagination
I want to call my function when user clicked on pagination button "Next" or "Previous" on this page http://junjob.ru/ I created soulution --- overloaded paginate_queryset method in views.py How can I determine when the user clicked “Next” and when “Previous” ? views.py class HomePageView(ListView): model = Vacancy template_name = 'vacancy_list/vacancy_list.html' paginate_by = 5 page_kwarg = 'vacancy' context_object_name = 'vacancies' def paginate_queryset(self, queryset, page_size): print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx ", self.request.user) """Paginate the queryset, if needed.""" paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_('Page is not “last”, nor can it be converted to an int.')) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) }) vacancy_list.html <!-- Paginator --> <div class="container" style="font-size: 2rem;"> <div class="row justify-content-center"> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="?vacancy={{ page_obj.previous_page_number }}">Previous</a></li> {% else %} <li class="page-item disabled"> <span class="page-link">Previous</span> </li> {% endif %} <li class="page-item disabled"> <span class="page-link">Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span> </li> {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="?vacancy={{ page_obj.next_page_number }}">Next</a></li> {% else … -
Always getting this AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)
I'm very new in django, and currently was following a tutorial and I was trying to test users are listed on user page. So I setup test_admin.py. And i get an AssertionError 302 != 200. Below are my test_admin.py from django.test import TestCase,Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@gmail.com', password='092100027h' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='test@gmail.com', password='092100027h', name='Test User Full Name' ) def test_users_listed(self): """ Test that users are listed on user page """ url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) and this is my admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from . import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] admin.site.register(models.User, UserAdmin) and this is my error Creating test database for alias 'default'... System check identified no issues (0 silenced). F.... ====================================================================== FAIL: test_users_listed (core.tests.test_admin.AdminSiteTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 28, in test_users_listed self.assertContains(res, self.user.name) File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py", line 446, in assertContains response, text, status_code, msg_prefix, html) File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py", line 418, in _assert_contains " (expected %d)" % (response.status_code, status_code) AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected … -
How to filter foreign key item?
I am not sure if I put correct title for what I need but here is the thing. I have two model. class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) device_name = models.CharField(max_length=200, null=True, blank=True ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.device_name) class StatusActivity(models.Model): OFFLINE = 1 ONLINE = 2 STATUS = ( (OFFLINE, ('Offline')), (ONLINE, ('Online')), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) device_id = models.ForeignKey(Device, related_name='status_activity', on_delete=models.CASCADE) status = models.PositiveSmallIntegerField(choices=STATUS) modified_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.device_id) I can get a list of StatusActivity and Device seperately. But what I need is latest status for every device. Devices: Id Created_At Device_name 5b9bbd0f02f8428ca69a582a491f0751 2019-11-30 15:38:37.076440 Temperature Device 17c1ac3ed05844cd879c218effaba15e 2019-11-30 15:39:14.716443 Humidity Device a0ca21a555b246b99be965db4493276f 2019-11-30 15:39:27.822114 Motion Device StatusActivities: Id Status Modified_at Device_id_id 350fed049ba04541a7b6d81932d5824b 2 2019-11-30 15:39:39.849491 5b9bbd0f02f8428ca69a582a491f0751 e4f317b56bbb46eb9309ba77da692af0 1 2019-11-30 15:39:47.912013 5b9bbd0f02f8428ca69a582a491f0751 e0a021dd53734d3b9a15e53ad93bbb28 2 2019-11-30 15:41:04.891823 5b9bbd0f02f8428ca69a582a491f0751 1c12c64708234df6992883b377d3102f 2 2019-11-30 17:12:58.336177 17c1ac3ed05844cd879c218effaba15e 8d280d522baa449588b9a9ab67ed7bae 1 2019-11-30 17:13:05.987487 a0ca21a555b246b99be965db4493276f Example result should be this: ID device_name Status Modified_at 5b9bbd0f02f8428ca69a582a491f0751 Temperature Device 2 2019-11-30 15:39:39.849491 17c1ac3ed05844cd879c218effaba15e Humidity Device 2 2019-11-30 17:12:58.336177 a0ca21a555b246b99be965db4493276f Motion Device 1 2019-11-30 17:13:05.987487 -
How do I get an image to render in weasyprint using a Django Template in production?
I am trying to get an image to render using Weasyprint with Django in production. I can get it to work with debug=True on my local machine, but cannot get it to work on my apache server with debug=True or False or with debug=False on my local machine. It's like it can't render out the url for the image source properly. The PDF is returned properly, and if I stick the {% static 'image.png' %} in the template as text it comes back with: /static/img/image.png What exactly am I missing? My filestructure is as follows: www |__app_root | |__static | | |__img | | |__image.png | |__urls.py | |__views.py |__settings_root |__settings.py settings.py DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'app_root/static') views.py html_string = template.render(context) pdf_file = HTML(string=html_string, base_url=request.build_absolute_uri('/')).write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/print.css')]) # have also tried request.build_absolute_uri() without the '/' template.html {% load static %} <img src="{% static 'image.png' %}"/> Apache Configuration - default-ssl.conf & 000-default.conf Alias /static /var/www/app_root/static <Directory /var/www/app_root/static> Require all granted </Directory> Error Message "GET /static/img/image.png HTTP/1.1" 404 77 -
django for python set up issues
I'm not familiar with using command prompt and having trouble at the start of the django for python set up process which i'm reading here: https://docs.djangoproject.com/en/2.2/intro/tutorial01/ My problem appears to be the 'python' command doesn't work (please see my command prompt screen shot). I tried adding it into 'System variables' in the 'Environment Variables' as shown in the other screen shot. Is there something i have done incorrectly here? Also although i can get the create the initial project the only place i can create it is in the 'c:\Python\Lib\site-packages\django\bin' folder because i have to be looking at this folder in order to run the django-admin.py file. I think the second issue is related to the first issue though i.e. if the 'python' command worked i could just run 'python django-admin.py startproject mysite' while my directory path is set to where ever i want the project to be created. I expect i could simply move the mysite folder to where i want it but i feel i need to understand why this all isn't working as expected before moving on. -
django orm: select_related, fooling reverse foreign key with a fake foreign key addition to the model, what can go wrong?
I am trying to learn how to use Django's ORM for more advanced queries, instead of using raw sql. select_related makes joins to reduce database hits, in principle it could make the joins that I would do manually. But there is a problem: It doesn't use reverse foreign key relationships to make the sql. For the schema I have this is a nuisance. I have found what looks like a surprisingly easy work around, and I'm worried that it will be incorrect in ways I don't understand. I'm using a legacy DB, and it is read-only, and therefore unmanaged by the ORM, and there are no consequences for cascade settings. I have made models for its tables via manage.py analysedb which did a very good job; I have a 6000 line model file, and only needed to spend ten minutes fixing things. One tweak I did was a hack to fool select_related by creating a foreign key relationship which is actually a reverse FK relationship. This means I have two entries in my model pointing to the same database column, which is the primary key (correct) and also now a foreign key. I exploit the "new" column in select_related. The … -
Registering derived child class of abstract class in admin.py in django 2.2
Does anyone know, how to register child class derived from abstract class in admin.py (the abstract class is in file abstract_models.py file) I tried major solution in the web but does not seem to work. It is possible as pointed by various contributors but don't know what I am doing wrong! My folder structure is like this ''' gaasc/ <- project folder contain urls.py, admin.py,models.py,etc gaasc_apps/<- contains all apps core/ abstract_models.py models.py admin.py,... about_app/ models.py, admin.py urls.py ''' I am trying to leverage abstract class inside core app to models inside about_app app. Yes, between different apps. Steps followed: create abstract_models.py and define abstract class import it in core/models.py 3.import the abstract class from core/models.py inside about_app/models.py register the class in about_app/models.py to admin.py(in about_app/) abstract_models.py file(inside core/abstract_models.py) has import uuid from django.db import models class AbstractTimeStampModel(models.Model): """TimeStampModel that holds created_date and updated_date field""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_date = models.DateTimeField("Created date", auto_now_add=True) updated_date = models.DateTimeField("Updated date", auto_now=True) def __str__(self): return self.created_date class Meta: abstract = True class AbstractTextAreaOnly(AbstractTimeStampModel): """Abstract class for textfield""" about = models.TextField( verbose_name="Description", blank=True ) def __str__(self): return "Textonly class-"+self.id class Meta: ordering = ['created_date'] models.py in core/models.py from django.db import models from .abstract_models import … -
SQL or django query to find the similar entries
I want to return the user a list of similar tasks. Two tasks A and B are considered similar if all the words in task A exist in task B or vice versa. I tried the query given below but couldn't get the required result. SELECT t1.task FROM todolistapp_todo t1 LEFT JOIN todolistapp_todo t2 ON t1.task in (t2.task) and t1.id != t2.id; I'm able to do this by the nested loop. But I want to do it by simple expression. similar = set() for task in tasks: for nested_task in tasks if (task.task in nested_task.task or nested_task.task in task.task) and task.id != nested_task.id: similar.add(task) -
pass pk to CreateView form in django
i'm new to django. I have a model that looks like this: models.py class Intervention(models.Model): subject = models.CharField(max_length=200) begin_date = models.DateField(default=datetime.datetime.today) end_date = models.DateField(default=datetime.datetime.today) description = models.TextField(blank=True) speaker = models.ForeignKey(CustomUser, on_delete=models.CASCADE) campus = models.ForeignKey(Campus, on_delete=models.CASCADE) class Meta: verbose_name = 'Intervention' verbose_name_plural = 'Interventions' def __str__(self): return self.subject class Evaluation(models.Model): interventions = models.ForeignKey(Intervention, on_delete=models.CASCADE) student_id = models.CharField(max_length=20) speaker_knowledge_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) speaker_teaching_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) speaker_answer_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) slide_content_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) slide_examples_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) comment = models.TextField(blank=True) The idea is when that the student enter the website on home page he have to choose the campus where he study then he is redirected to a page where he see only interventions of his campus then when he choose the intervention he get the detail of it : Home page screen Interventions page Intervetion detail page Everything is working so far. Now on "intervention detail page" when the user click on "give mark" he is redirected to a page to create mark (i use CreateView class-based) like below: create mark Now my question is how can i replace Modelchoicefield in the generated form by pk of the intervetion that student want to give a mark? Views.py class CreateEvaluationView(CreateView): form_class … -
How to disable or hide assign/redirect button if the ID already exist in other table on django
class Patient(models.Model): name = models.CharField(max_length=50) active_choices = [('Yes', 'Yes'), ('No', 'No')] active = models.CharField( max_length=6, choices=active_choices, default='Yes') def __str__(self): return self.name The other one is: class Ticket(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) is_active = models.IntegerField(default=1) def __str__(self): return self.patient.name In the Views.py @login_required def PatientView(request): form = PatientModelForm(request.POST or None) patients = Patient.objects.order_by('-id') ticket_list = Ticket.objects.filter(is_active=0) total = patient_list.count() if form.is_valid(): obj.save() messages.success(request, 'Patient was added successfully.') return redirect('/dashboard/patient') context = { 'form': form, 'patients ': patients , } return render(request, 'dashboard/patient.html', context) The other view for ticket: @login_required def TicketToGenerateView(request, pk): ticket = get_object_or_404(Patient, pk=pk) form = TicketModelForm(request.POST or None) if form.is_valid(): obj.save() messages.success(request, 'Patient assigned successfully.') return redirect('/dashboard/ticket') context = { 'form': form, 'ticket': ticket, } return render(request, 'dashboard/ticket.html', context) So I want to hide this bellow link button if patient.pk already exist in the Ticket model and is_active = 1 So it displays all rows with assign link button. <a href="{% url 'dashboard:ticket_to' patient.pk %}" name="doctor" class="btn btn-dark btn-sm" data-toggle="tooltip" title="Assign to a Doctor"> <span class=" fa fa-user-md "></span> </a> -
I want a feature to unregister model but in wagtail model admin
Suppose one model admin registered in wagtail model admin but i want to add/change in this registered modeladmin.So, how to add extra field in list_display in already registered modeladmin in wagtail? Please tell me idea about this problem or any method to unregister modeladmin in wagtail. -
How to setup Nginx server for angular and django
I'm trying to deploy a web application to my server. I have put the html files in one folder and I have a django server running on the same server. I am using nginx to set up reverse proxy for the backend but for some reason I'm not able to route to backend urls. Here is my nginx configuration: server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 301 https://example.com$request_uri; } server { listen [::]:443 ssl ipv6only=on; listen 443 ssl; server_name example.com example.com; root /var/www/html/; index index.html; # Let's Encrypt parameters ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location / { try_files $uri $uri/ = index.html; } location /api { proxy_pass http://unix:/run/gunicorn.sock; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; } } In the first block..I'm setting fallbacks to index.html because it is an angular app. The angular app runs fine. But I'm not able to access the routes of the reverse proxy server, whenever I hit a route with /api/something it takes me back to the angular app i.e index.html -
Create API for geojson data in django
I know we can use django rest framework for creating API for normal data. But I'm confused can we use django rest framework for geojson data. I'm mean i want to build location based web app using django and I also want to manipulate the data from android app or ios app. So here I'm confused can i use django rest framework or somethings else. Here I'm using PostgreSQL and postgis for data storage. -
How to set small icon size for`tinymce` in mobile screens?
I added tinymce4-lite in my Django application. The size of icons looks the same in bigger screens and small screens. Big Screens: Small Screens: the size of icons are similar in either big and small screens. I want it to be smaller and more elegant in mobile size screens. This is the configuration in settings.py: TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'menubar': False, 'statusbar': False, 'width': '100%', 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | bullist numlist table | | link image media | codesample | hr visualchars | ''', 'contextmenu': 'formats | link image', 'remove_linebreaks': False } Please help me with this. Thank you -
How to show BinaryField image preview in Django admin interface?
I've got web project with Django backend for which I decided to store images as BinaryField, it seemed to be more convenient for me in case of making backups and restoring them. At first I've created model: class ThermalSource(ClusterUnit): ... scheme_image = models.BinaryField(verbose_name='Scheme', blank=True, null=True, editable=True) ... Then created serializer to use in viewset (I know it is not related to admin interface, but maybe it will be useful): class Base64BinaryField(serializers.Field): def to_representation(self, value): from base64 import b64encode return b64encode(value) def to_internal_value(self, data): from base64 import b64decode return b64decode(data) class ThermalSourceSerializer(APAMModelSerializer): ... scheme_image_base64 = Base64BinaryField(source='scheme_image') ... Now I could get and set images converted to Base64 correctly via Django REST Framework. Admin class for ThermalSource looks so now: class ThermalSourceForm(forms.ModelForm): scheme_image = forms.FileField(required=False) def save(self, commit=True): if self.cleaned_data.get('scheme_image') is not None \ and hasattr(self.cleaned_data['scheme_image'], 'file'): data = self.cleaned_data['scheme_image'].file.read() self.instance.scheme_image = data return self.instance def save_m2m(self): # FIXME: this function is required by ModelAdmin, otherwise save process will fail pass class ThermalSourceAdmin(admin.ModelAdmin): form = ThermalSourceForm readonly_fields = ('id', ) list_display = ('id', ... 'scheme_image') But when I open Django admin interface, I could only download files to scheme image field, no preview is configured. Could anybody suggest me how could I …