Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Elasticsearch Highlighting
I have implemented elasticsearch into my Django website, now I'm trying to add highlighting and got stuck. What I want essentially, is to highlight the result everywhere on search page. Here is my documents.py: from django_elasticsearch_dsl import Document, Index from news.models import Article articles = Index('articles') @articles.document class ArticleDocument(Document): class Django: model = Article fields = [ 'title', 'description', ] I went through the docs and found: GET /_search { "query" : { "match": { "content": "kimchy" } }, "highlight" : { "fields" : { "content" : {} } } } How would I do what I want ? Where can I include these settings ? Thank you ! -
How to handle each object of v-for in vue?
I'm trying to build a like function using django rest api and vue. In the vue file, posts are rendered by v-for loop. And I want to change each Like Button Image whether a user has liked it or not dynamically. this is the API response. { "id": 48, "title": "Test post", "owner": { "username": "admin" }, "likes_count": 0, "user_has_liked": false }, { "id": 49, "title": "Second test post", "owner": { "username": "admin" }, "likes_count": 1, "user_has_liked": true }, and vue file. <b-card-group deck v-for="post in posts" :key="post.id" :post="post" class="border dashboard-card-container"> <b-card-header class="w-100 bg-white"> <span class="ml-3">{{ post.owner.username }}</span> </b-card-header> <b-card-footer class="w-100 bg-white"> <b-link v-on:click="postLike(post.id)"> <b-img v-if="post.user_has_liked" thumbnail :src="likeIcon" class="dashboard-icon" /> <b-img v-else thumbnail :src="notLikeIcon" class="dashboard-icon" /> </b-link> import { apiService } from "@/common/api_service"; export default { name: "home", data() { return { posts: [], notLikeIcon: require("@/assets/notlike.png"), likeIcon: require("@/assets/like.png") } }, methods: { getDashboardPosts() { let endpoint = "/api/dashboard/"; apiService(endpoint).then(data => { this.posts.push(...data); } }) }, postLike: function(pk) { let endpoint = "/api/posts/"+pk+"/like/"; let method = "POST"; apiService(endpoint, method).then(data => { }) } }, created() { this.getDashboardPosts() } }; Communication with API works fine. So, I'm wondering how to handle each post object. For example, In the post list page, if … -
Multiply two fields in django form and populate third filed with the result
I am creating a form in my django app like this: views.py @method_decorator([login_required, client_required], name='dispatch') class MaterialRequestFormView(CreateView): model = MaterialRequest template_name = 'packsapp/client/materialRequestForm.html' fields = "__all__" def form_valid (self, form): product = form.save(commit=False) product.save() messages.success(self.request, 'The material request was created with success!') return redirect('client:mat_req_table') models.py class MaterialRequest(models.Model): owner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='allotment_sales') flow = models.ForeignKey(Flow, on_delete=models.CASCADE, related_name='flow') kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='kit') quantity = models.IntegerField(default=0) is_allocated = models.BooleanField(default=False) quantity_p1 = models.IntegerField(default=0) quantity_p2 = models.IntegerField(default=0) quantity_p3 = models.IntegerField(default=0) quantity_p4 = models.IntegerField(default=0) quantity_p5 = models.IntegerField(default=0) html <h2>Material Request Form</h2> <div class="row"> <div class="col-md-6 col-sm-8 col-12"> <form method="post" id="MaterialRequestForm" data-kit-url="{% url 'employee:ajax_load_kit' %}" data-product-url="{% url 'employee:ajax_load_product' %}" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit">Save</button> </form> </div> </div> <div id="products-table"> </div> <script> $("#id_flow").change(function () { console.log("function running"); var url = $("#MaterialRequestForm").attr("data-kit-url"); var flowId = $(this).val(); $.ajax({ url: url, data: { 'flow': flowId }, success: function (data) { $("#id_kit").html(data); console.log(data); } }); }); </script> <script> $("#id_kit").change(function () { console.log("function running"); var url = $("#MaterialRequestForm").attr("data-product-url"); var kitId = $(this).val(); $.ajax({ url: url, data: { 'kit': kitId }, success: function (data) { $("#products-table").html(data); } }); }); </script> The ajax is to get the table. Can I change it such that when I enter the quantity … -
Get results of the model only if child with Foreign key has records
I have two models as follows: class Tutorial(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) class Video(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING, blank=False, null=False) I want to get all Tutorials where there is at least one video in Video model Something as follows: results = Tutorial.objects.filter(id__in=Video.objects.filter....) Any idea how to do that? -
How to allow user access to the django-constance admin?
I have added CONSTANCE_SUPERUSER_ONLY=False to the settings file as django-constance manual recommends. But the constance.change_config line has not appeared in the user's rights list. What did I miss? -
Save checkbox values from csv django
I have CSV file in this formate I can get data into this field dynamically. How Can I save this data into database so that I can show easily as form of check boxes .And save data into model using this csv. My model is something like this restaurant = models.OneToOneField(User, on_delete=models.CASCADE) ArticleName = models.CharField(max_length=50, null=False, blank=False) price = models.DecimalField(max_digits=10, decimal_places=2) Category = models.CharField(max_length=50, null=False, blank=False) Pickuptax = models.FloatField(null=True, blank=True, default=None) Ingredient = models.CharField(max_length=100) //As I can't assign static choice fields here. -
Django: Cannot load static image file with specific name?
I have .jpg file with name google_adsense, so I load it, like every other file from same folder with {% static 'core/images/google_adsense.jpg' %} but it doesn't appear, status from Network tab in browser is blocked:other If I change name to google_adsens for example or any other name it works fine. Also check for chars limit, but abvabv_abvabva works fine also. -
How to incorporate select2 in django forms for selecting multiple answers?
I'm trying to get multi-selecting in a dropdown list (pillbox or anything is fine). But I'm not been able to do it since I can't figure out how to install and import and use it. I've tried almost all answers here but cannot understand any of them. Currently, I'm using multiselect but I don't want checkboxes. My code: forms.py: from django import forms from django.forms import ModelForm from charts.models import HomeForm1 #Import the model from models.py class HomeForm(ModelForm): CHOICES = (("address1","address1"), ("address2","address2")) plot11=select2.fields.ChoiceField(choices=CHOICES,overlay="Choose an author...") class Meta: model = HomeForm1 fields = '__all__' models.py: #Importing Model from django.db import models from multiselectfield import MultiSelectField from survey import analysis #Backend coding module import ast global f1 f1=analysis.getQuestion() #get all the questions and their possible answers with a count in a string from f1=ast.literal_eval(f1)[0] #Convert it into a dictionary for key in f1.keys(): #Convert the values of dictionary in a nested dictionary f1[key]=f1[key][0] class HomeForm1(models.Model): ##################get the questions for the plot data########################################## choices1=tuple(map(lambda f: (f,f),list(f1.keys())[7:])) ###################get type of plot########################################################## choices_plot_types=((None,None),('bar','bar'),('horizontalBar','horizontalBar'),('line','line')) #Take dict_values and convert them into tuples eg.:('a','a') ###################assign the filters####################################################### for k in list(f1.keys())[:6]: q=list(f1[k].keys()) q.sort() choices=tuple(map(lambda f: (f,f),q)) locals()[k]=MultiSelectField(max_length=1000,choices=choices,blank=True) #Take the keys for filtering the data ###################assign the plot types … -
Configure multisite template loads
The current templates layout: A second site will soon be created, on a different domain. The logic of both sites is the same. The names of the templates are the same. It is need that when entering from the first domain, its templates are loaded, when entering from the second domain - its templates. If there are no such templates, load some common template. Make copies of templates not necessary. apps app1 templates folder_with_templates_1 index.html admin index.html app2 templates folder_with_templates_2 index.html admin index.html templates admin index.html 404.html 500.html What are the painless solution options? Write some crutch template loader? Did not work out. I can lay out the code, if necessary. Crutch Middleware, which will determine the website and load the appropriate templates? Configure dirs in the settings of each site? Found django-multisite, but failed to configure it. If necessary, I will show my settings. https://github.com/ecometrica/django-multisite Settings of first site: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '..', 'apps', 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # Project context processors 'apps.landing.context_processors.landing_settings', 'apps.landing.context_processors.page404_context', 'apps.landing.context_processors.user_token_data', ], }, }, ] -
Validation in Modelviewset
I have to validate image. I have tried add validator to field in models.py, but python cannot migrate validator depending on class. How can I add validation in this case in views.py validators.py class ValidateImageSize: ... views.py class EpisodeView(viewsets.ModelViewSet): serializer_class = EpisodeSerializer permission_classes = [BasicAuthorizationPermissions] queryset = Episode.objects.all() def create(self, request, story_id=None, *args, **kwargs): try: story = Story.objects.get(pk=story_id) except Story.DoesNotExist: raise NotFound kwargs = { 'story': story, 'title': request.data.get('title'), 'cover': request.data.get('cover'), } episode = Episode.objects.create(**kwargs) for image in dict(request.data.lists())['images']: EpisodeImage.objects.create(episode=episode, image=image) return Response({'episode_id': episode.id}, status=201) -
translate angular variables in django template
In my django project I can easily translate any string by the tag below: {% trans "any string" %} but there is a drop-down list in a page. I used angularjs to get the drop-down values as like below: <select class="form-control btn-bar-select" ng-model="selectedDivision" ng-change="changeDivision()" ng-options="division as division.name for division in divisions"> <option value="">{% trans "Select Division" %}</option> </select> I want to translate the drop-down list. Here division.name is responsible for the drop-down list values. Can I bring this under trans tag of django or any other way? -
Django Aggregate on related field with filter
Following problem: I have product groups containing products. These products can be visible in the frontend or not. I determine their visibility with the method frontend() (which contains a filter) like so: product_groups.first().products.frontend() Now I want to determine if I want to put a link for the product group on the homepage only if there are four or more products in it. With annotations I would do: product_groups.annotate(num_products=Count('products')).filter(num_products__gte=4) But this gives me of cause the count of all products and not the count of products visible in the frontend. So how do I put the additional filter frontend() into my query? To be clear, I want the Count() not on 'products' but on products.frontend(). -
How to stop SELECT before INSERT with Django REST Framework
I've used Django REST Framework to expose an API which is only used by another service to POST new data. It basically just takes json and inserts it in the DB. That's all. It's quite a high volume data source (sometimes more than 100 records/second), so I need to tune it a bit. So I was logging the (PostgreSQL) queries that are run, and I see that every POST gives 3 queries: 2019-10-01 11:09:03.320 CEST [23983] postgres@thedb LOG: statement: SET TIME ZONE 'UTC' 2019-10-01 11:09:03.322 CEST [23983] postgres@thedb LOG: statement: SELECT (1) AS "a" FROM "thetable" WHERE "thetable"."id" = 'a7f74e5c-7cad-4983-a909-49857481239b'::uuid LIMIT 1 2019-10-01 11:09:03.363 CEST [23983] postgres@thedb LOG: statement: INSERT INTO "thetable" ("id", "version", "timestamp", "sensor", [and 10 more fields...]) VALUES ('a7f74e5c-7cad-4983-a909-49857481239b'::uuid, '1', '2019-10-01T11:09:03.313690+02:00'::timestamptz, 'ABC123', [and 10 more fields...]) I tuned the DB for INSERTs to be fast, but SELECTs are slow. So I would like to remove the SELECT from the system. I added this line to the Serializer: id = serializers.UUIDField(validators=[]) But it still does a SELECT. Does anybody know how I can prevent the SELECT from happening? All tips are welcome! For complete info; the full Serializer now looks like this: import logging from rest_framework import serializers … -
Can't edit the image properties on django-ckeditor
I have an instance of django-ckeditor installed with the settings/models etc below. Although it allows me to upload images and save them within the RichTextUploadingField, it is not allowing me to alter their sizes. Within image properties, I cannot enter any of the input or drop down fields. I can only click the buttons. I do not know if the following has an impact and if I need to do something additional but I am loading the form through ajax as a bootstrap3 modal when a button is clicked which allows me to load the relevant form. Any thoughts on why the input boxes are not editable would be appreciated settings.py CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_UPLOAD_PATH = "ckeditor_uploads/" CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', #'toolbar': None, 'height': '100%', 'width': '100%', } } models.py class study(models.Model): researcher = models.ForeignKey("auth.user") # Researcher's name name = models.CharField(max_length = 51) # Study name instrument = models.ForeignKey("instrument") # Instrument associated with study #waiver = models.TextField(blank = True) # IRB Waiver of documentation for study or any additional instructions provided to participant waiver = RichTextUploadingField(blank = True) forms.py class RenameStudyForm(BetterModelForm): name = forms.CharField(label='Study Name', max_length=51, required=False) # Update study name #waiver = forms.CharField(widget=forms.Textarea, label='Waiver of Documentation', … -
How to do customize Model save method instead of form clean method and is it advisable?
I have this model: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False,) ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) and have this model form: class StudentIeltsForm(ModelForm): class Meta: model = StudentIelts exclude = ('student') def clean(self): cleaned_data = super().clean() has_ielts = cleaned_data.get("has_ielts") if has_ielts: msg = "Please enter your score." for field in self.fields: if not self.cleaned_data.get(str(field)): self.add_error(str(field), msg) else: for field in self.fields: self.cleaned_data[str(field)] = None self.cleaned_data['has_ielts'] = False return cleaned_data As you see, if a student has ielts, then he/she has to specify his/her scores in the model form. I now want to do this on the database level. So I need to customize my model save method, I guess. How should I do this? Will my modelform behavior be the same as before? -
django model creation connecting to mssql
I am connecting to a legacy mysql database in cloud using my django project. i need to fetch data and insert data if required in DB table. do i need to write model for the tables which are already present in the db? if so there are 90 plus tables. so what happens if i create model for single table? how do i talk to database other than creating models and migrating? is there any better way in django? or model is the better way? when i create model what happens in the backend? does it create those tables again in the same database? -
Django Saleor installing Dashboard 2.0 on windows
I am trying to install Saleor Dashboard 2.0 on my Windows 10 machine for a dev environment. So far I have git cloned the git clone dashboard into the same folder as the Saleor project Then cd saleor/dashboard and ran npm i The instructions were not really clear on how to configure the API_URI to http://localhost:8000/graphql/. It is not in the settings.py and the instructions were not clear on where this is. -
how to redirect any api request from http to https in django?
after migrating my django web app from http to https, when i type for example r= requests.get('http://xxxx.com') it gives me this error : requests.exceptions.SSLError: HTTPSConnectionPool(host=my_host_name,port:443) Max retries exceeded with url:http://xxxx.com (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)) but i made the nginx config for the redirection for example when i put any http address on my browser it redirects me to the correct https address. i would like to do the same thing on the api request . i don't like to change my requests adresses on my backend code i just want to redirect the http requests to https if it is possible? -
how can I send an email to user when admin change a value from admin panel
I want to send an email to the user when his/her post has to approve/reject. class Post(models.Model): POST_STATUS = ( ('approve', 'approve'), ('pending', 'pending'), ('reject', 'reject') ) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) status = models.CharField(max_length=10, choices=POST_STATUS, default='pending') #title, body, image will be here -
error with django.core.exceptions.ImproperlyConfigured: on Django 2.2.5
I know that this question has been asked before and I went through every possible answers given, and it still does not make it for me! I am running django 2.2.5 and python 3.7 on PyCharm. My manage.py seems to be working fine. The issue is coming from my admin file, I believe but I do not know where the issue could be. I ran django-admin check in terminal which also give me an error. My only file that raise an error is my admin.py but I cannot understand why. I copied my admin.py file as well as the errors that I get when I write the commands on the terminal from django.contrib import admin from import_export.admin import ImportExportModelAdmin from inventory1.templates.models import * @admin.register(Item) class ViewAdmin(ImportExportModelAdmin): exclude= ('id',) And when I execute it, I get the error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Now, I am sure this is related too, when I try django-admin check, i get: django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. from previous questions, this issue was coming from an issue with settings in the manage.py … -
How do I properly use a UUID id as a url parameter in Django?
I've been trying to pass a UUID4 id into the url for a specific detail page. After browsing Stackoverflow and other sites, here's what I've tried so far: Passing the url path as path('car/<uuid:id>/', views.CarDetailView.as_view(), name='car-detail'), But this raises the error: Generic detail view CarDetailView must be called with either an object pk or a slug in the URLconf.. Since the uuid field is composed of both letters and numbers, I can't use an int. So I used this: path(r"^(?P<car_model>\w+)/$", views.CarDetailView.as_view(), name='car-detail'), which returns the messy and broken url: showroom/%5E(%3FP09c32f72-5863-49fa-a42a-1d0fed274c4e%5Cw+)/$ Then I tried reverting to the original, but using a def_object method in the View class. def get_object(self): object = get_object_or_404(CarInstance,title=self.kwargs['car_model']) return object But this returns the error: "KeyError at /showroom/car/09c32f72-5863-49fa-a42a-1d0fed274c4e/ 'car_model'" models.py class CarInstance(models.Model): manufacturer = models.ForeignKey('Manufacturer', on_delete=models.SET_NULL, null=True) car_model = models.CharField('Model', max_length=50, null=True) views.py class CarDetailView(generic.DetailView): model = CarInstance template_name = 'car_detail' def get_queryset(self): return CarInstance.objects.all() def get_object(self): object = get_object_or_404(CarInstance,title=self.kwargs['car_model']) return object def get_absolute_url(self): return reverse('showroom:car-detail', args=[str(self.pk)]) The urls should be be formatted as showroom/car/09c32f72-5863-49fa-a42a-1d0fed274c4e/, which brings up the detail view for the specific object. Any ideas? -
filter a modelform based on a column not in that form
I have a model for users like: class user: name = models.CharField([...]) mobile = models.CharField([...]) and for its manager I have: [...] ManagerColumn('name', 3), ManagerColumn('last_order_date', 3, is_variable=True) [...] def get_last_order_date(): [some function returning date data type] now I want to filter this manager modelform based in last_order_date which is not in original model. how can I do that? -
How to distinguish 1 optional parameter and 1st function name in Django
Following urls are valid: //localhost/ //localhost/123 //localhost/hello/ //localhost/hello/456 url.py url(r'^$', views1.custom1, name='custom1'), url(r'^(?P<param1>.+)/$', views1.custom1, name='custom1'), url(r'^hello/$’, views2.custom2, name='custom2’), url(r'^hello/(?P<param2>.+)/$', views2.custom2, name='custom2’), view1.py def custom1(request, param1=''): view2.py def custom2(request, param2=''): For url //localhost/hello/, custom1() function responds, with param1='hello' which is not correct! Following 2 url can’t be distinguished. url(r'^(?P<param1>.+)/$', views1.custom1, name='custom1'), url(r'^hello/$’, views2.custom2, name='custom2’), How to fix it? -
TemplateDoesNotExist at /edit-narration/13/edit/
Why is my narrate_update_form template not showing? And why am I getting TemplateDoesNotExist at /narration/7/edit/ narrate_update_form My views.py is: class NarrateUpdate(UpdateView): model = Narrate fields = ['title', 'body'] template_name = 'narrate_update_form' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['narrate'] = Narrate.objects.get(pk=self.kwargs['pk']) return context On my narrate template I have this button: <a href="{% url 'edit-narration' narrate.pk %}" value="Update">Edit/Update</a> On the narrate_update_form.html, I have: {% extends 'base.html' %} {% block body %} <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form> {% endblock body %} Can anyone help me? -
name 'TEMPLATE_DIR' is not defined
i am trying to create Templates for the views, but when i trying to runserver it says NameError: name'TEMPLATE_DIR' is not defined i have tried to look in google and forums, but that didn't solve my problem i created templates in the base directory and add the route to the template directory TEMPLATES_DIR = os.path.join(BASE_DIR,'templates') and added TEMPLATE_DIRS in the DIRS 'DIRS': [TEMPLATE_DIR], NameError: name 'TEMPLATE_DIR' is not defined