Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django page not loaded with exception 'bytes' object is not callable issue
I'm doing downloading of the file in Django. I have added path into urls.py and in views.py trying to make code which will be loading a file and render page. def download(request): render(request, 'personal/home.html') # seems that it doesn't work filename = "C:/some_path/test_file.txt" wrapper = FileWrapper(open(filename)) response = HttpResponse(wrapper, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename) response['Content-Length'] = os.path.getsize(filename) return response As the result I got: Exception Type: TypeError Exception Value: 'bytes' object is not callable Can someone help with this? -
Get count of all clients invoices with multiple status id
my invoice Model : class Invoice(models.Model): client = models.ForeignKey(Clients) invoice_number = models.CharField(max_length=100) invoice_status = models.ForeignKey(Status, on_delete=models.CASCADE,null=True) Status model: class Status(models.Model): invoice_status = models.CharField(max_length=50) client model: class Clients(models.Model): name = models.CharField(max_length=50) address = models.TextField(null=True, blank=True) contact_person = models.CharField(max_length=50, null=True, blank=True) Status will be 1.Draft 2.Sent 3.Paid i tried multiple methods but all failed invoices = Invoice.objects.values("client").aggregate(Paid=Sum(Case(When(invoice_status__id=1, then=1),output_field=IntegerField()))) i like to get all clients invoices status count expected result: client_id:1, Draft:4(count), Sent:5(count), Paid:0(count) -
Django : RelatedObjectDoesNotExist in view but works fine in Admin
I am getting a (RelatedObjectDoesNotExist: UserProfile has no site) error in one of my views yet I am able to perform all CRUD operations in the admin with out any errors. Excerpt from models.py class Sites(models.Model): name = models.CharField(max_length=255, blank=True, null=True) active = models.NullBooleanField() created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) logo_file_name = models.CharField(max_length=255, blank=True, null=True) logo_content_type = models.CharField(max_length=255, blank=True, null=True) logo_file_size = models.IntegerField(blank=True, null=True) logo_updated_at = models.DateTimeField(blank=True, null=True) logo_path = models.CharField(max_length=255, blank=True, null=True) account_type = models.CharField(max_length=255, blank=True, null=True) def __str__(self): site_str = 'id = {}, name = {}'.format(self.id, self.name) return site_str class Meta: managed = True db_table = 'sites' class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) site = models.ForeignKey(Sites) def __str__(self): user_profile_str = '{}: {}'.format(self.user.username, str(self.site)) return user_profile_str Excerpt form views.py @login_required def client_list(request): user_profile = UserProfile(user=request.user) print(user_profile.user.username) clients = Clients.objects.filter(site_rec=user_profile.site) return render(request, 'snapreport/clients/all_clients.html', {'clients': clients}) -
Use prefetch_related in django_simple_history
I have a model Booking which has a history in it. like this and I use django_simple_history class Booking(CreatedAtAbstractBase): history = HistoricalRecords() And I use a management command to do task. In that I wanted to Prefetch history when taking a booking booking_p_history = Booking.history.filter(s_id=6).order_by( 'updated_at').first() booking_obj_list = Booking.objects.select_related(...) \ .prefetch_related( Prefetch('booking_history', queryset=booking_p_history, to_attr='driver_pickup_history') ,'booking_history') \ .filter(...) How to use simple history inside prefetch? -
Django permissions in checkbox form
I have a template in which I edit all the basic fields of a model User. Now I want to have a form in which there will be displayed all available permissions in a checkbox-like style. The ones allready assigned to the User should allready be checked. I have a form.py, with form for editing User, but have not completed the permissions form. class UserSettingsForm(forms.ModelForm): class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'urnik', 'ure_na_teden', 'rfid', 'oddelek', 'status_zaposleni', ) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(UserSettingsForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) self.fields['username'].disabled = True def save(self): user = super(UserSettingsForm, self).save() return user class UserPermissonsForm(forms.ModelForm): class Meta: model = Permission fields = ( 'name', 'content_type', 'codename', ) And a views.py: @login_required def uporabnik_uredi(request, username=None): user = get_object_or_404(User, username=username) uporabnik_form = UserSettingsForm(request.POST or None,request=request, instance=user) permissions = [(p.id, p.name) for p in Permission.objects.filter(user=user)] data = { 'uporabnik' : user, 'form' : uporabnik_form, 'from': request.GET.get('from', None), 'permissions' : permissions, } if request.POST: if uporabnik_form.is_valid(): user = uporabnik_form.save() next = request.GET.get('next', None) return redirect(next) return render(request, "sifranti/uporabniki/uredi.html", data) And a template, just to see which current permissions are assigned to the user: <div class=""> {% for id, … -
Django Template Error on Template Directory PyCharm Project basic problems
manage.py@vamshi1 > createsuperuser "C:\Program Files\JetBrains\PyCharm 2017.1.5\bin\runnerw.exe" C:\Users\V********\untitled\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2017.1.5\helpers\pycharm\django_manage.py" createsuperuser C:/Users/V********/PycharmProjects/vamshi1 System check identified some issues: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DIRS. Username (leave blank to use 'v*********'): -
Jinja2 - display delete button in particular html table row if condition is true
I'm trying to create an if else condition using jinja2 where only table row with the status pending_approval or scheduled will display a delete button beside it. But I'm having trouble figuring it out because all the data in the table is displayed in a for loop. Any help is much appreciated Below is my code : model.py class Leave(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='+') type = models.ForeignKey(LeavesType, on_delete=models.CASCADE, related_name='+') status = (('cancelled', 'Cancelled'), ('taken', 'Taken'), ('pending_approval', 'Pending Approval'), ('scheduled', 'Scheduled'), ('weekend', 'Week End'), ('public_holiday', 'Public holiday'), ) status = models.CharField(max_length=50, choices=status, default='pending_approval') view.py def my_leaves_view(request): leaves_log = Leave.objects.all().filter(employee=request.user.profile.employee.id) context = {'leaves_log': leaves_log} return render(request, 'hrm/employee/details/my_leaves.html', context) html <table id="Log" class="display table table-hover table-responsive leaves-table"> <thead> <tr> <th class="small text-muted text-uppercase"><strong>Leave Type</strong></th> <th class="small text-muted text-uppercase"><strong>Status</strong></th> <th class="small text-muted text-uppercase"><strong></strong></th> </tr> </thead> <tbody> {% for field in leaves_log %} <tr> <td>{{field.type}}</td> <td><img class="media-object img-circle status-icon-size" src="/media/dashboard/ui/file_status/{{field.status}}.png" style="display: inline-block; height: 24px; margin-right: 10px;">{{field.status}}</td> <td><div class="btn-group"> {% if field.status == 'pending_approval' or 'scheduled'%} <button type="button" class="btn btn-default btn-xs dropdown-toggle active" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Action <span class="caret"></span> </button> <ul class="dropdown-menu dropdown-menu-right"> <li onclick="delete_leaves();"> <a href="/hrm/employee/{{field.id}}/delete/" onclick="return confirm('Are you sure you want to delete this item?');"> <i class="fa fa-fw fa-trash text-gray-lighter m-r-1"></i>Withdraw </a> </li> … -
Django how to set value of hidden input in template
How to set value of who and image in template? class CommentForm(ModelForm): who = forms.CharField(widget=forms.HiddenInput()) image = forms.ImageField(widget=forms.HiddenInput()) class Meta: model = Comments fields = ['who', 'image', 'content'] It doesn't work (raw text): <form method='POST' action=''> {% csrf_token %} {% render_field comment_form.content class="form-control form-control-sm" placeholder='Comment..' %} {% render_field comment_form.who class="form-control form-control-sm" value='{{ request.user.profile.pk }}' %} {% render_field comment_form.image class="form-control form-control-sm" value='{{ image.pk }}' %} <input class="btn btn-primary btn-sm" type="submit" value="Add comment"> </form> -
How to make Django modify a little each `order_by` queryset in a certain way?
SQLite normally sorts strings according to the C locale, which yields awfully wrong results for many languages (like mine). This answer: https://stackoverflow.com/a/615284/4385532 offers a remedy for this issue. It requires setting collation explicitly on a per-query basis. So, instead of writing for example: SELECT * FROM some_table ORDER BY name; We are required to write: SELECT * FROM some_table ORDER BY name COLLATE POLISH; Which will work after some certain setup. But Django tries to be very smart and writes all SQL for us. So it would be very nice if we could somehow tell Django to append this COLLATE POLISH part to every query it writes that contains an ORDER BY clause if the ordering key happens to be a string. Of course, it would be even nicer if we could tell Django to do this only if the backend is SQLite. -
Getting error while doing subprocess call using Python and Django
I am getting some error while running the .sh script using Python and Django. The errors are given below. Traceback (most recent call last): File "cell.py", line 3, in <module> subprocess.call(shlex.split('./test.sh param1 param2')) File "/usr/lib/python2.7/subprocess.py", line 522, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 13] Permission denied I am explaining my code below. cell.py: import subprocess import shlex subprocess.call(shlex.split('./test.sh param1 param2')) test.sh: #!/bin/sh echo $1 echo $2 exit 0 While I was running the file I am getting the above error. Please help me to resolve this error. -
How to add relationship in Django fixtures without primary key?
I'm working with Django Framework. I have two models: Component and ComponentProperty. class Component(models.Model): name = models.CharField(unique=True, max_length=255) component_properties = models.ManyToManyField(ComponentProperty) class ComponentProperty(models.Model): label = models.CharField(unique=True, max_length=255) component_type = models.CharField(max_length=255) I'm trying to load data with fixtures. I wrote and fixture file that look like this: [ { "pk": 1, "model": "api.componentproperty", "fields": { "label": "label", "component_type": "text" }}, { "pk": 2, "model": "api.componentproperty", "fields": { "label": "description", "component_type": "text", }},{ "pk": 1, "model": "api.component", "fields": { "name": "text", "component_properties": [1, 2]}}] That's work fine! But I have 20 fixtures to load. I want to have fixture look like this bellow: [{ "pk": 1, "model": "api.component", "fields": { "name": "text", "component_properties": [{ "pk": 1, "model": "api.componentproperty", "fields": { "label": "label", "component_type": "text" }}, { "pk": 2, "model": "api.componentproperty", "fields": { "label": "description", "component_type": "text", }}]}}] The icing on the cake must be fixtures specifying a primary key like here. Please, can anyone help me to write these fixtures without pk and the relationships described above? -
Django: understanding how to serve static files during deployment -- NOOB edition
I am struggling with getting my static files to work. Before one starts posting links to the docs, I have been to and read to the best of my having-completed-the-django-tutorial-level understanding the following links: https://docs.djangoproject.com/en/1.11/topics/files/ https://docs.djangoproject.com/en/1.11/howto/static-files/ - https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.FileField I will state that I think the second of which is super confusing. In short, none of my attempts to remedy my issues using the docs have succeeded. So I would appreciate someone walking me through what is going on. First, I have an app, my_app. In my_app I have an model which has an image field that looks like this: def my_app_dir_path(instance, filename): return 'my_app/static/my_app/images/other_{0}/{1}'.format(instance.other.id, filename) MyModel(models.Model): other = models.ForeginKey("other", on_delete=models.CASCADE) image = models.ImageField(upload_to=my_app_dir_path) in short, files that I upload go to the namespaced local static directory: /my_app/static/my_app/images/other_<id>/<image_file> as it says I should do in (4) under configuring static files for the link howto static files. Great. I have a dummy view that I am using to try and see if I can get my image to load: #/my_app/views.py def dummy(request): img = MyModel.objects.first() return render(request, 'my_app/dummy.html', {'img':img}) which bascially is just this #dummy.html <img src="{{ img.image.url }}" /> looking at the website inspector, we see that the url that is … -
python - Cron on Amazon EC2 doesn't execute django command
I have a django script to send a slack report about the number of object Open Position be created everyday and it should be run daily at 18:00. When I run the cron in my computer, it only work when I add SHELL=/bin/bash into the cron file). SHELL=/bin/bash * * * * * source /the_virtual_env_path/bin/activate && cd /my_project_path/ && ./manage.py daily_slack But when I add the those commands to the cron on my Amazon EC2 instance, nothing happens. I tried to add some environment variables in the shell which not in cron environment (via this answer), restart the cron but it didn't work. But if I run the commands manually it run properly. This is the code for my script: # -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError from slackclient import SlackClient from human_resource.models.recruitment import OpenPosition, TimeMarkForSlackReport import datetime import os slack_token = 'my_slack_token' sc = SlackClient(slack_token) contents = [] attachments = [] class Command(BaseCommand): def handle(self, *args, **options): today = datetime.date.today() today_open_position_queryset = OpenPosition.objects.filter(created_at__date=today) count = 0 if(len(today_open_position_queryset) != 0): for open_position in today_open_position_queryset: count += 1 open_position_details = [ { "title": open_position.name, "value": "Position: " + open_position.position.position_name + " | Team: " + open_position.team.team_name + " … -
How to use .sh script to echo the messages using Python and Django
I need some help. I need to echo the messages using .sh script using Python and Django. I am explaining my code below. def plantsave(request): """ This function to save the reactor data . """ if request.method == 'POST': rname = request.POST.get('react')#Reactor1 ,Reactor2,Reactor3 if 'strt' in request.POST: status = 1#Running if 'shutbt' in request.POST: status = 0#Stop if 'susbtn' in request.POST: status = 2#Suspend Here I need to echo the message like Reactor1 is running if the status=1 and Reactor2 is stop if status=0 like this using .sh script. Please help me. -
auto save in django list display mode
here is my code for admin.py with a model named BASE2 class Base2Admin(ExportMixin, admin.ModelAdmin): resource_class = Base2Resource filter_horizontal = ('images',) list_display = ('id', 'name','description','promoted', 'slug') search_fields=['name','description', 'slug'] list_editable = ('name', 'description','promoted', 'slug') so now i get list display of all my data but what i want is that in admin in list mode the data should get saved on every keystroke. basically i do not want to click on the save button below -
List Field in Model-- Django
I am newbie in django,working on rest API framework. I want to ask the user for certain details to be put in html format, like popularity, name of some book. A book can belong to various category such as Friction, Romantic, Action. So I want to have a list Field for category. Two options can be given, one ask the user to enter the category and append in the list at the backend. Or provide a list from which user can choose. Have tried the below code in model.py from django.db import models class Category(models.Model): category = models.CharField(max_length=100) def __str__(self): return self.category class Books(models.Model): name = models.CharField(max_length=100) date = models.DateTimeField() category = models.ManyToManyField(Category) #category = models.ForeignKeyField(Category) #tried Foreign key Model Field also def __str__(self): return self.name Please help me out. Is that the correct approach or should try something else. Thanks in advance. -
Django send email with attachement
i'm trying to send some files in mail using django EmailMessage class the files attachement that i want to send are in DB, provided by each user during registration to my site. i'have tried this but it does not work myapp/views.py: from django.core.mail import EmailMessage def contactUber(request,id): user = User.objects.get(id=id) msg = EmailMessage( 'Hello', #subject 'Body goes here', #content 'vitalysweb@gmail.com', #from ['uber@uber.com'] #to ) msg.attach_file(user.profile.id_card.url) #the file that i want to attach msg.send() messages.success(request, "Email envoyé avec succes") #success msg return redirect(user_detail, id=str(id)) myapp/models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(('Date de naissance'), null=True, blank=True) #DOCUMENTS TO UPLOAD id_card = models.FileField(('Carte Nationale d\'Identité'), upload_to='documents/CNI') drive_licence = models.FileField(('Permis de conduire'), upload_to='documents/RIB') uploaded_at = models.DateTimeField(('Ajouté le'), auto_now=True) docs_are_checked = models.BooleanField(('Documents validés'), default=False) Traceback: Traceback (most recent call last): File "C:\venvs\env1\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\venvs\env1\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\venvs\env1\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\djangoprojects\mysite\mysite\core\views.py", line 272, in contactUber msg.attach_file(user.profile.id_card.url) #the file that i want to attach File "C:\venvs\env1\lib\site-packages\django\core\mail\message.py", line 394, in attach_file with open(path, 'rb') as file: FileNotFoundError: [Errno 2] No such file or directory: '/media/documents/CNI/1847635-2524541_FZLHlIr.jpg' [16/Aug/2017 12:10:27] "GET /core/send_mail_uber/16/ HTTP/1.1" 500 73307 -
PyCharm: Cannot find Sphinx in selected interpreter
I am trying to create documentation using Sphinx in PyCharm and it does not work. I already tried using the terminal command make html and it seems to work just fine. When I try to run Sphinx task in PyCharm it raises this error: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/rest_runners/sphinx_runner.py", line 5, in <module> from sphinx import cmdline File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/sphinx/cmdline.py", line 24, in <module> from sphinx.application import Sphinx File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/sphinx/application.py", line 33, in <module> from sphinx.environment import BuildEnvironment File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/sphinx/environment/__init__.py", line 45, in <module> from sphinx.util.websupport import is_commentable File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/sphinx/util/websupport.py", line 11, in <module> from sphinxcontrib.websupport.utils import is_commentable # NOQA File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/sphinxcontrib/websupport/__init__.py", line 13, in <module> __import__('pkg_resources').declare_namespace(__name__) File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 646, in _load_unlocked File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg/pkg_resources/__init__.py", line 3017, in <module> File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg/pkg_resources/__init__.py", line 3003, in _call_aside File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg/pkg_resources/__init__.py", line 3045, in _initialize_master_working_set File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg/pkg_resources/__init__.py", line 2577, in activate File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg/pkg_resources/__init__.py", line 2151, in declare_namespace File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg/pkg_resources/__init__.py", line 2091, in _handle_ns File "/Users/wtekimam/PycharmProjects/doctor/myvenv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg/pkg_resources/__init__.py", line 2120, in _rebuild_mod_path AttributeError: '_NamespacePath' object has no attribute 'sort' During handling of the above exception, another exception occurred: Traceback (most recent call last): File … -
Firefox very slow with forEachFeatureatPixel
Firefox and IE are operating REALLY slowly with OPENLAYERS 3 when using the forEachFeatureatPixel function. I'm trying to find a way to speed it up. Essentially, the application (found at www.penguinmap.com) has as popup that comes up when the user hovers over a point on the map. But Firefox struggles with this feature. I'm looking for help with the following code to speed it up: var selectMouseMove = new ol.interaction.Select({ condition: function (e) { return e.originalEvent.type == 'mousemove'; }, style: hoverStyle }) // Change cursor var target = map.getTarget(); var jTarget = typeof target === "string" ? $("#" + target) : $(target); // On Hover, change the mouse cursor and display the name of the site $(map.getViewport()).on('mousemove', function (e) { var pixel = map.getEventPixel(e.originalEvent); var feature = map.forEachFeatureAtPixel(pixel, function (feature, layer) { return feature; }); if (feature) { map.addInteraction(selectMouseMove) jTarget.css("cursor", "pointer"); var geometry = feature.getGeometry(); var coord = geometry.getCoordinates(); popup.setPosition(coord); $(element).popover({ 'placement': 'top', 'html': true, 'content': feature.get('site_name') }); $(element).popover('show'); } else { map.removeInteraction(selectMouseMove) jTarget.css("cursor", ""); $(element).popover('destroy'); } }); var element = document.getElementById('popup'); var popup = new ol.Overlay({ element: element, positioning: 'bottom-center', stopEvent: false }); map.addOverlay(popup); -
django multi level many to one query data retrieve
I have bit complex database model structure, see below(only the structure) class Service(models.Model) fields ..... class ServiceBillPost(models.Model): service = models.ForeignKey(Service, related_name='service_bill_posts') class Payment(models.Model): bill_post = models.OneToOneField(ServiceBillPost) mode = models.PositiveSmallIntegerField(choices=PAYMENT_MODE, default=0) PAYMENT_MODE = ( (0, 'Cash'), (1, 'bKash'), (2, 'CreditCard'), (3, 'Cheque'), (4, 'Company'), ) now i want to fetch , all ServiceBillPost of a Service which payment mode is company. i have service_id, say 1, then i have get that service, service = Service.objects.get(pk=service_id) then get all the service bill post, service_bill_post = service.service_bill_post.all() but here how can i filter by payment mode of mode field of Payment model according to the above given relationship using django ORM? -
Django Heroku DataError when populating database from script
I have made a script that reads xml file and populates database from it. When I run it locally it works with no problems. But when I run it on heroku it goes through and populates some data (exactly 6 objects), but then throws this error: skripta_vnos.py is my populating script I run it in shell Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/skripta_vnos.py", line 97, in <module> dob.save() File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 806, in save force_update=force_update, update_fields=update_fields) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 836, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 922, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 961, in _do_insert using=using, raw=raw) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 1063, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) DataError: value too long for type character varying(100) my model looks like this: class Supply(models.Model): name = models.CharField(max_length=255) maticna = … -
Django: best way to handle foreign key requests in template pages
Suppose you are making a site to simply list your products. You want to upload an unspecified number of pictures for your each of your products. So you, following Django's many-to-one documentation, make two models: # files stored under my_app/static/my_app/product_images/product_<id>/<img_name> def product_img_dir_path(instance, filename): return 'my_app/static/my_app/product_images/product_{0}/{1}'.format(instance.product.id, filename) class Product(models.Model): name = models.CharField ... ... # other attributes of the product, e.g. price, etc class ProductImage(models.Model): product = models.ForeignKey("Product", on_delete=models.CASCADE) image = models.ImageField(upload_to=product_img_dir_path) Now if I want all of the images for say product 1, I can retrieve them using: ProductImages.objects.filter(product__pk=1) My question starts here. Suppose you want an index page which just shows the listings for all of your products and for simplicity, the first image associated with each product. You make a template page with {% for product in product list %} <div class="product-listing" style="display:inline"> <!-- image for product goes here --> <!-- brief description goes here --> </div> {% endfor %} where product_list was passed in your context: # inside /my_app/views.py def index(request): ... context = {"product_list": Product.objects.all()} ... Question: what is the best way to also have access to the images for displaying the images in the template page? Currently I thought constructing a parallel image list would … -
django and bootstrap modal with custom content
I want to iterate through photo comments in bootstrap modal, photo which src I sent to modal. Is there a way to put in bootstrap modal some of django information? From bootstrap docs (using jQuery): <script> $('#Modal').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) var recipient = button.data('whatever') var modal = $(this) modal.find('.modal-title').text('New message to ' + recipient) modal.find('.modal-body input').val(recipient) }) </script> In that way I can put information from modal trigger to certain tag in modal, for example .modal-title or whatev. And I do it with some image that shows in modal: $('#PhotoModal').on('show.bs.modal', function (e) { var image = $(e.relatedTarget).attr('src'); $(".modal-photo").attr("src", image); }); To that modal: <div class="modal fade" id="PhotoModal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content" role="document"> <div class="modal-body"> <div class="container"> <div class="row"> <div class='col'> <center><img class="modal-photo" src=""></center> #my custom img </div> <div class="col-4"> # {% Add a comment loop %} </div> </div> </div> </div> </div> And that is element which triggers the modal: <a class="overlay" data-toggle="modal" data-target="#PhotoModal" src="{{ image }}">...</a> My question is if I can do in modal some iteration. I have some class: class Comments(models.Model): who = models.OneToOneField(Profile, related_name='comments') image = models.OneToOneField(ProfileImages, related_name='comments') content = models.CharField(max_length=255, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) And I want do in … -
Sorting list based on Ranking (push/remove elements) in Django
I'm searching for a looping and ranking algorithm for python to use in Django. So I have a list of topics/posts each one of them with ranking. Post Rank A 1 B 2 C 2 D 3 E 4 .............. Each day 3 of this post are shared and need to be moved to the bottom of the list and the new order will become D, E, A, B, C From time to time new posts are added to the top of the lists(random no specific interval of time or number of posts), and will be: X,Y,Z,D,E,A,B,C After are shared: D, E, A, B, C, X, Y, Z If I use a list with push and pop can be achieve easily, but I need to get the data from the database every time I share, with less queries as possible. Also I want to offer the possibility that some of the posts will be excluded from the sort, even if in past were used or will be used in the future. I will use Django Models. -
Django save inline forms without saving main form
I have a model article which has a GenericRelation with the model picture. the model picture in turn has a GenericForiegnKey. in my admin for article I have an inline form for the pictures which works fine. my picture inline form has a readonly field which is a link to the picture. I want to be able to see the link before I save my article therefore I need to save the inline form (with a button for example) separately while I'm still editing my articel. is that even possible? and how would one do that if it is? thanks.