Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
override __str__ method that allow display conditionnal string based on browser language
I have a Django project that is internationalized I have a model Pays that contain 2 fields (french and english) to manage translation In my form, I have a ModelChoice Field that display a list of country in french How can I manage language in Pays model str method ? def __str__(self): return f"{self.pay_nom_eng}" ... self.language = request.session.get('language') PAYS = Pays.objects.filter(pay_ran = 1).order_by('pay_ide') ... self.fields["pay_ide"] = forms.ModelChoiceField(queryset = PAYS, label = _("Country"), widget = forms.Select) -
Django static file href incorrectly formatted
So I have the following static loading in Django with DEBUG=True: {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> Now in my settings.py I have the following: STATIC_URL = "/static/" When I run the server python manage.py runserver and inspect my webpage in the console, the sources appear correctly, but the href attribute points to /static/css/styles.css, rather than static/css/styles.css (notice the omission of the leading /). Notice that the href on line 18 points to the wrong folder, but static/css appears correctly in the sources. So, clearly django, behind the scenes, just replaces {% static 'css/styles.css' %} with STATIC_URL + 'css/styles.css'. If I now change STATIC_URL to STATIC_URL = "static/" The href is correct (points to the right file) but the files themselves are not present!! So in order for the css file to appear, STATIC_URL needs to be /static/, but the href references a non-existent directory. If I change STATIC_URL to static/ the href is correct, but the files don't appear! Does anyone know how to fix this? I feel like it's such a basic problem, but it's doing my head in... -
How can I print the respnse json format datat in a table format in jinja template? Every time when I hit url I got 'Could not parse the remainder:'
"I want to print these response in template in table format using django but it gives "could not parse".I tried to resolve but failed. Someone please help.Below is the response which I am getting and want to print in template.I get this data when I hit an url in views.py file." { "display_free": 1, "display_paid": 1, "free": [ { "city": "", "confEndDate": "19 Feb, 2020", "confName": "AWS Innovate Online Conference", "confRegUrl": "https://aws.amazon.com/events/aws-innovate/machine-learning/", "confStartDate": "19 Feb, 2020", "confUrl": "https://aws.amazon.com/events/aws-innovate/machine-learning/", "conference_id": 1579503272, "country": "", "emailId": "", "entryType": "Free", "imageURL": "https://storage.googleapis.com/konfhub-bd9c9.appspot.com/54497.jpg?Expires=4733103270&GoogleAccessId=firebase-adminsdk-r3qh4%40konfhub-bd9c9.iam.gserviceaccount.com&Signature=GSihzq4Vf8koeEGcawKXeQmwT%2FQLZhooWUS%2BqJeNtPXtJqnNfky%2F5RgeOTEWKYCEjqAGFLSEx02cCdZ8CBTO7T2HlMjAZl6yTmDRMTH5mNawUHOrxqjsiNzSwCj4KLqHo8KlEqQrgE%2FTbxmWpT28zKfoOS20C88HrDXFMELmj5aHi4f0V%2BTF30rIlQJkNlFy6fkko2ipkLLxtYOMh0i%2B0tV1vZ0gI21mlpyNzfn6hC%2BGtN1BIz4BciB4IpMkkw7FUydFbXwJOVNm2FJs9AafozJdwdy0gOCtFDrMB2wY8JiPL2oSa%2BkBFlhIgjnIg3LaCPlfj%2Bqn9FTT%2FP5TrOioSg%3D%3D", "keywordSupport": " Artificial Intelligence ,Machine Learning,Cloud", "lat": "", "long": "", "searchTerms": " AWS Innovate Online Conference, Artificial Intelligence ,Machine Learning,Cloud, Online, February, Free, 1579503272, India", "state": "", "twitter_handle": "", "user_id": "1578287153", "venue": "Online" }, { "city": "Bangalore", "confEndDate": "22 Jan, 2020", "confName": "Redis Day Bangalore", "confRegUrl": "https://connect.redislabs.com/redisdaybangalore", "confStartDate": "21 Jan, 2020", "confUrl": "https://connect.redislabs.com/redisdaybangalore", "conference_id": 1578891826, "country": "India", "emailId": "", "entryType": "Free", "imageURL": "\"https://storage.googleapis.com/konfhub-bd9c9.appspot.com/5887.jpg?Expires=4732491826&GoogleAccessId=firebase-adminsdk-r3qh4%40konfhub-bd9c9.iam.gserviceaccount.com&Signature=JF33AcXB854Ndqw4VRN29NTQow51wGfuCSnAMIvmUUuZcmUEto3eREIrNYgqKqUpuRvGG8NIw3or6Jj8uTtl5dWVNaI93S5heRFhl3NJ1fj9zETiNE9tp6gcv1BiIkyJGCEJzXWxgUpNuqrq%2BUPzQGq4o6w1bQ0izgFP%2Fe5XhvOQmYvWDpnvsltvdppY8%2FFuVm3G13xZH3h5utMleXXqcKjGkf%2FqXHf4gSrMESrfbAZ0MPXRhZS9mGxiE2hg7DHcOweZkEY6spfLrVS2%2BEIePF4ZeXNDeDxv3bgOH6hX3VlyQFKcRCvvDzVWpvYubr0d8PJ7DK9OuMZWMmXe96BK9A%3D%3D\"", "keywordSupport": " Redis, Redis Clustering, Probabilistic Data Structures", "lat": "13.0291377", "long": "77.540708", "searchTerms": " Redis, Redis Clustering, Probabilistic Data Structures, Redis Day Bangalore, Bangalore, January, Free, 1578891826, India", "state": "Karnataka", "twitter_handle": "@redislabs", "user_id": "1578287153", "venue": "Taj Yeshwantpur, Bengaluru, 2275, Tumkur Road, Yeshwanthpur Industrial Area, Phase 1, Yeshwantpur, Bengaluru, Karnataka … -
django login not redirecting to index
I have got a login screen, which upon successful authentication should show user details on the same base URL , it used to work just fine all these days, and all of a sudden it's throwing 302 response code HTTP POST /login/ 302 [0.60, 127.0.0.1:53864] when the correct username and password is entered, no redirection is initiated, it forever keeps loading. What's more strange is that when I reload the same tab or open a new tab, it is correctly logged in and shows the appropriate details. No changes related to login functionality were made, the only recent change I made was to add reset password functionality which had nothing to do with this. user_login def user_login(request): field = None if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) try: field = UserModel.objects.get(user__username=username) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: messages.error(request,'username or password not correct') return HttpResponseRedirect('../') else: print("Error logging in{}".format(password)) messages.error(request,'Invalid username/password combination') return HttpResponseRedirect('../') except Exception: #return HttpResponse("ACCOUNT NOT ACTIVE!!!") messages.error(request,'Entered username does not belong to any account') return HttpResponseRedirect('../') else: return render(request,'app/login.html',{}) urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^$',views.IndexView.as_view(),name='index'), url(r'login/',views.user_login,name='login'),] It was working without any problems all these days, not sure of … -
Why is my django app deployed on heroku not working when debug=False?
My django app deployed on heroku doesn't work when debug is set to False, it works locally(both when debug is True and False), but I get a '500 internal server error' when I deploy my app with debug set to false, what is causing this? This is the settings file: import os from datetime import timedelta import dj_database_url import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! if os.environ.get('LOCAL') == 1: DEBUG = True SECURE_SSL_REDIRECT = False else: DEBUG = False SECURE_SSL_REDIRECT = True ALLOWED_HOSTS = ['selamselam.herokuapp.com', 'localhost'] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'api', 'frontend', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'graphene_django', 'graphql_jwt.refresh_token.apps.RefreshTokenConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ] ROOT_URLCONF = 'feel.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] # Change the things right now # https://docs.djangoproject.com/en/3.0/howto/static-files/ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) WSGI_APPLICATION = 'feel.wsgi.application' … -
Will this QuerySet hit database twice or once?
organizations = Organization.objects().all() for organization in organizations: pass ids = organizations.values_list("id", flat=True) So I assign the QuerySet to a variable then loop over all instances in the QuerySet. Then I call values_list on the same variable. Will values_list cause another database access or will the instances fetched while iterating over them be reused to create the list? -
how to see data of user specified through django-table2?
Hello i want to make a table where one can see only his created rows and not others so i have specified a user for everyrow previously i used it like this - def see(request): as=A.objects.filter(user=request.user) return render(request,'m/see.html',{'as':as}) this was working perfectly fine later i rendered a table through Django table 2 my tables .py is class ATable(tables.Table): class Meta: model = A exclude = ('aid',) per_page = 2 i want to make it user specific so that i can only see data entered from myuserid not all my filter.py code is class AFilter(df.FilterSet): class Meta: model = A exclude = ('aid',) kindly help what and where should i write to specify the user -
Performance issue with Django and Postgres on a single update
I have an intermittent performance issue with Django and Postgres when updating a single line in a small "< 1m" rows table. The APM reports the issue on the update line, which is: Model.objects.filter(id=model_id).update(field=True) The error is raised because the execution takes more than 5s. This code runs in a celery task which receives the id of the model as the argument and executes normally most of the time. I know it's a very open question but any idea or help on what might be happening is appreciated. I'm running out Python 3.7, Django 2.0.13, and Postgres 9.5. -
How to show Data In database (SQL Server) On Django Admin
I have a project working with sqlite3 (default database) and I am trying to use Microsoft SQL Server instead. I need to do get data from my SQL Server database to Django Admin pages. -
Keep selected options after form submit in Django
I have a ModelForm for filter datas. I would like to keep selected options after form submit.There is any Django's solution for this problem? I did find any good solution yet. My model form: class ELearningFilterForm(forms.ModelForm): class Meta: model = ELearning fields = ('e_learning_type', 'e_learning_name', 'specializations') widgets = { 'specializations': forms.CheckboxSelectMultiple(), 'e_learning_type': forms.RadioSelect() } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['e_learning_name'].required = False -
Computional complexity of reversed Foreign Key reference [closed]
I got such models in Django: class Artist(models.Model): name = models.CharField(max_length=128) class Sons(models.Model): title = models.CharField(max_length=128) artist = models.ForeignKey(Artist, on_delete=models.DO_NOTHING) Let's say there are 1000 songs in total, while Artist1 has just 10 songs. When I do basic ORM query like Artist.objects.first().songs.all(), does it need to check every of 1000 songs if it is related to the Artist1 or it "knows" which 10 to get? In other words, does the cost of retrieving those 10 songs increase as the next songs get created? -
How to save an image to a customized filepath in django admin?
I am trying to upload images to specific folders I select. the model code is as below: class PhotosTags(models.Model): Tag_name = models.CharField('Tag Name', max_length=100, default='NA', unique=True) Description = models.TextField('Tag Description', max_length=200, blank=True) class Meta: verbose_name = 'Tags' verbose_name_plural = verbose_name ordering = ['Date_created'] def __str__(self): return str(self.Tag_name) class Photos(models.Model): Name = models.TextField('Photo Name', max_length=200, blank=True) Tag = models.ForeignKey(PhotosTags, on_delete=models.CASCADE, default=None) filepath = 'Gallery' Photo = models.ImageField(upload_to=filepath, blank=False) class Meta: verbose_name = 'Photos' verbose_name_plural = verbose_name ordering = ['Date_uploaded'] pre_save.connect(upload_photo, sender=Photos) Here each tag has its own folder. The function I want to realize is, when I upload an image, I can select a specific tag (through selection of "Tag") and then this image can be uploaded to that folder. I tried use: signals to change the filepath but failed. The code i wrote is: def upload_photo(sender, instance, **kwargs): tardir = instance.Tag.Tag_name instance.filepath = 'Gallery'+'/'+tardir -
Package and deploy a Django app on local server
I am creating a web app using Django. I want to be able to package it into a setup file that can be installed on a client's computer and run on a local server on one computer or maybe a company's server which will serve the app to multiple pcs. I do not want to serve the app directly via internet as the data it will use is highly confidential. The client should not have access to the source code. The app will use multiple python modules other than Django. I am relatively new to programming so please keep it simple as far as possible. -
while adding image to database in django 3.1 showing this error
I am trying to add images to database it shows this error message. STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep)+['static'])) AttributeError: 'WindowsPath' object has no attribute 'split' Settings.py STATIC_URL = '/static/' STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep)+['static'])) MEDIA_ROOT = os.path.join(BASE_DIR,'images') MEDIA_URL = '/images' -
How to just listen to specific ip addresses for calling specific views
I was wondering if there is a way to listen to ip addresses and judge thereby if a view is allowed to be displayed or not. If so, could you recommend me a good approach for this. I'm gonna give an example in order to get better understood. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), path('accounts/', include('accounts.urls')), ] As to this example, when a certain url pattern is matched, i want for django to check if the requesting pc ip address lies in 'allowed_ips_list'. Im aware of this can be attained inside views but, i was thinking that if i am able to optimize this process it would be better.. than calling a view and checking consecutively. As always, thank you for your attention. -
How can i show products by price range in same page by Django and js
I want to show my products in-between two range of prices. I am making an eCommerce site and there is a price system is like this: price range image and the html code is here: <!-- Start Range --> <div class="htc-grid-range"> <h4 class="section-title-4">FILTER BY PRICE</h4> <div class="content-shopby"> <div class="price_filter s-filter clear"> <form action="#" method="GET"> <div id="slider-range"></div> <div class="slider__range--output"> <div class="price__output--wrap"> <div class="price--output"> <span>Price :</span><input type="text" id="amount" readonly> </div> <div class="price--filter"> <a href="#">Filter</a> </div> </div> </div> </form> </div> </div> </div> <!-- End Range --> this is the js file: $("#slider-range").slider({ range: true, min: 10, max: 500, values: [110, 400], slide: function(event, ui) { $("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]); } }); $("#amount").val("$" + $("#slider-range").slider("values", 0) + " - $" + $("#slider-range").slider("values", 1)); How can I solve this problem? I want to show products by the range of price but there is no min, max range in my HTML. I need the exact solution of models.py and view.py files for this HTML -
How to get year-month costs summary for certain category in DetailView, Django?
I have a table with expenses categories and when I click on the certain category it redirects me to this DetailView page. Then I want to show the year-month costs summary for chosen category to look similiar to this what I already got (summary per year-month but not for certain category). How can I achieve that? This is what I got for now and got stucked: def category_summary(): summary_by_year_month = Expense.objects.annotate( month=TruncMonth('date')).values('date').annotate( amount=Sum('amount')).order_by() return summary_by_year_month MODELS.PY class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' The most confusing part about this problem for me is how can I retrieve this information only for chosen category and show it to user in DetailView? Thank you in advance for any help. -
How to modify Django default language codes and names?
I am building a dictionary application for multiple languages using Django. Being a dictionary, I would like it to distinguish, say, between American English, British English, and Australian English. The LANGUAGES list in django.conf.global_settings.py has the following variations of the English language by default: LANGUAGES = [ ... ('en', gettext_noop('English')), ('en-au', gettext_noop('Australian English')), ('en-gb', gettext_noop('British English')), ... I would like to make American English more explicit both in terms of language code and language name. I tried to modify the django.conf.global_settings.py file OR to override the LANGUAGES list in my settings.py file as below but did not succeed. LANGUAGES = [ ... ('en-us', gettext_noop('American English')), ('en-au', gettext_noop('Australian English')), ('en-gb', gettext_noop('British English')), ... The language switcher that I am using, which is not displaying the desired changes, is the one I found on the official Django documentation. <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language" class="custom-select custom-select-sm bg-dark border-dark text-light"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> … -
How to call custom methods in DetailView / ListView in django?
I am builgind a eCommerce Website and thinking a custom method to check if a Product purchased by the user who's logging in, then I came up the "check_bough" method in ProductDetail View with Prodcut model and ProdcutPurchase model Now I have below qustions need your help: Which method should I override to make it call automatically? I thought of thinking on override the get_context_data_method. If check_done returns true then I would make a context['bought'] = 'some str' and render it on html. However, I think there must be better way... How should I modify the ProdcutList View to make it work as well? Finally, what will you guys suggest to show it in the html file? I just really want to know how will you guys will do about this problem. Even adding a attribute like 'bought by' in Prodcut model would be good or not? Do really need your help!! Thank you so much! Views.py class ProductList(generic.ListView): model = Product def get_context_data(self, *args, **kwargs): context = super(ProductList,self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj return context class ProductDetail(ObjectViewedMixin,generic.DetailView): model = Product def get_context_data(self, *args, **kwargs): context = super(ProductDetail,self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj return … -
How to list Django switches?
In my Django when you execute python -m django it lists all subcommands. But how do you list all switches like --version and others? -
Unable to override both contrib.admin.AdminSite and django.contrib.auth.admin.UserAdmin simultaneously
I'm trying to both override the default AdminSite class, and the UserAdmin. I'm trying to combine the examples from two different sections of the documentation: Overriding the default admin site Extending the existing User model Originally I had just the overriden AdminSite class, but then the problem arose when I tried to also override UserAdmin. Both of these work independently. I can either override AdminSite and get a custom header, or UserAdmin and get my inline showing. For whatever reason, I run into an import error: ImportError: Module "core.admin" does not define a "CoreCustomAdmin" attribute/class. It looks like a sort of circular dependency, but that's just a guess, as I cannot figure out where/how it's happening. Stack trace: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 20, in import_string return getattr(module, class_name) AttributeError: module 'core.admin' has no attribute 'CoreCustomAdmin' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 44, in autodiscover_modules if register_to: File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/utils/functional.py", line 240, in inner self._setup() File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 540, in _setup AdminSiteClass = import_string(apps.get_app_config('admin').default_site) File "/home/infernous/project_name/.venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
Django. How to query an array within a JsonField record?
Django. How to query an array within a JsonField record? I have a line that contains a JsonField field and inside this jsonfield contains another array field. How do I query the data and return the line within this array? Json in database site paste.ofcode.org/5v3GBex9sWVFBWMWjgbn3Q produto = Produto.objects.filter(pk=pk, labolatorio__historico__items__produto__contains='656aa2b9-9f5e-483b-8182-510bde827d5f').first() I need the result of the index in which the id was compatible In this case I need this return { "ee": { "ee": 0.1, "values": 0.1 }, "insetos": false, "produto": "656aa2b9-9f5e-483b-8182-510bde827d5f", } -
I keep getting the No module named 'django_heroku'
I'm trying to deploy an app on heroku but i keep getting this. Not the first time i'm facing this problem but i'm not able to get around it this time. Anyone knows what might cause this error? knowing that django-module is installed and the requirements.txt is up to date. -----> Python app detected -----> Installing python-3.8.5 -----> Installing pip 9.0.2, setuptools 47.1.1 and wheel 0.34.2 -----> Installing dependencies with Pipenv 2018.5.18… Installing dependencies from Pipfile.lock (f9b65c)… -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 224, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 231, in fetch_command settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load … -
Why am i getting Uncaught SyntaxError: unexpected token: identifier
for (post of posts){ //Posts are returned from a python django function let readMore = ''; let postDesc = post.fields.description if (post.fields.description.length > 227) { readMore = `<p class="btn btn-link" onclick="this.innerHTML = ${postDesc}"> Read more</p>`; }; output += ` <p class="card-text" style="white-space: pre-line;"> ${post.fields.description.substring(0, 227)} ${readMore} </p> ` }; } But when i click the read more button: Uncaught SyntaxError: unexpected token: identifierlocalhost:8000:1:22 I tried to remove the onclick and replace it with this at the end: $('#mainPosts').append(output) function showMore() { $('.readMore').click(function (e) { e.preventDefault(); $(this).parent().html(`<br> ${post.fields.description}`) }) } let g = document.createElement('script'); let s = document.getElementsByTagName('script')[0] g.text = showMore(); s.parentNode.insertBefore(g, s) But the problem is it's not replacing the substring current post description with the full one, it's replacing it with the very last post full description in the list! -
How to have a list of Fields in django models?
I have a models like this: from django.db import models class Article (models.Model): author = models.ForeignKey('Users.User') title = models.CharField() text = models.TextField() stars = [ models.IntegerField(), # 0 stars models.IntegerField(), # 1 stars models.IntegerField(), # 2 stars models.IntegerField(), # 3 stars models.IntegerField(), # 4 stars models.IntegerField(), # 5 stars ] but the problem is it the stars Fields won't be recognized in 000x_initials.py. What I have to do? I want to use it like this: if request.method == 'POST': post_data = request.post star = int(post_data['star']) article.stars[star] += 1 article.save()