Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Increase the performance in Django ORM
contents = Content.objects.filter(is_excluded=False).prefetch_related('likes').order_by('-id').all()[:500] result = [(v for v in contents if len(v.likes.all()) > 24] return result I want to return the content which has more than 25 like and 500 recently content. This works, but is there other way to increase the performance? -
Pillow is not found by Django thouhg it is installed using docker
Hello I am following this tutorial tutorial link. Everything is working fine but when i run bellow command it says pillow is not found but pillow already is installed. docker-compose -f docker-compose.prod.yml exec app python manage.py migrate --noinput This is the error: employee.Employee.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". students.Student.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Then i again try to install using bellow command docker-compose -f docker-compose.prod.yml exec app python -m pip install Pillow And it says pillow is Pillow is already installed Requirement already satisfied: Pillow in /usr/local/lib/python3.8/site-packages (6.2.1) Here is my docker file ########### # BUILDER # ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev zlib-dev jpeg-dev musl-dev # lint RUN pip install --upgrade pip RUN pip install Pillow COPY . . # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps … -
Django createView passing current user_id to Modelform
I am trying to make a calendar app and currently trying to stop people from being about to save an event when they are already busy during that time period. I believe my issue is that the modelForm doesn't have the user_id as part of the form object. how can I pass the user_id so I can use it to filter with the clean(). I tried using get_form_kwargs() but this doesn't seem to be the correct route to take. Please can you point me in the right direction of how to do this. view.py class CalendarEventAdd(LoginRequiredMixin, CreateView): model = Event form_class = EventForm template_name = 'calendar_create_event_form.html' success_url = reverse_lazy('calendar_list') def form_valid(self, form): form.instance.manage = self.request.user return super(CalendarEventAdd, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs = super(CalendarEventAdd, self).get_form_kwargs() kwargs['user_id'] = self.request.user return kwargs form.py class EventForm(forms.ModelForm): class Meta: model = Event widgets = { 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = ['avilibility','start_time','end_time'] def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',) self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',) def clean(self, *args, **kwargs): form_start_time = self.cleaned_data.get('start_time') form_end_time = self.cleaned_data.get('end_time') form_manage_id = self.cleaned_data.get('manage_id') between = Event.objects.filter(manage_id=1, end_time__gte=form_start_time, start_time__lte=form_end_time) if between: raise forms.ValidationError('Already Calendar entry … -
Truncate content for Mdeditor (content as markdownx) - Django
I installed Mdeditor and everything works fine. My problem is when I want to truncate the content of my BlogPost in template. And this is how it looks. This is my model blog/models.py class BlogPost(models.Model): # blogpost_set -> queryset # id = models.IntegerField() # pk user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='image/', blank=True, null=True, height_field='height_field', width_field='width_field') height_field = models.PositiveIntegerField(default=0) width_field = models.PositiveIntegerField(default=0) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) # hello world -> hello-world content = MDTextField(default=' ') # content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) category = models.CharField(max_length=255, default='issue') private = models.BooleanField(default = False) tags = TaggableManager() objects = BlogPostManager() This is the template's code for the page in the image: <article class="blog-item heading_space wow fadeIn text-center text-md-left" data-wow-delay="300ms"> <div class="image"> <img src="{{ blog_post.image.url }}" alt="blog" class="border_radius"></div> <h3 class="darkcolor font-light bottom10 top30"> <a href="{{ blog_post.get_absolute_url }}">{{ blog_post.title|capfirst }}</a></h3> <ul class="commment"> <li><a href="#."><i class="fas fa-calendar"></i>{{ blog_post.publish_date }}</a></li> <!-- <li><a href="#."><i class="fas fa-comments"></i></a></li> --> <li><a href="#."><i class="fas fa-user"></i>{{ blog_post.user }}</a></li> </ul> <p class="top15">{{blog_post.content|linebreaks|truncatewords:50}}</p> <!-- <div id="content"><textarea> blog_post.content| </textarea> </div> --> </article> Is there any way to make it show content with truncatewords as markdown ? Or something that is gonna look … -
django-notifications-hq remove notification after creation
I am using django-notifications-hq to send notifications between users. Assuming I create a notification with the following code: notify.send(sender=user, recipient=other_user, verb=message, target=target_obj) Now how can I delete the exact same notification in a separate view? I have looked into the documentation and could not come up across a method that can delete a notification. I appreciate any help in advance! -
How can i find the object location in model using django and pandas
Not that the sequanse of the objects id in the model start from 26500 not from one... when i use iloc[] to get object ihave index erro because the system can not fiend the location.. I am using django and have my data from csv files -
Is there a way to return two combined lists from get_queryset instead of just the query set?
I am using Django to generate a generic.ListView of objects. I am also using Elastic Search for search results. My question is how can I combine my queryset with an ordered list of JSON objects? get_queryset only allows me to return one variable (the queryset) but I need get_context_data to be able to access both the queryset and the associated metadata for the search results. I created a below hack that works but looking for a better solution. def get_queryset(self): # just get 2 documents, in my actual code the queryset is generated by a list of IDs # from the Elastic Search query qs = Document.objects.all()[:2] # create some fake search results, in my actual code I get a similar looking JSON # objects with metadata like result score or highlighted snippets from the search corpus fake_results = [ { 'meta': { 'highlight': { 'title': ['ABC'], 'content': ['123', '456'], } } }, { 'meta': { 'highlight': { 'content': ['789'], } } } ] # this is a hack (i think) but need to merge the metadata from search results into the queryset object for doc, result in zip(qs, fake_results): if 'highlight' in result['meta']: doc.snippet = result['meta']['highlight'] return qs def … -
"You cannot set the upload handlers after the upload has been processed"
I need to change my upload handlers to get the root directory of all files that are upload, in order to do this, I created a custom upload handlers on my views.py: class NamedMemoryFileUploadHandler(MemoryFileUploadHandler): def file_complete(self, file_size): in_memory_file = super().file_complete(file_size) if in_memory_file is None: return return in_memory_file, self.file_name class NamedTemporaryFileUploadHandler(TemporaryFileUploadHandler): def file_complete(self, file_size): temporary_file = super().file_complete(file_size) if temporary_file is None: return return temporary_file, self.file_name @csrf_exempt def upload_files(request): request.upload_handlers = [ NamedMemoryFileUploadHandler(request), NamedTemporaryFileUploadHandler(request), ] return _upload_files(request) @csrf_protect def _upload_files(request): files = request.FILES.getlist("upload") for tmp_file, full_path in files: print(tmp_file, full_path) return files @login_required(login_url='/login/') def code(request): upload_files(request) if request.method == 'POST': form = UploadDocumentForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.save() if request.FILES: for f in request.FILES.getlist('upload'): data = f.read() print(data) form = UploadDocumentForm() return render(request, 'main/example.html', {'form':form}) But when I try to upload a folder, I get this error: Traceback (most recent call last): File "/Code/modapp/site/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Code/modapp/site/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Code/modapp/site/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Code/mysite/mysite/main/views.py", line 72, in code upload_files(request) File "/Code/modapp/site/env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Code/mysite/mysite/main/views.py", line 57, in upload_files NamedTemporaryFileUploadHandler(request), File "/Code/modapp/site/env/lib/python3.7/site-packages/django/http/request.py", line 300, in … -
Select items from database and add it to temporary table, and make changes to selected items in django
I have created an inventory management system using django. A feature to be added to that... All the items with details are stored in database. Some items are to be transferred to another location. So the user must be given an option to choose items from database and update the location field and file field of selected items at a time. -
How to call Django model class instance method into Django template?
Can anyone plz help me? I want to display the average rating for a tutor in my Django template, but I don't know how to call a model class instance method into a template. Models.py class ratings(models.Model): username= models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) rating=models.FloatField() tutorname=models.ForeignKey(tutors,related_name='ratingss',on_delete=models.CASCADE) created_date=models.DateTimeField(auto_created=True) def get_absolute_url(self): return reverse('tutor_detail') def rating_avg(self,id): return self.objects.filter(id=tutorname_id).aggregate(Avg('rating')) -
Django Admin FileFile not open from listview
in my model class i have an attribute like this one: c_cv = models.FileField(upload_to='mysite/static/docs', max_length=254, validators=[FileExtensionValidator(['pdf']),validate_fsize], verbose_name="CV") in my admin.py: list_display = ('c_data', 'c_sur', 'c_name', 'c_dob', 'c_en', 'c_de', 'c_cv') but when i open from admin my list page, if i click on my c_cv field in list i get an error because link does not start from 127.0.0.1:8000/mysite/static/docs/file.pdf but instead from 127.0.0.1:8000/admin/cv_list/... How can i force in admin looking my c_cv field using root of domain instad actual path as prefix? So many thanks in advance -
Understanting Django inheritance templates
Im really lost about this, im trying to understand a django inheritance template about I have a layout with a navbar and html structure: todos/templates/todos/layout.html <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <title>Practice Django</title> </head> <body> <nav class="navbar navbar-dark bg-dark justify-content-between"> <div> <a class="navbar-brand" href="/">Django app</a> <a href="#" class="navbar-item mr-3">Page 1</a> <a href="#" class="navbar-item">Page 2</a> </div> <form action="" class="form-inline"> <input type="search" placeholder="Search Todo" aria-label="Search" class="form-control mr-sm-2" /> <button type="submit" class="btn btn-outline-success my-2 my-sm-0"> Search </button> </form> </nav> <div class="container"> {% block content %} {% endblock %} </div> </body> </html> then im trying to setup a index page with a grid, a column for show todos and the another one for create a new todo. todos/templates/todos/base.html {% block content %} <h1 class="text-center">Base Page</h1> <div class="row"> <div class="col"> {% block todolist %} {% include 'todos/todos_list.html' %} {% endblock %} </div> <div class="col"> {% block addtodo %} {% include 'todos/add_todo.html' %} {% endblock %} </div> </div> {% endblock %} todos/templates/todos/add_todo.html {% extends 'todos/base.html' %} {% block addtodo %} <h3 class="text-center">subpage addtodo</h3> {% endblock %} todos/templates/todos/todos_list.html {% extends 'todos/base.html' %} {% block todolist %} <h3 class="text-center">subpage todolist</h3> {% endblock %} For try to understand … -
Caching the result of a query to the database
When rendering a page, a heavy query to the database is performed. My task is to cache the queryset obtained in the query and use it later. If 5 minutes have passed since the last initialization of the cache during the next cache query, the old cache should be removed and new data should be written from the database. Now I have written the logic without taking into account the timing, and further I have a problem with understanding how to connect the timer. class BlacklistCache: def __init__(self): self._cache = {} @property def cache(self): return self._cache @cache.setter def cache(self, value): self._cache = value @cache.deleter def cache(self): del self._cache blacklist_cache = BlacklistCache() def check_blacklist_cache(item_type): if blacklist_cache.cache: return blacklist_cache.cache else: blacklist = BlacklistedItem.objects.filter(item_type=item_type).values_list('item_id', flat=True) blacklist_cache.cache = blacklist return blacklist_cache.cache Could you get me any advice, or maybe most efficient approach? -
Data rollbacking when using AJAX function in Django?
I have an application that displays data to the users. There is a secondary column where users can enter a correction. I created an AJAX function that saves the data entered and updates my database. The application was working fine. I started to do some testing and today I found out that when I enter a value in the editable columns, after like 10 minutes it is deleted. I did queries in my database. When I query the row where I edited the value, it is shown correctly in my SQL database, and after 10 minutes, it is reverted. I don't understand why this is happening, and I was almost certain that it wasn't happening before. This is how my html/js script looks like: <head> <link rel="stylesheet" type="text/css" href="{% static 'css/dashboardStyle.css' %}"> </head> <body> <br> <br> <br> <br> <h1 class='fade-in'>Hello, {{ name }}</h1> <br> <br> <br> <br> <table class="content-table"> <thead> <tr> <th>ID</th> <th>MonthlyAccess</th> <th>MonthlyAccess_E</th> <th>QTY</th> <th>QTY_E</th> <th>GrossProfit</th> <th>GrossProfit_E</th> <th>Source</th> <th>Comment</th> </tr> <tbody> {% for datadisplay in Fact_POSTransactions %} <tr> <td>{{datadisplay.id}}</td> <td>{{datadisplay.MonthlyAccess}}</td> <td class="editable" data-id="{{ datadisplay.id }}" data-type="MonthlyAccess_E">{{ datadisplay.MonthlyAccess_E }}</td> <td>{{datadisplay.QTY}}</td> <td class="editable" data-id="{{ datadisplay.id }}" data-type="QTY_E">{{ datadisplay.QTY_E }}</td> <td>{{datadisplay.GrossProfit}}</td> <td class="editable" data-id="{{ datadisplay.id }}" data-type="GrossProfit_E">{{ datadisplay.GrossProfit_E }}</td> <td class="editable" data-id="{{ … -
Django (containerized) cannot connect to MySQL (containerized) on local machine
I set up a MySQL database using the official image from DockerHub by the command on a virtual machine with CentOS 7.6 docker run -d -p 3306:3306 --name mysql -v /opt/mysql/mysql-data/:/var/lib/mysql -e MYSQL_DATABASE=myblog -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7 Then I built and started a Django project in another container named myblog with the settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myblog', 'USER': os.environ.get("MYSQL_USER", 'root'), 'PASSWORD': os.environ.get("MYSQL_PASSWD", '123456'), 'HOST': os.environ.get("MYSQL_HOST", '127.0.0.1'), 'PORT': os.environ.get("MYSQL_PORT", '3306') } } However, when I opened the interactive bash shell of the Django project and tried to makemigrations with the command python3 manage.py makemigrations, Django complains about the connection with the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 583, in connect **kwargs) File "/usr/lib64/python3.6/socket.py", line 724, in create_connection raise err File "/usr/lib64/python3.6/socket.py", line 713, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 325, in __init__ self.connect() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 630, in connect raise exc … -
how can i bind three ModelForm in django?
i want to make a report of a patient. every patient has many of vitals, each vital has different results_values. but i don't know how can i perform these steps and bind that forms in single view to achieve ? i also get patient and vitals data but i don't understand how can i put reportform in same view and submit report attribute? i want to render forms fields and data something like this. models.py class Patient(models.Model): name = models.CharField(max_length=100) vitals = models.ManyToManyField(Lesson) class Vital(models.Model): title = models.CharField(max_length=100) expected_values = models.CharField(max_length=10) class Report(models.Model): vital = models.ForeignKey(Vital, on_delete=models.CASCADE) result_values = models.CharField(max_length=10, blank=True) forms.py class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name'] class VitalsForm(forms.ModelForm): class Meta: model = Vitals fields = [ 'title', 'expected_values' ] class ReportForm(forms.ModelForm): class Meta: model = Report fields = ['result_values'] views.py def book_update_form(request, pk): book = get_object_or_404(Book, pk=pk) b_form = BookForm(request.POST or None, instance=book) l_form = [LessonForm(request.POST or None, prefix=str( lessons.pk), instance=lessons) for lessons in book.lessons.all()] if request.POST and b_form.is_valid() and all([lf.is_valid() for lf in l_form]): b_form.save() for lf in l_form: lesson_form = lf.save() return redirect('dashboard') context = { 'book_update': b_form, 'lesson_form_list': l_form } return render(request, 'patient/report.html', context) -
is there way to add wysiwyg editor in django admin and automatically create url and html page?
is there way to add wysiwyg editor in django admin and automatically create url and html page ? i have blog and i want add new posts from admin panel and choose url for each post also i want the post must have an design then just pass data from wysiwyg editor to page and keep the design i have installed CKeditor and add it to model like this class Test(models.Model): name = models.CharField(max_length=50,default="") content = QuillField(default="") app_image = models.ImageField(upload_to='images/',null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name -
Generic detail view DetalleProyecto must be called with either an object pk or a slug in the URLconf
i am trying to build a view that shows me the detail of a record but i am having trouble adding a pk or slug, i am new to python. any help will be very appreciated thanks The error message it sends me is the following, NoReverseMatch at /buscar/ Reverse for 'detalle_obra' with arguments '('',)' not found. 1 pattern(s) tried: ['detalle/(?P[0-9]+)/$'] I also tried to solve it with get_absolute_url but it only returns the same screen #Models.py ` class Documento(models.Model): Num = models.AutoField(primary_key=True) doc = models.CharField(max_length=300, blank=True, null=True) Adjunto = models.FileField(upload_to='project', blank=True, null=True) LOPSRMEP = models.CharField(max_length=50, blank=True, null=True) Adjunto_lop = models.FileField(upload_to='project', blank=True, null=True) RLOPSRMEP = models.CharField(max_length=50,blank=True, null=True) Adjunto_rlo = models.FileField(upload_to='project', blank=True, null=True) etapa = models.ForeignKey(Etapa, on_delete=models.CASCADE) CeCo = models.ForeignKey(Obra, on_delete=models.CASCADE) creado = models.DateTimeField(auto_now_add=True) modificado = models.DateTimeField(blank=True) def __str__(self): return self.doc #urls.py from django.urls import path from .views import HomePageView, DetalleProyecto#, detalle from core import views app_name = 'libro' urlpatterns = [ path('', HomePageView.as_view(), name="home"), #path('catalogo/', CatalogoPageView.as_view(), name="catalogo"), path('busqueda/', views.busqueda, name="busqueda"), # path('documento/<slug>/', views.DetalleProyecto.as_view(), name='detalle_obra'), path('detalle/<int:pk>/', DetalleProyecto.as_view(), name='detalle_obra'), path('buscar/', views.buscar), ] #views.py def buscar(request): if request.GET["srch"]: ce=request.GET["srch"] et=request.GET["etapa"] res=Documento.objects.filter(CeCo__CeCo=ce, etapa=et).order_by('modificado') return render(request, "core/busqueda.html", {"res":res, "query":ce}) else: return render(request, "core/invalido.html") '''def detalle(request, slug): documento = Documento.objects.get(slug=slug) context = { 'documento': documento } … -
Django upgrade to version 2.2.16 adds Boto dependency
I upgraded my environment .yml file for my Django application from Django version 2.2.11 to 2.2.16. But this upgrade includes adding the boto dependency (2.49.0) to my environment file. I want to know if this dependency is necessary. If so -Is there any Django documentation that explains why? -
Element of class <myClass> is not JSON serializable in request.session
In my project i have this class: class priceManage(object): def __init__(self,uid): self.uid = uid def getRealPrice(self): tot_price = 0 plist = e_cart.objects.filter(e_uid_id = self.uid, e_ordnum__isnull = True).select_related() for x in plist: tot_price += x.e_prodid.getRealPrice()*x.e_qta return float(tot_price) but when i try to store my object reference in request.session: if not 'tot_cart' in request.session: request.session['tot_cart'] = priceManage(request.user.id) i get the error: Object of type priceManage is not JSON serializable How can i save my instance reference in a request.session dict for call methods in every part of my code? So many thanks in advance -
CSRF verification failed on safari browsers only
My form is referenced outside my site via iFrame, the {% csrf_token %} is set in the form, the nginx config allows for that wordpress site to use my form and after form submission it redirects to a thank you post thats also hosted by me, but for some reason when the person filling out the form uses safari browser its giving me a error 403 csrf verification failed, I've tried having them enable cookies on their safari browsers but apparently they are still receiving the error. The form code is too big to post here but here's the view that processes that form submission. def add_reg_cf_issuer_part1(request): is_private = request.POST.get('is_private', False) postIssuerCompanyName = request.POST.get('issuerCompanyName') try: newIssuer = Issuer.objects.get(issuerCompanyName=postIssuerCompanyName) except ObjectDoesNotExist: doesNotExist = True else: doesNotExist = False return redirect("/company-registered") postEmail = request.POST.get('issuerEmail') nothingstring = 'None' postFirstName = request.POST.get('issuerFirstName') postLastName = request.POST.get('issuerLastName') postIssuerTitle = request.POST.get('issuerTitle') postIssuerPhone = request.POST.get('issuerPhone') postIssuerCompanyName = request.POST.get('issuerCompanyName') postCompanyType = request.POST.get('companyType') postStateOfIncorporation = request.POST.get('StateOfIncorporation') postDBA = request.POST.get('DBA') postIssuerCountry = request.POST.get('issuerCountry') postIssuerState = request.POST.get('issuerState') postIssuerCity = request.POST.get('issuerCity') postIssuerAddress = (request.POST.get('q46_businessAddress') or nothingstring)+" "+(request.POST.get('q47_businessAddress47') or nothingstring) postIssuerZip = request.POST.get('issuerZip') postIssuerHomepage = request.POST.get('issuerHomepage') q1=(request.POST.get('q1') or nothingstring) q2=(request.POST.get('q27_haveYou') or nothingstring)+" "+(request.POST.get('q2') or nothingstring) q3=(request.POST.get('q28_areYou') or nothingstring)+" "+(request.POST.get('q3') or nothingstring) q4=(request.POST.get('q30_haveYou30') or nothingstring)+" … -
Django TemplateSyntaxError :- How access Dictionary values for iteration?
I have one list and dictionary. Where list values are keys of dictionary. Want to display this data on html page like there will be 3 tables first is Per page B&W print, second "Per page front and back B&W print" and third Per page Color print as in tableTitle list. now in table data will come from respective key of complext_dict. so final output should like this:- table 1:- Per page B&W print and table rows are 2 first abcd.pdf and second abc,pdf. table 2:-Per page front and back B&W print and table rows are zero table 3:-Per page Color print and table row is one rp.pdf tableTitle = ["Per page B&W print", "Per page front and back B&W print", "Per page Color print",] complex_dict = {'Per page B&W print': ['abcd.pdf', 'abc.pdf'], 'Per page front and back B&W print': [], 'Per page Color print': ['Rp.pdf']} Here is the HTML template {% for title in tableTitle %} <div class="card"> <div class="card-body"> <p>{{title}}</p> <table class="table table-striped table-responsive"> <thead> <tr> <th scope="col">#</th> <th scope="col">Documet Name</th> <th scope="col">Action</th> </tr> </thead> <tbody> {% for file in complexDict.title%} <tr> <td>{{forloop.counter}}</td> <td>{{file}}</td> <td>Action</td> </tr> {% endfor %} </tbody> </table> </div> </div> ** app/views.py ** def userDashboard(request): … -
Filtered consultation in django
Good morning, I want to make a post consultation by profile type but the relation of post is with profile and profile if you have a profile type. post_suggest_type_profile = Post.objects.all().filter() model profile class Profile(AppModel): """Profile Model. model used to store those created by users. """ user = models.OneToOneField( "users.User", related_name='profile', on_delete=models.CASCADE, blank = True, null = True, ) profile_type = models.ForeignKey( "users.ProfileType", related_name='profiles', on_delete=models.CASCADE, blank = True, null = True, ) model Post class Post(AppModel): """Post Model. model used for storing users' posts. """ class Meta: ordering = ['-created'] profile = models.ForeignKey( "users.Profile", related_name="posts", on_delete=models.CASCADE, blank = True, null = True, ) -
django webapplication which should support windows and should handle multiple request
suggest me some server for Django web application which should support windows and should handle multiple request. currently I'm using wsgi,it handling only single request. I need to replace the server which should handle multiple request at a time. -
Custom Upload Handlers in Django
I'm trying to create my own custom upload handlers on Django with the goal of being able to upload sub-directories. I ccouldn't find any resouce to build my own upload handlers so I saw Django Upload Handler on Github I basically copy and paste it in the begining to check all works fine and then make my changes, but I'm missing something, because it doesn't return the files to the request, so I'm currently lost, I think maybe that Django uploads handlers isn't what I think it is and needs some changes in order to work, but I neither know what changes, because the handler doesn't return any NotImplementedError. Any suggestion will be much appreciated.