Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PUDB window in django app keeps scrolling
I am using PUDB to debug a Django app that runs in a docker container. When the PUDB window opens up in the terminal, the same terminal keeps receiving logging output, causing the PUDB window to be overwritten. I have to press CTL l to refresh the screen. Is there a way to keep the PUDB window up without any scrolling? -
How to get jQuery datepicker in loop in django template?
I would like to have the datetimepicker in the input. I can get the clock in the first entry only. how can I get the datetimepicker in all the inputs? Thank you Here is my html: <div> <table class="table table-hover" border="1" cellpadding="5" cellspacing="5" width="100%" style="width:100%"> <tr> <th>Start</th> <th>End</th> <th>Update</th> </tr> {% for b in time_layer %} <tr scope="row"> <form action="/app/ok_go/" method="get" autocomplete="off" > <td><input type="text" name="Start" id="Start" value = "{{ b.Start|default:'' }}" size="1"></td> <td><input type="text" name="End" id="End" value = "{{ b.End|default:'' }}" size="1"></td> <input type="hidden" name="id_path" id="id_path" value = "{{ request.build_absolute_uri }}" > <td><input class="btn btn-primary btn-sm" type="submit"value="Update"/></td> </form> </tr> {% endfor %} </table> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.js"></script> <script type="text/javascript"> jQuery('#Start').datetimepicker({ datepicker:false, format:'H:i' }); jQuery('#End').datetimepicker({ datepicker:false, format:'H:i' }); </script> -
User as a foreign key in models return erro table TaskList_todolist has no column named user_id
I am trying to use user a Foreign key in my Django project. But I am getting the error: ' table TaskList_todolist has no column named user_id ' My models.py look like this from django.conf import settings from django.utils import timezone from datetime import date from Account.models import User from django.db.models.signals import post_save # Create your models here. class ToDoList(models.Model): title = models.CharField(max_length=120) description = models.TextField(blank=True) created_date = models.DateField(default=date.today) due_date = models.DateField(default=date.today) completed = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title def post_save_receiver(sender, instance, created, **kwargs): pass post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL) -
Django-forms on every Wagtail page, e.g. Contact form in the footer of base.html
I want to implement a contact form using django-forms into the footer of a multi-page website based on the wagtail cms framework. How can I render the form in the base.html template on every page? Thank you! -
instance.__dict__ in django templating language
I often find it useful to use instance.__dict__ to display properties of an object in python. I'm trying to examine an field object in a django template, is there a way to replicate this behaviour in django templating language? I would expect something like {{ my_object.__dict }}, but i can't see anything in the docs. -
Boostrap Navigation menu dropdown not working
Im using bootstrap to develop a online web app. The navigation is not working, i tried a few things but no luck. I have bootstrap css files stored in my static directory. My Navbar Code is below <!DOCTYPE html> <html lang="en"> {%load staticfiles%} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Maps - Map</title> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Bootstrap core CSS --> <link href="{% static '/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/2-col-portfolio.css' %}" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="{% url 'polls:home' %}">FestiMaps</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'polls:home' %}">Home <span class="sr-only">(current)</span> </a> </li> </ul> </div> </div> </nav> <center> <div class = "section"> <iframe></iframe> </div> </center> <footer class="py-5 bg-dark"> <div class="container"> <center><p class="m-0 text-center text-white">Copyright &copy; Maps Creators 2019</p></center> </div> <!-- /.container --> </footer> </body> </html> <style class="cp-pen-styles"> body { vertical-align: middle; background: #27ae60; } I expect the navigation bar to work as expected by showing me a list of … -
TinyMce works only with folder tiny_mce but not with tinymce
I have installed tinymce and now i have two folders. One is tiny_mce and the other one is tinymce. It will work just with the tiny_mce folder, but there are not so many options like on my localhost where i work with tinymce. When i add this tinymce into my settings.py, then it works: TINYMCE_DEFAULT_CONFIG = { 'theme': "advanced", 'skin': "o2k7", 'skin_variant': "silver", 'relative_urls': False, 'width': "640", 'height': "500", 'theme_advanced_toolbar_location': "top", 'theme_advanced_toolbar_align': "left", 'theme_advanced_statusbar_location': "bottom", 'theme_advanced_resizing': True, 'element_format': "html", 'plugins' : "contextmenu,directionality,fullscreen,paste,preview,searchreplace,spellchecker,visualchars,wordcount,table", 'theme_advanced_buttons3_add' : "tablecontrols", 'table_styles' : "Header 1=header1;Header 2=header2;Header 3=header3", 'table_cell_styles' : "Header 1=header1;Header 2=header2;Header 3=header3;Table Cell=tableCel1", 'table_row_styles' : "Header 1=header1;Header 2=header2;Header 3=header3;Table Row=tableRow1", 'table_cell_limit' : 100, 'table_row_limit' : 5, 'table_col_limit' : 5, 'table_inline_editing': True, } it works. But when i want to add the settings like on my localhost: TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, '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 | indent outdent … -
Max retries exceeded with url trying to get data from Riot API
I'm creating a social network for an exam project that wants to include as well as the classic user profile infos also some League Of Legends data, like ranked stat. I'm trying to import data using an app called "RiotWatcher" that I have included in my code. I have already tried to use this app functions to get data, using the key, region and the user name (in game) and it works, giving in output all the data I was looking for, like Soloq and Flex rank. At this point I want to use this method in my site, so after the user go to the edit_profile url and inserts his Region and In game name, the site can show in his profile also the ranked stats. def find_my_rank(): me = watcher.summoner.by_name(my_region, my_name) my_ranked_stats = watcher.league.positions_by_summoner(my_region, me['id']) if my_ranked_stats[0]['queueType'] == 'RANKED_FLEX_SR': UserProfile.ranked_flex = (my_ranked_stats[0]['tier'], my_ranked_stats[0]['rank'], my_ranked_stats[0]['leaguePoints']) #print("Flex rank: ", my_rank_flex) UserProfile.ranked_solo = (my_ranked_stats[1]['tier'], my_ranked_stats[1]['rank'], my_ranked_stats[1]['leaguePoints']) #print("Solo: ", my_rank_soloq) elif my_ranked_stats[0]['queueType'] == 'RANKED_SOLO_5x5': UserProfile.ranked_solo = (my_ranked_stats[0]['tier'], my_ranked_stats[0]['rank'], my_ranked_stats[0]['leaguePoints']) #print("Solo: ", my_rank_soloq) try: response = watcher.summoner.by_name(my_region, 'this_is_probably_not_anyones_summoner_name') except ApiError as err: if err.response.status_code == 429: print('We should retry in {} seconds.'.format(err.response.headers['Retry-After'])) print('this retry-after is handled by default by the RiotWatcher library') print('future … -
Django Rest Framework ModelSerializer custom serializer field to_internal_value doesn't save to object
I have model and serializer, there is ArrayField(postgres) in that model. Now I wanted to create a serializer field that will receive list [1,2] and save it to object, and for a list and get in serializer to show a list of JSON objects. Model: class User(models.Model): email = models.EmailField('Email', unique=True, blank=False) full_name = models.CharField( 'Full name', max_length=150, blank=True, null=True) roles = ArrayField( models.PositiveSmallIntegerField(), default=list, blank=True ) Serializer: class ArraySerializerField(ListField): def __init__(self, queryset, serializer_class): super(ArraySerializerField, self).__init__() self.queryset = queryset self.serializer_class = serializer_class def to_representation(self, value): if value: qs = self.queryset.filter(pk__in=value) return self.serializer_class(qs, many=True).data return [] def to_internal_value(self, value): super(ArraySerializerField, self).to_internal_value(value) print(value) return value class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer): roles = ArraySerializerField(queryset=Role.objects.all(), serializer_class=RoleSerializer) class Meta: model = User fields = ('id', 'email', 'full_name', 'roles') def create(self, validated_data): print(validated_data) user = super(UserSerializer, self).create(validated_data) return user Now when I do list or detail request, everything is ok, I get a list of roles as JSON. But when I try to POST data and send with this data: { "email": "test@test.com", "full_name": "Test", "roles": [1, 2] } validated_data in create method shows roles always as [] and object is saved without roles, but print from to_internal_value shows [1, 2]. What am I doing wrong? It should … -
HyperlinkedModelViewSet + Schemas: How I make nested urls?
I'm making for the first time a Rest API with django, I made the tutorial in the website of the project but now I have doubts and I haven't found a clear answer. The API I'm making have base endpoints (ex: api.site.com/v1/videos/)and others that depends in a nested configuration (ex: api.site.com/v1/videos/<pk:video>/label/<pk:label>). But I'm using the view set HyperlinkedModelViewSet and the Schemas from the Rest framework. All the nested structures have foreign keys pointing to the root endpoints. So the "label" model have a foreign key from the categories. One Category can have several labels. This is the code I'm working actually: urls.py from django.urls import path, include from rest_framework import DefaultRouter from API import views from rest_framework.schemas import get_schema_view # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'videos', views.VideoViewSet) router.register(r'categories', views.CategoryVieWSet) schema_view = get_schema_view(title='Annotation Tool API') # The API URLs are now determined automatically by the router. urlpatterns = [ path('', include(router.urls)), path('schema/', schema_view), ] views.py from API.models import User, Video, Category from API.serializers import UserAPISerializer, VideoSerializer, CategorySerializer from rest_framework import generics from rest_framework import permissions from rest_framework.decorators import api_view from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.reverse import reverse from … -
How to make the post title available at my template
i need to know how i can make the actual postname a comment belongs to available at my template to display it later on: views.py def comment_edit(request, pk): comment = get_object_or_404(Comment, pk=pk) if request.user == comment.author: if request.method == "POST": form = CommentForm(request.POST, instance=comment) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.published_date = timezone.now() comment.save() return redirect('post_detail', pk=comment.post.pk) else: form = CommentForm(instance=comment) return render(request, 'app/Post/post_comment_edit.html', {'form': form}) else: return redirect('post_detail', pk=comment.post.pk) template.html: <a href="{% url 'post_list_by_category' pk=post.category.pk %}">{{ post.category.title }} </a> <a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }} </a> models.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=500) published_date = models.DateField(auto_now_add=True, null=True) thanks in advance -
How does the check attribute work on a checkbox?
So I am trying to base some JQuery conditional statements (involving required fields) on the attribute of the checkbox "checked." When the checkbox is checked, I want the checked attribute to be false, or non-existent, and when it is checked, the checked attribute should be there. My question is, do I have to make a click function that changes the attribute? Because as far as I can tell, the attribute is either there, or it's not and clicking the checkbox doesn't make a difference. I also have the boolean field for the checkbox set to default=True so that when the page is loaded it is already checked, and that seems to be working. To sum it up, I would just like the best way to implement a conditional statement in JQuery involving the checkbox. Here is sort of an example of what I've tried and it didn't work? $('#id_rehire_comments').attr('required'); $('#id_street_1').removeAttr('required'); $('#id_city').removeAttr('required'); $('#id_zip_code').removeAttr('required'); };``` -
Filter, then ordering and get distinct on queryset
I have a list of agents, i want to filter this list then ordering it by comments they wrote (if agent wrote a comment then he should appear at the top of my list). The problem is i getting 3 times the same agents in my list because he wrote 3 comments. I tried to add distinct to the end of the query but i got this error : NotImplementedError: DISTINCT ON fields is not supported by this database backend Here my query that produce x agents if one agent wrote x comments agents = Agent.objects.filter(name__icontains=name, metier__name__icontains=metier, code_uf__icontains=code_uf, grade_code__icontains=grade, matricule__icontains=matricule).order_by('-comments') Here the query with distinct : agents = Agent.objects.filter(name__icontains=name, metier__name__icontains=metier, code_uf__icontains=code_uf, grade_code__icontains=grade, matricule__icontains=matricule).order_by('-comments').distinct('comments') I expected to get my list agents with no double or triple agents. For moment i got 3 times the same agent in my list because he wrotes 3 comments... -
bootstrap4 only shows 4 items in a multiselect
I've been googling for a solution, but no luck so far. I have a bs4 multiselect > <select id="myid" class = "myclass multiselect-container" multi > > {{ myid_html_list | safe | escape }} > </select> I validated that myid_html_list is a list of 9 options formated as follows: "<option value="myval1">myval1</option> <option value="myval2">myval1</option> . . <option value="myval9">myval9</option> " But when the webpage is displayed, I only the first 4 items only ... can't scroll up or down for other items. Please advise how to resolve. -
File "manage.py", line 14 ) from exc^ SyntaxError: invalid syntax
I want to create a username and password for the Superuser and you place this code: python manage.py migrate But I have this error: File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax If I run the server, this command is written: python manage.py runserver This error comes: Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/usr/lib/python3.5/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/usr/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/usr/lib/python3.5/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/usr/lib/python3.5/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python3.5/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 943, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked ImportError: No module named 'DEGNet' -
Django template rendering error - "no such table"
I have the following, very simple, question-answer site in Django and am getting template rendering error with the following being reported in the browser. OperationalError at / no such table: qa_question Error during template rendering In template C:\Users\User\Desktop\qa\Python-Question-and-Answer-master\templates\index.html, error at line 12 Could someone explain what 'no such table' is referring to, as I cannot find any reference to the qa_question that is thrown up in the error. I'm struggling to understand the connection between the Django templating language for loop and the "no such table" error. The relevant files are below. index.html {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>{{ question.question_title }} - My Q&A</title> <link rel="stylesheet" href="{% static 'style.css' %}"> </head> <body> <div class="content"> <h1>{{ question.question_title }}</h1> <p>{{ question.question_text|safe }}</p> <p class="questiondetails"><span style="float: left">Posted on <strong>{{ question.date_posted }}</strong></span><span style="float: right">Posted by <strong>{{ question.posted_by }}</strong></span></p> <div id="answers"> {% for answer in answers %} {{ answer.answer_text|safe }} <p class="answerdetails"><span style="float: left">Posted on <strong>{{ answer.date_posted }}</strong></span><span style="float: right">Posted by <strong>{{ answer.posted_by }}</strong></span></p> {% endfor %} </div> <!-- <form class="reply" action="" method="post"> --> {% csrf_token %} <textarea name="answer" id="answer" rows="8" cols="80" placeholder="What's your answer?"></textarea><p /> <input type="text" id="posted_by" name="posted_by" value="" autocomplete="off" placeholder="Enter your name ..."><p /> <input … -
How do I ensure a Django Channels message is received successfully
the below code is from Django Channels official doc and i use this in my project. # chat/consumers.py from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) How do I ensure all clients get the message successfully When server send a message to a group with below code? async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) And how a client ensures the message successfully received by server, when the client send a message? in http protocol we can get status code from response object. what is the alternative in websocket? -
How can I do to fusion two cells using django?
Hello I have a part of my code : style = TableStyle() rowc = 0 for cldt in data: column = 0 for cell in cldt: style.add('BOX', (column, rowc), (column, rowc), 0.25, colors.lightgrey) style.add('ALIGN', (column, rowc), (column, rowc), 'CENTER') style.add('VALIGN', (column, rowc), (column, rowc), 'MIDDLE') style.add('GRID', (0, 0), (0, 1), colors.pink) column += 1 rowc += 1 And I would like to fusion two cells so I try this : style.add('SPAN', (0,0), (0, 1), 'MIDDLE') but this does not work ... I precise I just want to fusion the two first cells in position (0,0) and (0,1) Could you help me please ? -
How to grant access to two mongodb DB, to write records synchronously, after a celery task is triggered?
I have two databases (namely, test and celery). When a celery task is triggered, it will first update the "test" db with results and then update the "celery" db with success/failure message. I have secured these DBs with credentials and followed this method: https://medium.com/@matteocontrini/how-to-setup-auth-in-mongodb-3-0-properly-86b60aeef7e8 Now, when I run my task, it gives me this error: pymongo.errors.OperationFailure: not authorized on celery to execute command { createIndexes: "celery_taskmeta", indexes: [ { key: { date_done: 1 }, background: "true", name: "date_done_1" } ] } I am using: mongodb: 3.4 mongoengine: 0.16 django 2.1 and python3 mongoengine.connect(db="test",host=config.host,username="admin_1", password="admin1234",authentication_source="admin") CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = "mongodb" CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Apart from the method mentioned in the link above, I have tried creating an admin user in admin DB like this: use admin db.createUser( { user: "admin_1", pwd: "admin1234", roles: [ { role: "dbOwner", db: "test" }, { role: "userAdminAnyDatabase", db: "admin" }, { role: "dbOwner", db: "celery" } ] } ) It gives the same error! -
Managing Django settings with app dispatcher to serve static files
I'm trying to serve a flask application with a django application. For this I'm using the appdispatcher like described here: https://werkzeug.palletsprojects.com/en/0.15.x/middleware/dispatcher/. I got it set up to serve the django page but I cannot seem to find the right settings to serve the static files as well. I keep getting 404 not found on my static files. folder structure: JUNIPER_DOVAL.py (app dispatcher file) -- DOVAL/ (django) -- doval/ -- dashboard/ -- static/ -- templates/ -- other django files -- doval/ -- wsgi.py -- settings.py -- urls.py -- app2/ settings.py (BASE_DIR prints: /DOVAL/doval): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'DOVAL.doval.dashboard' ] ROOT_URLCONF = 'DOVAL.doval.doval.urls' WSGI_APPLICATION = 'DOVAL.doval.doval.wsgi.application' STATIC_URL = os.path.join(BASE_DIR, '/static/') I would appreciate some help getting the right settings. thanks. -
how to display form.errors message properly in django
here with this code the form errors are not displaying properly.The all error messages says, this field is required only.how can i define my custom form.error message in the template. template {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p> {{ error }} </p> {% endfor %} {% endfor %} {% endif %} <div class="form-group"> <h5>Full Name <span class="text-danger">*</span></h5> <div class="controls"> <input type="text" name="name" class="form-control" title="Full Name is required" > </div> </div> <div class="form-group"> <h5>Courses<span class="text-danger">*</span></h5> <div class="controls"> {% for course in courses %} <input name ="courses" type="checkbox" id="course-{{course.id}}" value="{{course.id}}" autofocus title="Please Check at least one course"> <label for="course-{{course.id}}">{{course.title}}</label> {% endfor %} </div> </div> views.py if request.method == 'POST': form = AddStudentForm(request.POST, request.FILES) if form.is_valid(): student = form.save(commit=True) student.save() messages.success(request, 'student with name {} added.'.format(student.name)) return redirect('admin:add_student') else: form = AddStudentForm() return render(request, 'admin/add_student.html', {'form': form}) -
Django - CheckboxSelectMultiple() with scrollbar
I will have more than a hundred checkboxes on the form. This looks ugly right now. I am trying to make the checkboxes be in a frame(?) with a vertical scrollbar. Using height:100px; in crispy forms doesn't have any affect at all. Using that same in attrto CheckboxSelectMultiple() or ModelMultipleChoiceField throws unexpected argument attr error. Form field: specialities = forms.ModelMultipleChoiceField( queryset=spQry ,widget = forms.widgets.CheckboxSelectMultiple(), label=_('Speciality'), required=True) cripsy form part: self.helper = FormHelper() self.helper.layout = Layout( Field('practice_date'), Field('gender'), Field('specialities', style='max-height:20px!important'), StrictButton("Submit", name="submit", value="Submit", type='submit' ,css_class='btn btn-action-success') ) Is there anyway to have that scrollbar? Thank you -
Get Django attachments from browser
I want to send image as attachment. My code: resp = FileResponse(open(fullImgPath, "rb")) resp['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(fullImgPath)) resp["Content-Type"]="image/%s"%('png' if fullImgPath.endswith('png') else 'jpeg') return resp It does work, if i download file via requests. But when i download file via browser (chrome and firefox), file is corrupted . How i do it via browser (javascript): $.get(requestUrl) .success(function(data, textStatus, request){ headers = ParseRespHeaders(request.getAllResponseHeaders()) SaveBlob(data, getFname(headers), getCtype(headers)) } }) function SaveBlob(blob, fileName, contentType) { var a = document.createElement('a'); a.href = window.URL.createObjectURL(new Blob([blob], { "type" : contentType })); a.download = fileName; a.dispatchEvent(new MouseEvent('click')); } It worked before! Today i found file i get is corrupted. However, file stored at server is normal image. What's wrong? -
How can I compile whole django project
I was exiting if someone was able to compile Django based projects (into shared object libs for instance) with any tool and still maintain the flexibility using normal Django projects with python. -
why getting not found error on django application?
I'm running pre-built django app in a container with Dockerfile, all dependecnies are insatlled, and when the last command with gunicorn executes, and I visit the page, I get this error. what could be the issue? I tried # docker logs container but it only shows 'Not Found' No clue what's going on..