Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make Q object expression in this case(filtering by ForeignKey field)?
models.py: class Post(models.Model): title = models.TextField(max_length=1000, null=True, blank=True, default=None) created = models.DateTimeField(auto_now_add=True) class PostFollow(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) and from those model classes, I want to get posts that is not followed by some user. Like this: user = User.objects.get(pk=1) not_followed_post = Post.objects.filter(Q(pk__lte=1000) & ~Q(self__is_not_followed_by_user=user)) How can I do this? -
How to convert class based detail view in function based view?
I am a learner I am learning django by doing an accounting application using django. I was wondering how to convert a critical class based detail view to function based view This is my code which I want to convert: class ledger1DetailView(LoginRequiredMixin,DetailView): context_object_name = 'ledger1_details' model = ledger1 template_name = 'accounting_double_entry/ledger1_details.html' def get_object(self): pk1 = self.kwargs['pk1'] pk2 = self.kwargs['pk2'] get_object_or_404(company, pk=pk1) ledger = get_object_or_404(ledger1, pk=pk2) return ledger def get_context_data(self, **kwargs): context = super(ledger1DetailView, self).get_context_data(**kwargs) context['journal_list'] = journal.objects.all() context['company_list'] = company.objects.all() journal_details = get_object_or_404(journal, pk=self.kwargs['pk']) context['Debitcount'] = journal_details.debitsum() context['company_list'] = journal_details.creditsum() company_details = get_object_or_404(company, pk=self.kwargs['pk1']) context['company_details'] = company_details return context This is my urls.py: url(r'^company/(?P<pk1>\d+)/ledgerdetail/(?P<pk2>\d+)/$',views.ledger1DetailView.as_view(),name='ledgerdetail'), So you can understand what pk1 and pk2 is...And pk is the id for the journal objects...I want to pass some function which I have performed in the journal model in ledger1detailview... If anyone know how to do it...plz help Thank you -
Django model optional file name = uploaded file filename
I have this model: class TaskFile(models.Model): task = models.ForeignKey('prosystem.Task', on_delete=models.CASCADE, related_name='files') file = models.FileField(upload_to=make_file_path, validators=[validate_file_size]) name = models.CharField(max_length=128, default=???, blank=True, null=True) Where field name is optional, but I want it to store an uploaded file filename by default. How can I achieve that? -
Django 2.0 autocomplete field, how to prevent the foreign key mapping from being changed, but allow editing
In Django 2.0, the Admin introduces an auto complete field. It works great but I can't seem to figure out a way to prevent the user from changing the foreign key object that is mapped in, without making it read only. If I make it read only the foreign key object is not editable using the edit button. Any suggestions? -
Geodjango Error with GDAL libraries showing OSError: [WinError 126] The specified module could not be found
Currently, I am working on Geodjango. I have gone through all the procedures written in https://docs.djangoproject.com/en/2.1/ref/contrib/gis/install/#requirements for windows OS. But now I am facing an error showing : OSError: [WinError 126] The specified module could not be found [You can see this error in this image.][1] I have installed PROJ4, GDAL and GEOS libraries using OSGeo4W installer. But the problem is with GDAL library. Earlier there was an error showing :- django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. Then after setting the path using GDAL_LIBRARY_PATH = 'C:\Users\gaurav\Anaconda3\Lib\site-packages\django\contrib\gis\gdal' in settings.py file the error changes to what I have stated before which is :- OSError: [WinError 126] The specified module could not be found. Also I have reinstalled GDAL from https://sandbox.idre.ucla.edu/sandbox/tutorials/installing-gdal-for-windows and followed all the steps provided in this website, but still the problem is not resolved. Now I have given this path GDAL_LIBRARY_PATH = 'C:\Program Files\GDAL\gdal203.dll' in settings.py . But still the problem is not resolved. Can anyone help me out of this. -
Scraping data using google custom search API with django
I have made a custom search API for a particular website. I am trying to get a data parameter from the website and arrange the results using this parameter. I didn't find any custom way of accessing the data of websites to do this. Does anyone have an idea how we can scrape data from the links shown by custom search API and use the data to reorder the search results. I am using python 3.5 with django 2.1 -
Pass variable (non-model-field) to serializer in django rest framework
I added a non model field to my serializer but after I hit api it returns the field as None value it doesn't store the value to use it in serializer function serializers.py class LeaveTeamSerializer(serializers.ModelSerializer): user_id = serializers.SerializerMethodField() class Meta: model = Team fields = ['id', 'name', 'user_id', 'players'] def get_user_id(self, *args, **kwargs): user_id = None # kwargs['context']['request'].user_id return user_id def update(self, instance, validated_data): user_id = validated_data.get('user_id') user = self.context['request'].user if user_id is None or user_id == '': instance.players.remove(user) else: instance.players.remove(user_id) instance.save() return instance views.py class LeaveTeamListAPIView(RetrieveUpdateAPIView): queryset = Team.objects.all() serializer_class = LeaveTeamSerializer def get_queryset(self): return Team.objects.filter(players=self.request.user) and Team.objects.filter(admin=self.request.user) json put request { "user_id":"22", "name":"a" } what i need is retrieve user_id value from json request as above json code to serializer class to use it in if statement. please any one has the solution help me I tried to over ride the context but it didnt work fine with me thanks -
JSON - Bootstrap table only first time
To populate bootstrap table on dropdown event change i use this code : dsubgroup.change(function() { var e = document.getElementById("psubbgroup-dropdown"); var subgroup_id = e.options[e.selectedIndex].value; urlsubgrps = urlsub + '/' + subgroup_id + '/Products'; console.log(urlsubgrps); $.getJSON(urlsubgrps, function (data) { $(function () { console.log(data); $('#table').bootstrapTable({ data: data }); }); }); }); And it works exact as i wanted to : But the main problem here is second usage of it. On first dropdown event change it load data inside the #table but second time when i change the dropdown it wont populate table with new data : Console did logged the correct api/route and responded with data as shown bellow But the table in HTML stays the same : The html code for table is shown bellow : <table class="table" id="table"> <thead> <tr> <th data-field="chiper">Chiper</th> <th data-field="product_name">Product</th> <th data-field="barcode">BarCode</th> </tr> </thead> </table> -
Optimizing a Django query
I have 2 models like these: class Client(models.Model): // some fields class Transaction(models.Model): client = models.ForeignKey(Client) created = models.DateTimeField(auto_now_add=True) amount = DecimalField(max_digits=9, decimal_places=2) I want to write a query that add the last created Transaction amount, per clients, only if created is lower than a provided date argument. For example, if I have a dataset like this one, and that the provided date is 01/20: Client1: - Transaction 1, created on 01/15, 5€ - Transaction 2, created on 01/16, 6€ - Transaction 3, created on 01/22, 7€ Client2: - Transaction 4, created on 01/18, 8€ - Transaction 5, created on 01/19, 9€ - Transaction 6, created on 01/21, 10€ Client3: - Transaction 7, created on 01/21, 11€ Then, the query should return 15 (6€ + 9€ from transaction 2 and 5). From a performance view, my purpose is to avoid having N queries for N clients. Currently, I have trouble selecting the right Transaction objects. Maybe I could start by: Transaction.objects.filter(created__lt=date).select_related('client'). But then, I can't figure out how to select only the latest per client. -
Application not working after deployment to Appengine standard environment
My python(3.5) and django(2.1) app runs good locally but after I have deployed it on App engine, It gives me error by clicking on links. ProgrammingError: (1146, "Table 'chaipani.django_site' doesn't exist") raise_mysql_exception (/env/lib/python3.7/site-packages/pymysql/err.py:109) Plese tell me whats wrong with it? -
template dosen't show detailView in django?
my problem is when i want set detailview for each my post in postlist i get this error : NoReverseMatch at /blog/post-list/ Reverse for 'postdetail' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['blog\/post-list/(?P\d+)/$'] views.py def PostList(request): postlist = Post.objects.all() context = { "postlist":postlist } template_name = "postlist.html" return render(request,template_name,context) def PostDetail(request,id): post = get_object_or_404(Post,id=id) context = { 'post':post } template_name = "postdetail.html" return render(request,template_name,context) postlist.html {% extends "base.html" %} {% block content %} <div class="container"> <div class="row"> <div class="col"> {% for item in postlist %} <ul> <li><h3>Title:</h3> {{ item.title }} <smal>{{ item.timestamp }}</smal></li> <li><h3>description:</h3>{{ item.description }}</li> <li><h3>Updated:</h3>{{ item.updated }}</li> <li><h>Author: {{ item.Author }}</h></li> {{ item.id }} </ul> <a href="{% url 'blog:postdetail' id=post.id %}" class="btn btn-primary">{{ item }}</a> {% endfor %} </div> </div> </div> {% endblock %} urls.py urlpatterns = [ re_path(r'^post-list/$',views.PostList,name ='postlist'), re_path(r'^post-list/(?P<id>\d+)/$',views.PostDetail,name="postdetail"), path ('post-create',views.CreatPost, name='post-create'), re_path (r'^post-list/update/(?P<id>\d+)/$',views.PostUpdateis,name='update-post'), # re_path(r'^(?P<slug_post>[-\w])+/$',views.PostDetail,name="postdetail"), ] Plz can anyone tell why i get this error tnx. -
Filter a queryset field of PointField for items within a specific distance range is incorrect
I would like to filter a queryset for items within a specific range. This is what my model looks like class modelEmployee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) location = models.PointField(srid=4326,max_length=40, blank=True,null=True) objects = GeoManager() Now this is how I am running a filter command. To return items within a specific range of 90 miles. qset = modelEmployee.objects.filter(location__distance_lte=(someLocation, D(mi=90))) The result returns an item whose distance is actually 223.732 miles which it shouldnt return. These are the locations of the two items location A - lat: 47.628641 and long: -117.402997 location B - lat: 47.618337 and long: -122.205341 The distance b/w the two is actually 223.732 miles. I must be filtering it wrong. Any suggestions on where I might be going wrong ? -
Django Admin with Parler translations generates IntegrityError
I'm using Django Parler 1.9.2 and Django 2.1. I have a Business Admin Class with inlines to edit the related models (Service and Resource) class ServiceInline(TranslatableTabularInline): model = Service class ResourceInline(TranslatableTabularInline): model = Resource @admin.register(Business) class BusinessAdmin(TranslatableAdmin): inlines = [ServiceInline, ResourceInline] When I try edit a Business in Admin it gives me a IntegrityError: File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/forms/models.py", line 650, in save_existing return form.save(commit=commit) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/forms/models.py", line 458, in save self.instance.save() File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/parler/models.py", line 648, in save self.save_translations(*args, **kwargs) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/parler/models.py", line 701, in save_translations self.save_translation(translation, *args, **kwargs) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/parler/models.py", line 728, in save_translation translation.save(*args, **kwargs) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/models/base.py", line 717, in save force_update=force_update, update_fields=update_fields) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/parler/models.py", line 892, in save_base super(TranslatedFieldsModelMixin, self).save_base(raw=raw, using=using, **kwargs) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/models/base.py", line 747, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/models/base.py", line 833, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/models/base.py", line 872, in _do_insert using=using, raw=raw) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/models/query.py", line 1133, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1285, in execute_sql cursor.execute(sql, params) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/vagrant/.virtualenvs/appy/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return … -
I added custom Languge to the list of my languages
I am having problem with adding my custom languages in Django. Here is the configuration of the settings.py: LANGUAGES = [ ('en', 'English'), ('ru', 'Russian'), ('uz', 'Uzbek'), ] EXTRA_LANG_INFO = { 'uz': { 'bidi': False, 'code': 'uz', 'name': 'Uzbek', 'name_local': "O'zbek", }, } import django.conf.locale LANG_INFO = dict(django.conf.locale.LANG_INFO.items() + EXTRA_LANG_INFO.items()) django.conf.locale.LANG_INFO = LANG_INFO global_settings.LANGUAGES = global_settings.LANGUAGES + [("uz", 'Uzbek')] but I am having the following errror: unsupported operand type(s) for +: 'dict_items' and 'dict_items' I am using django == 2.1 and pycharm as an IDE on ubuntu 18.04. Actually according to the instructions it should work. -
Django,AJAX : what to return?
I have written a class where i am sending get requests to the API and returning the json response to the front end where i am showing the response by parsing it. class ListView(TemplateView): template_name = "home.html" def get(self,request): API_URL = Geturl().api_url() API_KEY = Getkey().api_key() url = '{}{}'.format(API_URL,'/GetList') parameters = {'authToken':API_KEY} r = requests.get(url=url,params=parameters) return Httpresponse(r) i am displaying the response what i get through api call through ajax. <script> $(document).ready(function(){ $('.btn').click(function(){ alert('clicked') $.ajax({ method:'GET', url:'/home', success:function(response){ alert(response); var resss = $.parseJSON(response); console.log(resss.status); $(".ex").attr("list_status",resss.status) } }) }) }) </script> My API send response status as "content found" and "list is empty",Now i want to redirect my list view to blog post submitting section if i get API response "list is empty". I know i can redirect if i would send Jsonresponse ex: class ListView(TemplateView): template_name = "home.html" def get(self,request): API_URL = Geturl().api_url() API_KEY = Getkey().api_key() url = '{}{}'.format(API_URL,'/GetList') parameters = {'authToken':API_KEY} r = requests.get(url=url,params=parameters) return JsonResponse({'redirect_url': reverse('blog_form')}) and in ajax part success: function(res) { window.location = redirect_url; } But i want to send both r and redirect url to the ajax part so i can check what is the response of API and if that satisfies then only redirecting to … -
Pagination does not work after changing queryset in get_context_data
Pagination works ok until I add reverse arg to QS for ordering queryset in reverse mode. After it pagination is broke. I can use get() function and paginate it there, but I think that for this issue should be better solution. Thanks model.py: class Log(models.Model): user = models.ForeignKey('auth.User') comment = models.CharField() date_add = models.DateTimeField() view.py: class LogView(ListView): model = UserLog template_name = 'log.html' context_object_name = 'log_list' paginate_by = 13 def get_queryset(self): return Log.objects.filter(user=self.request.user).all() def get_context_data(self, *, object_list=None, **kwargs): context = super(LogView, self).get_context_data(**kwargs) if 'reverse' in self.request.GET: context['log_list'] = Log.objects.filter(user=self.request.user).all().order_by('date_add') return context -
Django can't manipulate initial value of a Form edit
In a Django project I'm using django-money package. When a form is in edit mode I need to modify on the fly its Money fields initial currency values if they are empty: from djmoney.models.fields import MoneyField DEFAULT_CURRENCY = 'EUR' CURRENCIES_CHOICES = [ ('EUR', 'Euro (EUR)'), ('USD', 'US Dollar (USD)'), ('GBP', 'Pound Sterling (GBP)')] class ExampleModel(models.Model): description = models.TextField(blank=True) total_charged = MoneyField(max_digits=22, decimal_places=7, default_currency=DEFAULT_CURRENCY, currency_choices=CURRENCIES_CHOICES, null=True, blank=True) class FormExampleEdit(forms.ModelForm): class Meta: model = ExampleModel fields = ['description', 'total_charged'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.initial.get(total_charged, None) is None: self.fields['total_charged'].initial = [None, 'USD'] A MoneyField is composed of two fields (amount and currency). When instantiating a FormExampleEdit with an ExampleModel instance (edit mode) if the total_charged field is None then its initial currency value would be set to 'EUR', that is the default_currency chosen in the model field. In some cases this currency might depend on other factors so when I instantiate a form with an instante of ExampleModel, I check if the instance has a total_charged set to None, in that case I manipulate the form field initial value to set its currency to something else, for example 'USD'. If I inspect the form instance everything should work but somehow … -
Model's max_length field doesn't work on localhost
My model has a CharField called title with a max_length set to 30. I have a parser that parses data to the database and when I use it all on my localhost I don't have any errors. After deploying, it happened there was an error: django.db.utils.DataError: value too long for type character varying(30) I found that it's trying to insert value that has 35 characters but this error doesn't appear on my localhost. I tried using shell and I managed to add a field that had 60 characters. What's wrong? class Coin(models.Model): symbol = models.CharField(max_length=20) title = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.title} ({self.symbol})' -
Storing value changes in Django DB
I am recording price history data in a Django model and would like to save the value whenever it changes vs. it's previously recorded value. For example, if I check prices once a day I'd like the following... Time | Price 1 | $10 2 | $10 3 | $12 4 | $15 5 | $15 to be recorded as... Time | Price 1 | $10 3 | $12 4 | $15 Does anyone have any suggestions? My models.py file class PriceHistory(models.Model): product_id = models.ForeignKey('Product', on_delete=models.CASCADE) price = models.DecimalField(max_digits=9, decimal_places=2) timestamp = models.DateTimeField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.product_id) My current code that stores ALL rows to the database (for each row of a dataframe) ph, created = PriceHistory.objects.update_or_create( product_id=row.product_id, defaults={ "timestamp": timezone.now(), "price": row.price_current, } ) -
Django: How to filter query-sets based on deep nested relations
Disclaimer: English is not my first language. I find this question hard to formulate, so it might be a duplicate. Maybe you can suggest a better title? I'm trying to do an efficient query-set for nested relations. I need to get relations spanning over multiple many-to-many relationships. Let me give you the models and the queryset I came up with, because I really can't find the words to describe my problem, but I can express it easily in code. Note I left out fields for the sake of brevity. from django.conf import settings class UserWaiterProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) class Restaurant(models.Model): name = models.CharField() @cached_property def employees(self): return UserWaiterProfile.objects.filter( employment__restaurant=self, employment__status=1 ) class Table(models.Model): number = models.PositiveSmallIntegerField() restaurants = models.ManyToManyField(Restaurant) class Employment(models.Model): restaurant = models.ForeignKey(Restaurant) employee = models.ForeignKey(UserWaiterProfile) There are users that can be employees via employments to a given restaurant. These restaurants have tables and a table can belong to several restaurants. Given a table, I need to send a message to all users that are employees at restaurants that have a relationship to that table. Here is the query currently: # ... other imports from fcm_django.models import FCMDevice class SomeView(generics.GenericAPIView): def some_serializer_method(self, serializer): restaurants = qr_code.table.restaurant_set … -
Django: TypeError : __init__() takes 1 positional argument but 2 were given
I apologize if this is silly. But I’m unable to understand this error message : This is my forms.py: class group1Form(forms.ModelForm): class Meta: model = group1 fields = ('group_Name', 'Master', 'Nature_of_group1', 'balance_nature', 'Group_behaves_like_a_Sub_Ledger', 'Nett_Debit_or_Credit_Balances_for_Reporting') widgets = { 'group_Name': forms.TextInput(attrs= {'class' : 'form-control'}), } def __init__(self, *args, **kwargs): super(group1Form, self).__init__(*args, **kwargs) self.fields['Master'].widget.attrs = {'class': 'form-control select2',} self.fields['Nature_of_group1'].widget.attrs = {'class': 'form-control select2',} self.fields['balance_nature'].widget.attrs = {'class': 'form-control select2',} This is my views.py: class group1CreateView(LoginRequiredMixin,CreateView): form_class = group1Form template_name = "accounting_double_entry/group1_form.html" def form_valid(self, form): form.instance.User = self.request.user form.instance.Company = self.kwargs['pk'] return super(group1CreateView, self).form_valid(form) Can anyone tell me what exactly I am doing wrong in this code??? Just cant figure it out Thank you -
Nagios/Python/Query: How to return 3 values with different thresholds in the same function
I'm currently working on a nagios-python plugin that runs a query for tracking failed automated phone calls with 3 different metrics: 1. High ring time calls (warning threshold at 1+, critical threshold at 5+) 2. Zero seconds calls (warning threshold at 4+, critical threshold at 10+) 3. Bad hangup code calls (warning threshold at 2+, critical threshold at 5+) The function with the query is: def phonecall(self): self.connect() cur = self.conn.cursor() query = """ SELECT count(*) FILTER (WHERE ring_time > 5) AS high_ring_time_calls, count(*) FILTER (WHERE call_duration = 0) AS zero_sec_calls, count(*) FILTER (WHERE hangup_id NOT IN (0, 16, 127)) AS bad_hangup_calls FROM cdr WHERE caller_terminate >= (current_timestamp AT TIME ZONE 'xxx/xxx' - interval '15 minute') AND call_start >= (current_timestamp AT TIME ZONE 'xxx/xxx' - interval '1 day') AND x_id IN (232, 3440, 3047, 3212, 191) """ cur.execute("SET TIMEZONE = 'xxx/xxx'") cur.execute(query, {'current_timestamp': datetime.datetime.now()}) row = cur.fetchone() (high_ring_time_calls, zero_sec_calls, bad_hangup_calls) = row return high_ring_time_calls, zero_sec_calls, bad_hangup_calls My probe function: def probe(self): self.connect() high_ring_time_calls, zero_sec_calls, bad_hangup_calls = self.phonecall() now = datetime.datetime.now() high_ring_delta = total_minutes(now - high_ring_time_calls) zero_sec_delta = total_minutes(now - zero_sec_calls) bad_hangup_delta = total_minutes(now - bad_hangup_calls) yield nagiosplugin.Metric('high_ring', high_ring_delta, min=0, context='phonecall') yield nagiosplugin.Metric('zero_sec', zero_sec_delta, min=0, context='phonecall') yield nagiosplugin.Metric('bad_hangup', bad_hangup_delta, min=0, context='phonecall') … -
Django save files under dynamic path based on ForeignKey
I have these models: class Project(): name = models.CharField(max_length=512) class Task(): name = models.CharField(max_length=256) project = models.ForeignKey('prosystem.Project', related_name='tasks', on_delete=models.CASCADE) class TaskFile(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='tasks') file = models.FileField(upload_to=self.make_file_path()) # I want this to be dynamic path def make_file_path(self): # pseudocode, does not work project = self.task.project.name task = self.task.name path = f'{project}/{task}/' return path I want to upload files to a folder based on its Task name and its parent Project name. How can I do that? -
How to fix Django Custom Filter: "namespace is not bound error"
I've created a simple custom filter to check if an "< option >" in a "< select >" is selected. It is working fine tho, it's just that it has an error on the pycharm editor "namespace is not bound" and the filter is highlighted red. clearly there's something wrong. this is my custom filter cus_filter.py: from django import template register = template.Library() @register.filter def is_option_selected(value, to_compare): return "selected" if value == to_compare else "" my application: {% load cus_filters %} <label>LONG/SHORT</label> <select class="form-control"> <option {{ data.type|is_option_selected:"Short" }}>Short</option> <option {{ data.type|is_option_selected:"Long" }}>Long</option> </select> -
Django render without return?
I have situation where I have for loop inside my view function. And I need to calculate something and render content for each iteration. But render needs to be returned and thats why it makes only one iteration and then my view function ends. Is there any way how to bypass this? Thanks for reply. This is how I imagine how it should be. for i in iterations: ... context = i.name render(request, template, {context: context}) return render(request, template, {context: context})