Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want to create separate page for each blog post in django?But dont know how to proceeed?
I am trying to create a blog app with django.I have a home page in my app where all blog posts will be displayed.If anyone clicks on a blog post it should be displayed on a separate page.But dont know how to proceed? I know that i cant create separate html page for each post.I created a common layout html page for displaying each post.But dont know know how to add that content to it. <!---------layout.html----> {% load static %} <html> <head> <title>Self Learn</title> <link rel="stylesheet" type="text/css" href="{% static ' styles/main.css' %}" /> </head> <body> <div class="header"> <h1 class="logo">Blog</h1> <ul class="menu"> <a href="/">Home</a> <a href="#">About Us</a> {% if user.is_authenticated %} <a>Hi,{{user.username}}</a> <a href="logout">Logout</a> {% else %} <a href="login">Login</a> <a href='register'>Register</a> {% endif %} </ul> </div> <a href="newpost"> <img src="{% static 'images\12.PNG' %}" class="logo1"/> </a> <!----Post------> {% for blog in blog %} <div class="list"> <div class="con"> <h3 style="color:DodgerBlue;">{{blog.author}}</h3> <h6 style="font-family: montserrat,sans-serif;"> {{blog.date}} </h6> </div> <div class="line"></div> <div class="con"> <a href='indpost'><h1><b>{{blog.title}}</b></h1></a> </div> <div class="con"> <p>{{blog.desc}}</p> </div> </div> {% endfor %} {% block content %} {% endblock %} </body> </html> -
I am completely new to using ajax with django. How do I write the function for ajax for changing the value of model field?
I am using CBVs and I need to change the value of a field on button click. I have tried some code but it doesn't seem to work. What is wrong in this code and what can be modified? script $("#ajax_button").on('click', function () { $.ajax({ url: 'NewApp/ajax/change_status/{{userprofile.id}}', data: { 'verified': False , }, dataType: 'json', beforeSend:function(){ return confirm("Are you sure?"); success: function (data) { if (data.success) { alert("ajax call success."); // here you update the HTML to change the active to innactive }else{ alert("ajax call not success."); } } }); }); views.py def ajax_change_status(request,pk): userpr = UserProfile.objects.get(pk=pk) try: userpr.verified = True userpr.save() return JsonResponse({"success": True}) except Exception as e: return JsonResponse({"success": False}) return JsonResponse(data) urls.py url(r'^ajax/change_status/(?P<pk>\d+)/$', views.ajax_change_status, name='ajax_verified') -
Change label of a form field Django
I'm sure, there is an aswer on Google but after 30 minuts of search, I don't find my solution. So, I've my model in model.py and I generate a modelform in inventory_form.py. A field is named "watercourse" in my model so, the form field has "Watercourse" as label. model.py class Inventory(models.Model): watercourse = models.CharField(max_length=255, null=False) inventory_form.py class InventoryModelForm(forms.ModelForm): class Meta: model = Inventory fields = ['watercourse',] widgets = { 'watercourse': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'lorem ipsum', }), } If i want to change the label for "Insert a watercourse", where do I change this setting? Thanks! -
Graphene Django to Query Elasticsearch
My data is stored in elasticsearch and it is very big. So I want to use graphql to query it properly. I am using django graphene package to query it. For database models it is working fine. My json schema of elasticsearch https://pastebin.com/EQBnnCBU below is my Type definition and query code https://pastebin.com/fsr9V1Rf Problem is that I am not able to understand how to write the query schema for the elastic json schema. need only initial help or any explanation that can help me I have checked the answer here django-graphene without model But is of not help My current ElasticType schema class ElasticType(graphene.ObjectType): id = graphene.ID() index = graphene.String() found = graphene.String() properties = graphene.String() -
How to use django infinite scroll with custom overflow / custom scroll bar?
I want to implement django waypoint infinite scroll for web page & have successfully implemented too with default scroll bar. But, when I apply it to custom scroll bar, it loads all pages one by one of infinite scroll. It doesn't wait for scrolling to load next page. Django Waypoint plugings used: <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> Code overview: <div class="panel panel-height panel-flat"> <div class="panel panel-info" style=""> <div class="panel-body"> <ul class="media-list dropdown-content-body" style="padding:1% 27%;"> <div class="infinite-container" style="overflow: auto;height:70%"> <div class='infinite-item'> <span>...some content..</span> </div> </div> </ul> </div> </div> </div> -
Make 2 versions of template cache for page with and without message
Question is about using {% cache %} tag in Django templates. For example I have a “user_profile” page with “change user data” sub-page. When user wants to change his personal data, he would visit this sub-page and on completion redirected to the “user_profile” page again with message created by messaging framework like “ Dear username, you data has changed, etc” . Problem is that page would be cached with this message included and each and every time user visits “user_profile” page , message “ Dear username, you data has changed, etc” would be displayed again, that is cache freezes page condition on first visit. My cache tag is like following: {% cache "60*60*24*30"|multiplier correct_user_info request.user.change_date request.user.pk %} Page, used the view extends base.html where <div class="messages" id="message_container"> {% bootstrap_messages %} </div> is not cached at all I could move {% bootstrap_messages %} block to each individual page outside the cache tags but its kind of fishy option imo… Question is - is it any sign I could use in {%cache%} tag as a unique indicator to separate 2 situations: a) where user just changed his data , redirected to the “user_profile” and message should be displayed b)where user just visits … -
display django form.errors beside the field
When I get some error after submitting a form implemented in django it is displayed in top of the page where I have form.errors. Here I want that error to be displayed beside the field due to which the error is occurring like in django user creation form. How to do it?? template {% if form.errors %} <div class="alert alert-danger"> {{ form.errors }} </div> {% endif %} -
How to extend django UserCreationForm properly
Here i am trying to add profile model fields along with user model fields.But it not working it doesn't add the profile models data.But after adding when i do update the user i can update both model user and profile together.But while registering the user i am not being able to add profile models data .Is it possible to add profile model data along with user model at a time ? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100,blank=True,null=True) last_name = models.CharField(max_length=100,blank=True, null=True) location = models.CharField(max_length=100,blank=True, null=True) phone = models.CharField(max_length=20,blank=True,null=True) image = models.ImageField(upload_to='user image',default='default.jpg') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=False) last_name = forms.CharField(max_length=100, required=False) location = forms.CharField(max_length=100, required=False) phone = forms.CharField(max_length=20, required=False) image = forms.FileField(required=False, initial='default.jpg') def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise ValidationError('Email Already Exists') return email class Meta: model = User fields = ['username', "email", "password1", "password2",'first_name','last_name','location','phone','image','is_superuser', 'is_staff', 'is_active'] views.py def add_user(request): if request.method == "POST": form = RegisterForm(request.POST or None,request.FILES or None) if form.is_valid(): user = form.save(commit=False) user.save() messages.success(request, 'user created with username {}'.format(user.username)) return redirect('list_user') else: form = RegisterForm() return render(request, 'add_user.html', {'form': form}) def … -
Django Test Login
I created a test for create user and login. In my settings I have defined the password with min_length = 8. But the test passes with a password of 3 chars. Here my settings: AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {'min_length': 8}}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },] My test looks like this: from django.test import TestCase from django.contrib.auth import get_user_model class UsersManagersTests(TestCase): def test_create_user(self): custom_user = get_user_model() user = custom_user.objects.create_user(email='normal@user.com', password='foo') self.assertEqual(user.email, 'normal@user.com') self.assertTrue(user.is_active) self.assertFalse(user.is_staff) self.assertFalse(user.is_superuser) try: # username is None for the AbstractUser option # username does not exist for the AbstractBaseUser option self.assertEqual(user.username, '') # password will be encrypted with bcrypt self.assertNotEqual(user.password, 'foo') except AttributeError: pass with self.assertRaises(TypeError): custom_user.objects.create_user() with self.assertRaises(TypeError): custom_user.objects.create_user(username='') with self.assertRaises(TypeError): custom_user.objects.create_user(username='', password="foo") def test_create_superuser(self): custom_user = get_user_model() admin_user = custom_user.objects.create_superuser(email='super@user.com', password='bla') self.assertEqual(admin_user.email, 'super@user.com') self.assertTrue(admin_user.is_active) self.assertTrue(admin_user.is_staff) self.assertTrue(admin_user.is_superuser) try: # username is None for the AbstractUser option # username does not exist for the AbstractBaseUser option self.assertEqual(admin_user.username, '') except AttributeError: pass with self.assertRaises(ValueError): custom_user.objects.create_superuser( email='super@user.com', password='bla', is_superuser=False) def test_login_user(self): # Create an instance of a POST request. self.client.login(email="normal@user.com", password="foo") data = {'username': 'test name'} res = self.client.post('/accounts/login/', data) self.assertEqual(res.status_code, 200) What am I missing ? Or aren't the settings not considered during … -
Readonly for a Fields in form
I have a calendar form for my page and I would like to make a columns to be read-only. Here is the code forms.py class EventForm(ModelForm): class Meta: model = Event # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = '__all__' def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',) self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',) models.py class Event(models.Model): title = models.CharField(max_length=200) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() @property def get_html_url(self): url = reverse('cal:event_edit', args=(self.id,)) return f'<a href="{url}"> {self.title} </a>' -
django.db.utils.DataError: value too long for type character varying(100)
I have not set max_length and min_length for TextField: text = models.TextField(_("Full story"), null=True, blank=False) But it still gives me this error: django.db.utils.DataError: value too long for type character varying(100) Could someone help please?. -
Not read only not model field in ModelSerializer
How can I add not-read-only not model field to ModelSerializer? For example, note = serializers.CharField() (this value will be used for ItemHistory model) models.py class Item(models.Model): name = models.CharField(...) quantity = models.IntegerField() serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['name', 'quantity'] -
Install MySQL Client in Django Show Error
Hi I am trying to install Mysqlclient in Django and I got this message collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Complete output from command 'c:\users\usermo~1\virtua~1\tmsv2_~2\scripts\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\userMO~1\\AppData\\Local\\Temp\\pip-install-vzfx29bg\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\userMO~1\AppData\Local\Temp\pip-wheel-rd_6y67h' --python-tag cp37: ERROR: running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,4,2,'post',1) -D__version__=1.4.2.post1 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb" "-Ic:\users\user moe\appdata\local\programs\python\python37-32\include" "-Ic:\users\user moe\appdata\local\programs\python\python37-32\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /TcMySQLdb/_mysql.c /Fobuild\temp.win32-3.7\Release\MySQLdb/_mysql.obj /Zl /D_CRT_SECURE_NO_WARNINGS _mysql.c MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include … -
How to filter an ordered dictionary in Python using Django?
Actully I am new to Python.Working with Python,Django and Mysql. I was trying to filter some data from an ordered dictionary which i received while fetching data from mySQL database.The entire data is there in a variable. But I want to store some of it in another variable... This is my view.py file... all_dataobj=fetchdata.objects.all() pserializer=fetchdataSerializers(all_dataobj,many=True) p = pserializer.data print(p) And I am getting data like this... [OrderedDict([('id', 1), ('first_name', 'raunak'), ('middle_name', 'yy'), ('last_name', 'ron')]), OrderedDict([('id', 2), ('first_name', 'josh'), ('middle_name', 'yy'), ('last_name', 'mod')]), OrderedDict([('id', 3), ('first_name', 'david'), ('middle_name', 'yy'), ('last_name', 'cop')]), OrderedDict([('id', 4), ('first_name', 'bob'), ('middle_name', 'zj'), ('last_name', 'go')])] Now I want to filtre this ordered dictionary and store data of id 1 and 2 only in a variable. So, if I print the result variable it should look like this... [OrderedDict([('id', 1), ('first_name', 'raunak'), ('middle_name', 'yy'), ('last_name', 'ron')]), OrderedDict([('id', 2), ('first_name', 'josh'), ('middle_name', 'yy'), ('last_name', 'mod')])] Please help me...i am stuck for very long...How can I get so?? -
Redirecting public url fails on django - SignatureDoesNotMatch
Im trying to download a file from s3 to a client throught django. In order to do this Ive generate a public url from the s3 object required and the Im trying to redirect the user to that url, so the file is downloaded to his/her computer. The code is the following def generate_public_url(self, bucket, file) url = '' filename = file client = boto3.client( 's3', ) url = client.generate_presigned_url( ClientMethod ='get_object', ExpiresIn = 7200, Params = { 'Bucket': bucket, 'Key': file, } ) return url The code that redirects the url: from .django.http import HttpResponseRedirect . . . http_response_redirect = HttpResponseRedirect(url) return http_response_redirect And the response from aws is 403 with the following error: Code: SignatureDoesNotMatch Message: The request signature we calculated does not match the signature you provided. Check your key and signing method. After doing some research for a few days and trying a lot of things, Im sure this is a problem with django, and after reading some post in github people says that if the headers include something different compare to the ones used to generate the public url it can generate this error. So something in the django way of making the request must … -
Django - How to filter by annotated value
Consider the following model. I'd like to filter objects based on the latest timestamp, which might be either created_at or updated_at. For some reason, the filter function does not recognise the annotated field and I'm having hard time finding the appropriate code examples to do this simple thing. The error message is "Cannot resolve keyword 'timestamp' into field.". How would you retrieve the Example objects within 7 days, based on newer date. from datetime import timedelta from django.db import models from django.db.models.functions import Greatest from django.utils import timezone class Example(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) @property def recently_updated(self): return Event.objects .annotate(timestamp=Greatest('created_at', 'updated_at')) .filter(timestamp__gte=timezone.now() - timedelta(days=7)) .order_by('-timestamp') Django 1.11 -
static files in django framework that holds css and javascript they cant display in the web browser
I already have an index file in a template folder that hold the html code,Also i have css and javascript file in the static folder so when i load the browser i only see the index content without css and javascript in setting.py file i set clearly the path to the static files that hold css and javascript also in index file we put special tags that specify our static files The following is the setting.py contents: STATIC_URL = '/static/' STARTICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT= os.path.join(BASE_DIR,'assets') The following is the index file contents: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href=" {%static'styles/bootstrap4/bootstrap.min.css' %}"> I expect the output of css style and javascipt functionality -
How to create superuser for django in docker programatically withput using the manage.py createsuperuser commad?
I am a newbie to django. I have my django app running in docker, I need to create a superuser without using the createsuperuser command I tried using this code initadmin.py (shown below) but I am not able to run it in a bash file using "python manage.py initadmin". It is not working! initadmin.py from django.contrib.auth.models import User from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): if User.objects.count() == 0: for user in settings.ADMINS: username = 'admin' email = 'admin.com' password = 'admin' print('Creating account for %s (%s)' % (username, email)) admin = User.objects.create_superuser(email=email, username=username, password=password) admin.is_active = True admin.is_admin = True admin.save() else: print('Admin accounts can only be initialized if no Accounts exist') Can anyone tell me what am I doing wrong? Any better way to create superuser programmatically ? -
MSSQL uses db_owner prefix in selects on client's database
My Django app is normally working on SQLite3, but this time I had to convert it to use MSSQL. On test server everything went well, but when my friend copied this database to client's server I had an error: (norm)esd@server:~/Desktop/norm/myproject> python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7fc57eb4f8c0> Traceback (most recent call last): File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check_migrations() File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 163, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/migrations/loader.py", line 176, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/migrations/recorder.py", line 66, in applied_migrations return set(tuple(x) for x in self.migration_qs.values_list("app", "name")) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/query.py", line 258, in __iter__ self._fetch_all() File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/query.py", line 128, in __iter__ for row in compiler.results_iter(): File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/sql/compiler.py", line 802, in results_iter results = self.execute_sql(MULTI) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql cursor.execute(sql, params) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) … -
Auto Delete user entered data after window close or user logout
I have an, where the user enters data and it is saved in the db through Djnago forms. But I don't want to save this user entered data forever, only until the user is logged in. As soon as the user logs out or closes his browser I want Djnago to delete all that user entered data. Please look at the code and tell me how can I achieve this. views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import * from django.contrib.admin.views.decorators import staff_member_required from .forms import * from django.shortcuts import * from .models import * from django.contrib.auth.forms import * from django.contrib.auth import * from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.views.generic import CreateView from django.views import generic from .models import * def reg_user(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') return redirect('LoginPage') else: form = UserCreationForm() return render(request, 'userfiles/reg.html', {'form': form}) Also there is an issue here. Whenever I use the following decorator I get this error File "C:\Users\Bitswits 3\Desktop\Maala\MaalaWeddings\userfiles\urls.py", line 22, in <module> url(r'^invite/$', InviteCreate.as_view(), name='Invite-Page'),le "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-package AttributeError: 'function' object has no attribute 'as_view' # @login_required(login_url='LoginPage') class InviteCreate(CreateView): form_class = InviteForm model = … -
Uploading all image files from a folder into Django Template [duplicate]
This question already has an answer here: displaying all images from directory Django 2 answers I have a pdf that I am converting into individual png files in a specific folder in my app folder. The purpose is to display all the files in the folder on the template with a caption no matter what is the number of image files in the folder? Another question I have here is does it have to be inside the static folder to display the image files, can I give the path from which I want django to display the image files. Thanks. -
I need to change the value of a field and redirect to a url on button click. How am I supposed to do it?
I am working on a problem where I need to change the value of a model field "verified" on button click and redirect it to mail url so the the verified users get mail. I am not familiar with ajax. Please help me out in doing this. models.py: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles, default='client') verified =models.BooleanField(default = False,blank=True) template: <td> < a class="btn btn-primary"><i class="feather icon-edit mr-1">Verify</i></a> <a class="btn btn-primary"><i class="feather icon-trash-2">Delete</a> </td> -
Django filtering: from a list of IDs
I'm using Django Rest Framework. The model class is class MyModel(models.Model): id = models.CharField(max_length=200) name = models.CharField(max_length=200) genre = models.CharField(max_length=200) And what I have set up so far is that, when the user does a POST request, the backend will take the request data and run a python script (which takes some parameters from the request data) which will in turn return a list of IDs corresponding to the "id" in MyModel. But the problem is, let's say I want to return only the ids that point to the model instances with genre "forensic", how do I do that? I don't really have a clue how to do that, apart from doing a query on each id returned by the python script and filtering out the ones I want based on the genre returned from the query? -
How to enable HTTP access for Django APIs on HTTPS server
I have a website running on a server that redirects all HTTP requests to HTTPS as shown below. I also have a few Django APIs that the server serves (let's say https://www.example.com/apis/log). I am running the Django implementation on Ubuntu + Nginx and have installed SSL certificate using Let's Encrypt. server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name xxx.xx.xx.xx example.com www.example.com; listen 80; return 404; # managed by Certbot } Now, I would like to do the following: Run the website in the present settings (all HTTP requests should redirect to HTTPS) Django APIs should work with both HTTP and HTTPS. Hence, I would like to have both http://www.example.com/apis/log and https://www.example.com/apis/log accessible. -
how to get the SimpleListFilter lookups list in template in django
I am new in Django. I want to get the SimpleListFilter lookups list in my custom template. I want to show the list, like a dropdown menu. But i don't know how to get the loopups list in my custom template. Could anyone help me. class PollDataListFilter(SimpleListFilter): template = 'admin/input_filter.html' title = 'Author Name' parameter_name = 'author_name' def lookups(self, request, model_admin): return (('1', 'True'), ('0', 'False')) From the above code i want to get the lookups method's return list to populate my custom template. Is it possible to get that list in django?