Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why doesn't the first ModelFormSet pick up the id from request.POST?
I'm trying to add multiple of a ModelForm using the ModelFormSetFactory. Upon submission the first of the set returns an error saying "(Hidden field id) This field is required." even though the hidden id field is in the form. For any further forms in this set, this error does not occur and the id can be found in the cleaned_data. The view for this form (in views.py): class NewRecipeView(generic.TemplateView): def get(self, request, *args, **kwargs): ingredient_data = { 'ingredient-TOTAL_FORMS': '0', 'ingredient-INITIAL_FORMS': '1', } context = {"new_page": "active", "form": RecipeForm(), "formset_ingredient": RecIngFormSet(ingredient_data, prefix="ingredient"), } return render(request, 'recipes/new_recipe.html', context) def post(self, request): form = RecipeForm(request.POST) formset_ingredient = RecIngFormSet(request.POST, prefix="ingredient") print(request.POST) for fs in formset_ingredient: print(fs) print(fs.cleaned_data) if form.is_valid() and formset_ingredient.is_valid(): new_rec = form.save(commit=False) new_rec.created_at = timezone.now() new_rec.save() for fs in formset_ingredient: new_rec_ing = fs.save(commit=False) new_rec_ing.recipe = new_rec new_rec_ing.save() return HttpResponseRedirect(reverse('recipes:recipe', args=(new_rec.id,))) else: print('handle invalid forms here') And the actual form in forms.py: class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient fields = ['quantity', 'unit', 'ingredient'] recIngFormSet = modelformset_factory(RecipeIngredient, RecipeIngredientForm) In the HTML I am building the form from {{ formset_ingredient.empty_form }} with javascript and making sure that I follow the rules set in {{ formset_ingredient.management_form }}. I think this bit is fine as the … -
Slices vs queryset in django
It all started with me trying to apply slices to a queryset to limit it. As I understand the documentation it is supposed to limit the results to 10 entries: def get_queryset(self, *args, **kwargs): qs = Message.objects.all() qs = qs.filter(Target_id=self.dialog)[:10] # here the limit qs = qs.annotate(sender_id=Max('Sender__id')) return qs But really in template the request returns me all the records, but applies the annotation only to the first 10. I do not know why. I thought the whole reason was annotate. Then I remove the last line (with annotate). However I got in the template all the records instead of 10. That is same result as if I didn't make the slice. In my template I'm not doing anything unusual: the iteration over the my queryset: {% for message in messages %} {{message}} {% endfor %} This is weird: if I take len(qs) in my view, I get 10! But in template I get 300! It doesn't fit in my head. I tried also to apply slice in the template instead of my view: {% for message in messages|slice:":10" %} But nothing has changed. I have got all messages in my template instead of 10. How could this be? PS: … -
How to Extend The User Model with field of another class in django?
i want make an extend of the User Model with field from another class (structure in models.py in immob app) in django ,i will show you my project -
what mean the error local variable 'instance' referenced before assignment
i am trying to get values from the views.py function into the html template but the system crash and display this error : local variable 'instance' referenced before assignment views.py def update(request,pk): #deny anonymouse user to enter the detail page if not request.user.is_authenticated: return redirect("login") else: if request.method == "POST": instance = get_object_or_404(suspect,pk=pk) print(suspect) context = { "title":instance.suspect_name, "instance":instance, } return render(request,'blog/update.html',context) update.html {{instance.id}} its just a test because what i want is to be able to update form based on the id so i am trying to get the id of the object. i will appreciate any help -
Threading.py in python while running server for django project
This is the error message shown up while running server for django project in pycharm,I didn`t find what kind of error is this.. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ashish Attri\AppData\Local\Programs\Python\Python35\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Ashish Attri\AppData\Local\Programs\Python\Python35\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) My Threading.py file is provided below: Please help me out of this.... THIS IS THE STARTING OF A CODE: import sys as _sys import _thread from time import monotonic as _time from traceback import format_exc as _format_exc from _weakrefset import WeakSet from itertools import islice as _islice, count as _count try: from _collections import deque as _deque except ImportError: from collections import deque as _deque AND THIS IS THE ERROR PART OF A CODE: def _bootstrap_inner(self): try: self._set_ident() self._set_tstate_lock() self._started.set() with _active_limbo_lock: _active[self._ident] = self del _limbo[self] if _trace_hook: _sys.settrace(_trace_hook) if _profile_hook: _sys.setprofile(_profile_hook) try: self.run() except SystemExit: pass except: -
Passing csv data from views to template
I've been stuck on this problem for some time now. It's pretty simple, and I bet there's a simple solution for this. I'm able to read the csv file pretty easily, and just to test if everything is working, I print the data from the csv file on the cmd line. The prooblem is that I'd like to, instead of printing it out, send everything to the template (book/r.html) so I can graph it later (using chart.js). # views.py def rtest(request): url = staticfiles_storage.path('dat.csv') with open(url, 'r') as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: print(f'value: {line[3]} & year:{line[4]}') return render(request, 'book/r.html') Each line has the following format: ['59', 'US', 'United States', '3007.12344537862', '1960'] And I'm only interested in the last two values. I believe I need to use a dictionary as context to send this data through the view function, but I have no idea how I'd that. If I can do something like {{ context.value }} and {{ context.year }} on my r.html would be awesome, but my final goal is to graph these values (value y-axis, year x-axis). Any help is appreciated, thank you! -
How to automate object adding in the django model?
I have the model for a team object. I want to add objects in this models by parsing. So, I have parsing code in the views.py. How can I do adding of that data in the model in the views.py. Should I use queryset or something like that? As I know there is approach to add objects using Django shell. But is it possible to add objects automatically? While the project is deployed on a hosting it is not possible to use Django shell. I tried to use manual adding using lists and dictionaries as the variable during template rendering. from django.shortcuts import render from django.views.generic import TemplateView from bs4 import BeautifulSoup from urllib.request import urlopen def homePage(request): tn = [] ti = [] for team in teamList: tn.append({'name': team}) for img in imgList: tn.append({'img': img}) teamDict = { 'team': tn, 'matchLink': linkSrc, 'img': tn, } return render(request, 'home.html', teamDict) # Parser try: html = urlopen("//some url//") except: print("Connection problems") teamList = [] imgList = [] bsObj = BeautifulSoup(html, "lxml") futMatches = bsObj.find("div", {"class": "esport-match-future-list"}) for link in futMatches.find_all("div", {"class": "esport-match-single"}): linkTag = link.find("a", {"class": "team-vs-team"}) if "tbd" not in linkTag.attrs["href"]: teamDiv = linkTag.find_all("div", {"class": "team"}) for item in teamDiv: … -
Django: SELECT JsonField AS new_name?
I have a table, in which some attributes are columns, and some are implemented as a postgres JsonField. For the columns, I can write eg Product.objects.values(brand=F('brand_name')) for implement a SELECT brand_name AS brand query. I need to do something similar for a JsonField, eg Product.objects.values(color=F('jsonproperties__color')) However, the F expressions do not work correctly with JsonFields, and there doesn't seem to be a fix coming anytime soon. How could I work around this? -
Sharing database definitions (models.py) across two separate django projects
Say you want to share some model definitions across two separate django projects, living in two different workspaces. How would you go about this? May models.py be "linked" as done in java from one project to the other? May the models.py live in a separate "libarary"? or does that requires use of pip?! Am I forced to put the two project in the same workspace? Copy the definition over once it changes ... Is there a best practice around this? -
How to interpret/render template tags as HTML from Django database
I'm trying to add posts with images from Django admin site, but the safe/autoescape-off filter cannot interpret Django's template tags. My input and page look like: "copy image address" gives http://127.0.0.1:8000/%7B%%20static%20'post/image.jpg'%20%%7D My view inherits from a generic ListView. My base.html and post_list.html: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <div style="color: red;"> <a href="{% url 'admin:index' %}">admin</a> {% block contents %} {% endblock %} </div> </body> </html> {% extends 'post/base.html' %} {% block contents %} {% for post in object_list %} {% autoescape off %}{{ post.text }}{% endautoescape %} {{ post.text|safe }} {% endfor %} {% endblock %} -
Ipd matching query does not exist in Django
I am trying to get objects from ForeignKey using QS but I can't seem to find a problem models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,blank=False,default = " ") def __str__(self): return self.patient.name views.py: @login_required def ipd (request,patient_id): formtwo = IpdForm() qs = Ipd.objects.get(patient=patient_id) if request.method=="POST": formtwo = IpdForm(request.POST) if formtwo.is_valid() : instance = formtwo.save(commit=False) instance.save else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'a':qs,'form2':formtwo}) html : Name : {{a.name}} Phone : {{ a.phone }} Address : {{ a.address }} Gender : {{ a.Gender }} -
how can i make a functional feedback view in Django?
i have a view where users can provide feedback by filling a form which will send emails.The idea is that the app also sends emails for confirming emails and resetting passwords and stuff. forms.py subjects = ( (1,'Bug/error reporting'), (2,'Enhancement suggestion'), (3,'Support and help'), (4,'General feedback') ) class ContactForm(forms.Form): name = forms.CharField(max_length=180) email = forms.EmailField(required=True) subject = forms.ChoiceField(choices=subjects,required=True) message = forms.CharField(widget=forms.Textarea(attrs={"rows":9, "cols":20})) views.py def emailView(request): user = request.user initial_data = { 'name' : user.first_name, 'email' : user.email, } if request.method == 'GET': form = ContactForm(initial=initial_data) return render(request, "email.html", {'form': form}) else: form = ContactForm(request.POST,initial=initial_data) if form.is_valid(): name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] message_f = name + 'has the following complaint \n' + message try: send_mail(subject, message_f, from_email, ['admin@example.com'],fail_silently=True) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) but i don't thinks this is functional as it returns error for invalid username and password from the dummy data i provided the settings.py with. I think that the problem is that i have to use other function for sending mails with other email backends. -
is there is a solution for urls issues
I am building a web app using django and I get an error, I couldn't figure out what is the problem behind it. I have three models( Category, SubCategory, Article) in my url I want something like that (localhost:8000/categories/Id_category/Id_subcategory) the url (localhost:8000/categories/Id_category) worked perfectly but (localhost:8000/categories/Id_category/Id_subcategory) didn't work I get this error enter image description here So here is my code that I tried to make it: #views.py def categorie(request): Catégorie_list=Catégorie.objects.all() context = { 'Catégorie_list':Catégorie_list, } return render(request,'articles/Category.html',context) def souscategorie(request,categoryID): SousCatégorie_list=SousCatégorie.objects.order_by('désignation').filter(Catégorie_identifiant_id=categoryID) name_category=Catégorie.objects.get(id=categoryID) articles=Article.objects.select_related('Sous_Catégorie__Catégorie_identifiant').filter(Sous_Catégorie__Catégorie_identifiant_id=categoryID) context = { 'SousCatégorie_list':SousCatégorie_list, 'name_category': name_category, 'articles':articles } return render(request,'articles/SubCategory.html',context) def articl(request,categoryID,articleID): return render(request,'articles/article.html') #articles/urls.py urlpatterns=[ path('',views.categorie, name='Category'), path('<int:categoryID>/',views.souscategorie, name='SubCategory'), path('<int:categoryID>/<int:articleID>/',views.articl, name='article'), path('search',views.search, name='search'), ] #my template <div class="row"> {% if articles %} {% for article in articles %} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="{{ article.photo_main.url }}" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="{% url 'article' name_category.id article.id %}">{{ article.désignation }}</a> </h4> <h5>{{ article.Sous_Catégorie }}</h5> <p class="card-text">{{ article.Description }}</p> </div> <div class="card-footer"> <h6 class="text-muted">Ajouter au panier</h6> </div> </div> </div> {% endfor %} {% else %} <a class="list-group-item"> Aucune sous catégorie disponible</a> {% endif %} </div> -
Object does not exist error: User has no profile
I am trying to create two forms to update the user profile, but I keep getting the error: django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile. I do not know where I am going wrong! My code is as follows: My profile.html {% extends "apotofgold/base.html" %} {% load crispy_forms_tags %} {% load avatar_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{% avatar user %}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </form> </div> {% endblock content %} My forms.py from django import forms from django.contrib.auth.forms import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ['username','email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] My models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __sr__ (self): return f'{self.user.uMy mpodsername} Profile' My signals.py from djamgo.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import … -
Django: form is valid but is not save because no module named app is found
I'm developing a simple form to upload files. I see that my form is valid because some print statments I've made, however I'm getting an error when saving the form. ModuleNotFoundError at /admineditorial/predica/add/ No module named 'app' And: Exception Location: <frozen importlib._bootstrap> in _find_and_load_unlocked, line 965 I don't think it has to do something with Bootstrap. I don't know what could be happening. models.py: class Predica(models.Model): audio_file = models.FileField(upload_to = u'audio/', max_length=200) **views.py:** # Create your views here. def predica_upload(request): predicas = Predica.objects.all() if request.method == 'POST': form = PredicaUpload(request.POST, request.FILES) if form.is_valid(): print("### Form is valid ###") form.save() print("Despues del save") print(form) return redirect('today_editorial') else: print("### Form not valid ###") print(form.errors) else: form = PredicaUpload() return render(request, 'predicas/predicas.html', {'form': form, 'predicas': predicas}) urls.py: from django.urls import path from editorial import views from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin', admin.site.urls), path("", views.today_editorial, name="today_editorial"), path('predicas',views.predica_upload, name = 'predica_upload') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) predicas.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Subir</button> </form> {% for predica in predicas %} <div> <img src="{{predica.audio_file.url}}" alt="myvideo"> </div> <p>No audios in my gallery yet :-(</p> {% endfor %} settings.py: """ Django … -
Is it possible to include a ForeignKey inside a JSONField schema? How else can I effect this?
I am building an app in Django that allows users to build their own forms and in effect customise dynamic models. After much research, I've decided to effect this through Django, PostgreSQL and JSONFields where one model holds the schema and another holds the record data: class = Template(models.Model): schema = JSONField(null=True) # Schema for the form/model class = DynamicModel(models.Model): data = JSONField(null=True) # Corresponding data for the form/model template = models.ForeignKey(Template, null=True, blank=False, on_delete=models.SET_NULL) This means users can define their own model templates and I can hold different records using that template in another model. The idea is to parse the template.schema JSONField to display editable forms using jQuery and to store the output as dynamicmodel.data JSONField. Validations are passed on the client side. However, this comes with the drawback if I want to allow users to include ForeignKey lookups in their models. For example, say they wanted to add a choice box that offered selections from different customer.ids in a Customer(models.Model) class. Without hardcoding the ForeignKey directly into the DynamicModel class (which would defeat the point of the exercise) can you think of a way I can achieve this? -
How to get objects from one model to other using ForeignKey in Django
I want to link models with there ids, I am having trouble in getting objects of foreignkey linked with id and creating queryset, I am new to Django I have searched alot about my problem but not getting answer. models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,blank=False) def __str__(self): return self.patient.name forms.py : class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name', 'phone', 'address', 'Patient_id', 'consultant', 'Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','reason_admission','presenting_complaints', 'rooms','date_of_admission'] views.py: @login_required def ipd (request,patient_id): p = Patient.objects.get(pk=patient_id) if request.method=="POST": formtwo = IpdForm(request.POST,instance=p) if formtwo.is_valid() : formtwo.user_id = request.user.id if formtwo.save(): return HttpResponseRedirect('ipd_list.html', messages.success(request, 'Patient is successfully updated.', 'alert- success')) else: return render('ipd_list.html', messages.error(request, 'Data is not saved', 'alert-danger')) else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'p':p ,'form2':formtwo}) html : <div class="card-panel"> <span class="blue-text text-darken-2">Name : {{p.name}}</span> <br> <span class="blue-text text-darken-2">Phone : {{ p.phone }}</span><br> </div> I am having problem with queryset that allows me to use object … -
How can I fix 'ModelForm has no model class specified.'
I am getting the ModelForm has no model class specified. error when trying to use the ModelForm I can't see where the error is coming from. To the best of my knowledge, I have reference the model which I am using properly. Please see my code below: forms.py from django import forms from .models import BlogPost class BlogPostForm(forms.Form): title = forms.CharField() slug = forms.SlugField() content = forms.CharField(widget=forms.Textarea) class BlogPostModelForm(forms.ModelForm): class meta: model = BlogPost fields = ['title', 'slug', 'content'] views.py def blog_post_create_view(request): form = BlogPostModelForm(request.POST or None) if form.is_valid(): form.save() form = BlogPostModelForm() context = {'form': form} template_name = "form.html" return render(request, template_name, context) -
The current path, index, didn't match any of these. http://127.0.0.1:8001/index
I setup webpage via cmd for Django.However, i had problem when accessing index page of 127.0.0.1:8001. I tried to update urls.py but still have problem. Browser page error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8001/index Using the URLconf defined in barry.urls, Django tried these URL patterns, in this order: admin/ The current path, index, didn't match any of these. urls.py file: """{{ project_name }} URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/{{ docs_version }}/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.conf.urls import url from sign import views urlpatterns = [ path(r'^admin/', admin.site.urls), path(r'^'index/$', views.index.urls), ] -
Indexing product list takes way too long with Django, Haystack and Whoosh
I'm experiencing issues indexing a list of products (about 280k) with Haystack and Whoosh. It seems to take more than 28 hrs to run the update of the index. I don't think that's a reasonable time at all. I've got a model: class SupplierSkus(models.Model): sku = models.CharField(max_length=20) link = models.CharField(max_length=4096) price = models.FloatField() last_updated = models.DateTimeField("Date Updated", null=True, auto_now=True) status = models.ForeignKey(Status, on_delete=models.PROTECT, default=1) category = models.CharField(max_length=1024) family = models.CharField(max_length=20) family_desc = models.TextField(null=True) family_name = models.CharField(max_length=250) product_name = models.CharField(max_length=250) was_price = models.FloatField(null=True) vat_rate = models.FloatField(null=True) lead_from = models.IntegerField(null=True) lead_to = models.IntegerField(null=True) deliv_cost = models.FloatField(null=True) prod_desc = models.TextField(null=True) attributes = models.TextField(null=True) brand = models.TextField(null=True) mpn = models.CharField(max_length=50, null=True) ean = models.CharField(max_length=15, null=True) supplier = models.ForeignKey(Suppliers, on_delete=models.PROTECT) I got a search_indexes.py: from haystack import indexes from products.models import SupplierSkus class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) sku = indexes.CharField(model_attr='sku') category = indexes.CharField(model_attr='category') product_name = indexes.CharField(model_attr='product_name') family_name = indexes.CharField(model_attr='family_name') prod_desc = indexes.CharField(model_attr='prod_desc') family_desc = indexes.CharField(model_attr='family_desc') brand = indexes.CharField(model_attr='brand') mpn = indexes.CharField(model_attr='mpn') ean = indexes.CharField(model_attr='ean') attributes = indexes.CharField(model_attr='attributes') def get_model(self): return SupplierSkus def index_queryset(self, using=None): return SupplierSkus.objects.filter(status_id=1) I've noticed a massive performance decrease in the Django versions after 2 when it comes to iterating over a large QuerySet. I'm not sure why that is, … -
Django download link with relative path in template
I have a few download links and I want to use relative paths to the specific files in my template, so I don't need to adjust paths and the full path is not shown when inspecting that element. views: def home(request): template = loader.get_template('home/index.html') context = {'directory': settings.BASE_DIR} return HttpResponse(template.render(context, request)) def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/octet-stream") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 where BASE_DIR from settings.py is: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) urls.py: urlpatterns = [ path('download/<path>', views.download, name='download') ] Snippet from the template: <a href="{% url 'home:download' '{{ directory }}\files\Main.xaml' %}">Download</a> My question is how to properly paste {{ directory }} as a variable in the element as a argument to the download view. It's not working like shown above. -
What email backend should i use to make users send emails ? and how to specify email backends for cerrtain views?
I have an app where users can send feedbacks by filling form containing there basic info and in the same app (same web application no the same application) the app will send emails for confirming their emails when they sign up. the email backend i use for confirming their emails is smtp backend so what should i use for them sending emails and how can i specify it ? -
Pass parameter in string mongo query in python
I have following query in my database query = u'collection.aggregate([{ "$match": { "code": { "$in": {__sensors__}} } },{"$project" : {"_id" : 0}},{"$group" : {"_id": "$code", "data": {"$last": "$$ROOT"}}}])' And I have following arguments, Now I want to pass that argument in the above query. args = {"__sensors__": ["GP0", "GP1", "GP5", "GP6"]} I'm trying following but it is giving me an error. query.format(**args) above statement giving me this error --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-44-7db1aba33ea5> in <module>() ----> 1 a.query.format({"__sensors__": []}) KeyError: u' "$match"' Can anyone give me the solution for the above problem? -
Django paginator not responsive on last page
Iterating over a large QuerySet doesn't seem to be a viable option in Django 2.0 anymore. I've tried to speed it up using Django's own Paginator. def read_from_db_4(): paginator = Paginator(DataSet.objects.filter(status_id=1).order_by('id'), 1000) l = [] print("{} iterations!".format(paginator.num_pages)) for page in range(1, paginator.num_pages+1): l = l + list(paginator.page(page).object_list) print("{}, next page...".format(page)) return l This little function is reasonably quick but will stop on the very last page. I can also not get to the length of this page: len(paginator.page(LASTPAGE).object_list) this will just hang forever. I can get the length of all other pages previously. What's the reason for this odd behaviour? -
How to run a FOR loop on a JSONField in Django referring to specific elements
I have the following JSONField: class Flow(models.Model): flow_title = models.CharField(max_length=200, null=True) flow_data = JSONField(null=True) def __str__(self): return self.flow_title In the flow_data JSONField I have the following JSON: { "section1": { "section_title": "Untitled Section 1", "section_description": "Section description 1", "field1": { "field_name": "Untitled field 1", "field_type": "Text", "field_value": "This is text value 1" }, "field2": { "field_name": "Untitled field 2", "field_type": "Text", "field_value": "This is text value 2" } }, "section2": { "section_title": "Untitled Section 1", "section_description": "Section description 1", "field1": { "field_name": "Untitled field 1", "field_type": "Text", "field_value": "This is text value 1" }, "field2": { "field_name": "Untitled field 2", "field_type": "Text", "field_value": "This is text value 2" } } } Now, I know I can pass context in my views.py to create the required object: def index(request): flow_list = Flow.objects.all() return render(request, "index.html", {"flow_list": flow_list}) And that I can loop through all of my json objects in the template: {% for object in flow_list %} <li>{{ object.id }}>{{ object.flow_data }}</a></li> {% endfor %} However, if I want to format individual parts of the JSON in the loop like below, how would I do this? {% for object in flow_list %} <li>[nth Section]</li> <li><b>[nth Section Description]</b></li> <li>[First Field] - [Field …