Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error relationship users_user_permissions when i try to add or change user in django admin
I am writing because I can’t understand what’s wrong, recently this code worked ... I have a custom user(Testuser). When I try to add or change it, it says that there is no users_user_permissions table. I tried run a manage.py migrate --run-syncdb and this does not work. How to fix it? All permissions are stored in the default schema public . models.py class CustomUserManager(UserManager): pass class TestUser(AbstractUser): phone = PhoneNumberField(null=False, blank=False, unique=True) email = CharField(unique=True, max_length=35, null=False, blank=False) class Meta: db_table = '"fyzzys"."users"' permissions = [ ("can_see_payments", "payments"), ("can_see_analytics", "analytics"), ("can_see_documents", "documents"), ("can_see_sverka", "sverka"), ("can_see_ways", "ways") ] objects = CustomUserManager() Admin.py class MyUserAdmin(UserAdmin): model = TestUser form = CustomUserChangeForm add_form = CustomUserCreationForm list_display = ('username', 'first_name', 'email', 'phone', 'is_active',) list_filter = (['is_active']) search_fields = () filter_horizontal = (['groups', 'user_permissions']) fieldsets = ( ('Personal info', {'fields': ('first_name', 'email', 'phone', 'password')}), ('permissions', {'fields': ('is_active', 'is_staff','user_permissions')}) ) add_fieldsets = UserAdmin.add_fieldsets + ( ('Personal info', {'fields': ('first_name', 'email', 'phone')}), ('permissions', {'fields': ('is_active', 'is_staff','user_permissions')}), ) admin.site.register(TestUser, MyUserAdmin) form.py class CustomUserCreationForm(UserCreationForm): phone = PhoneNumberField(region='RU', required=True) class Meta(UserCreationForm): model = TestUser fields = ('username', 'first_name', 'email', 'phone') class CustomUserChangeForm(UserChangeForm): phone = PhoneNumberField(region='RU', required=True) class Meta: model = TestUser fields = ('username', 'first_name', 'email', 'phone') settings.py AUTH_USER_MODEL = … -
I created login authentication in Rest Api
I created login authentication in Rest Api it Retrieves token key in postman. Right now I need the username of the person associated with a token key. how to do that ? '''class LoginView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] django_login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({"token": token.key }, status=200)''' '''class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): username = data.get("username", "") password = data.get("password", "") if username and password: user = authenticate(username=username, password=password) if user: if user.is_active: data["user"] = user else: msg = "User is deactivated." raise exceptions.ValidationError(msg) else: msg = "Unable to login with given credentials." raise exceptions.ValidationError(msg) else: msg = "Must provide username and password both." raise exceptions.ValidationError(msg) return data''' -
Django - Need some assistance with Refactoring / Improving my view
Im making an airbnb website as a project, and I have created this monster ( yes, I know ) : def apartment_view(request, apartment_id): reservation = Reservation.objects.filter(apartment__pk=apartment_id) apartment = get_object_or_404(Apartment, pk=apartment_id) context = {} context['apartment'] = apartment unavailable = [] for start, end in apartment.reservations.values_list('start_date', 'end_date'): while start <= end: unavailable.append(start.strftime('%-d-%m-%Y')) start += datetime.timedelta(days=1) form = ReservationForm() context['unavailable_dates'] = json.dumps(unavailable) context['form'] = form if request.method == 'GET': form = ReservationForm() if request.method == "GET": form = ReservationForm(request.GET) if form.is_valid(): context = {} reservation = form.save(commit=False) reservation.apartment = apartment start_date = request.GET.get('start_date', None) end_date = request.GET.get('end_date', None) sdate = datetime.datetime.strptime(start_date, '%Y-%m-%d') #start edate = datetime.datetime.strptime(end_date ,'%Y-%m-%d') #end prices_by_date = apartment.price_by_date(sdate, edate) user_dates = [sdate + datetime.timedelta(days=x) for x in range((edate-sdate).days + 1)] user_date_list = [] for day in user_dates: user_date_list.append(day.strftime('%d,%m,%Y')) context['price_per_day'] = prices_by_date.price context['total_price'] = len(user_date_list) * prices_by_date.price context['unavailable_dates'] = json.dumps(unavailable) context['form'] = form context['apartment'] = apartment context['date_start'] = start_date context['date_end'] = end_date form.save() return render(request, "booking/apartment.html", context) elif request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): reservation = form.save(commit=False) reservation.apartment = apartment reservation.save() form.save() HttpResponseRedirect(reverse('booking:apartment', kwargs={"apartment_id": apartment.pk})) return render(request, 'booking/apartment.html', context) To describe what is going on, user first comes to the site and picks the start and end date to … -
X accel redirect not downloading the file
I'm trying to add authentication to allow only valid users to download static files from nginx. This is my Nginx configuration : location ^~ /download-logs { internal; alias media/logs; } And in Django I've added a route to handle the response : url : url(r'^media/', views.protectedMedia, name="protect_media"), views : def protectedMedia(request): response = HttpResponse(status=200) response['Content-Type'] = '' response['X-Accel-Redirect'] = '/download-logs/log.txt' return response When i try to go to the route http://my_ip_address/media/ from the response i can see X accel redirect field, but file is not getting downloaded -
Got widnows error 1120 while trying to install psycopg2/psycopg2-binary
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\link.exe' failed with exit status 1120 I have installed postgresql and added to the global variables path to pg_config. Windows 8, python 3.8 -
Check If one datetime lies between two datetimes python
I am trying to check if one datetime lies between two datetimes, most of the cases return true, but in below case it return false whereas it should return true, how can I check it in proper way. time1=1900-01-01 08:30:00 time2=1900-01-01 00:00:00 inbetween=1900-01-01 20:00:00 if (time1<=inbetween<=time2): # if 12 hour format (8:30AM<8:00PM<12:AM) it should be true print("True") return True else: print("False") return False in above case inbetween lies between time1 and time 2 so it should return True but it return False. How can I check. NOTE: the date will always remain same so I have to check it on the time basis. -
Queryset v/s List Django
I want to know what is the difference in terms of execution in Django queryset and Django list. For eg, List of Objects v/s Queryset of Objects Will there be much difference in the execution part? -
How to cache query results in django and use it?
I have a small request, the data from which is transferred to <select>. I use a paginator and this selector makes a request every page.So I want to cache it and try to update every 10 minutes, for example.How do I save a cache and how do I pass it to a template so that the selector works? views.py contractors = Contractors.objects.values_list('name', flat='True') HTML-code <select name="contractorName" class="form-control" id="id_contractorName"> <option value="" selected=""></option> {% for contractor in contractors %} <option value="{{ contractor }}">{{ contractor }}</option> {% endfor %} </select> -
Comparing non-optional value of type 'JSON' to 'nil' always returns true. Any suggestion to fix this?
if let vendorId = vendor?.id { APIManager.shared.getProducts(vendorId: vendorId, completionHandler: { (json) in if json != nil { <<<<<<<<<Comparing non-optional value of type 'JSON' to 'nil' always returns true self.products = [] if let tempProducts = json["products"].array { for item in tempProducts { let product = Product(json: item) self.products.append(product) } self.tableView.reloadData() Helpers.hideActivityIndicator(self.activityIndicator) } } }) } } In My APIManager.Swift import Foundation import Alamofire import SwiftyJSON import FBSDKLoginKit class APIManager { static let shared = APIManager() let baseURL = NSURL(string: BASE_URL) var accessToken = "" var refreshToken = "" var expired = Date() // Request Server Function func requestServer(method: Alamofire.HTTPMethod , path: String, params: [String: AnyObject]?, encoding: ParameterEncoding, completionHandler: @escaping (JSON?) -> Void ) { let url = baseURL?.appendingPathComponent(path) refreshTokenIfNeed { AF.request(url!, method: method, parameters: params, encoding: encoding, headers: nil).responseJSON{ response in switch response.result { case .success(let value): let jsonData = JSON(value) completionHandler(jsonData) break case .failure: completionHandler(nil) break } } } } // API - Getting the latest order (Customer) func getLatestOrder(completionHandler: @escaping (JSON) -> Void) { let path = "api/customer/order/latest/" let params: [String: Any] = [ "access_token": self.accessToken ] requestServer(method: .get, path: path, params: params as [String : AnyObject], encoding: URLEncoding()) { (json) in print(json!) } } } -
How to save all related data using django signals post_save
I just want that if the admin select Course(ABM) and Education Level (Grade 11) it will save all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. this is my code in models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True,null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): teachers = SubjectSectionTeacher.objects.all().filter(Sections=instance.Section,Education_Levels=instance.Education_Levels) if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( # This should be the instance not instance.Student_Users Students_Enrollment_Records=instance, # The below is also not an instance of SubjectSectionTeacher Subject_Section_Teacher=teachers.first()) -
best method to mock http request without use of url in django
I have 2 class like below I don't have url path for class A what is the best method to test process_get? I tried mocking a http request with request in rest_framework.request but they don't let me set query_params witch i need to set class A(APIView): def process_get(self, request, form): pass class B(A): def get(self,request) pass -
Use jinja2 with some django apps but not others?
I cannot seem to get Django to use its default Templates engine for the admin app and use Jinja2 everywhere else. It seems that no matter what I do, I can only ever get one of the two to work at any one time. I've tried reordering whether the Jinja or DjangoTemplates block goes first, adding/removing stuff from the DIRS field, and setting APP_DIRS to False. I either break it all (either with a TemplateNotFound or wrong syntax when the wrong backend tries to render) or only get one of the two functioning. I'm using the django-jinja pip package, which lets me leave my templates in the templates folder instead of moving them to a jinja2 directory. 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", ], }, }, { "BACKEND": "django_jinja.backend.Jinja2", "DIRS": [os.path.join(BASE_DIR, "templates")], "APP_DIRS": True, "OPTIONS": { "match_extension": ".html", "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.contrib.auth.context_processors.auth", "django.template.context_processors.i18n", "django.template.context_processors.media", "django.template.context_processors.static", "django.template.context_processors.tz", ], "match_regex": r"^(?!admin/).*", }, }, ]``` (OK, I think I can get rid of a bunch of those processors that I'm pretty sure I'm not using, but that's a separate issue) -
form is not getting updating after submitting like button
When submitting the button after clicking like it is creating the object successufuly but like field is updating with null value and django is getting error 302. Can somebody please help me with this. models.py Codes in models.py class VoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self,song,user): try: return Vote.objects.get(song=song,user=user) except ObjectDoesNotExist: return Vote(song=song,user=user) class Vote(models.Model): UP = 1 DOWN = -1 VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),) like = models.SmallIntegerField(null=True, blank=True, choices=VALUE_CHOICE) user = models.ForeignKey(User,on_delete=models.CASCADE) song = models.ForeignKey(Song, on_delete=models.CASCADE) voted_on = models.DateTimeField(auto_now=True) objects = VoteManager() class Meta: unique_together = ('user', 'song') views.py Codes in views.py class SongDetailView(DetailView): model = Song template_name = 'song/song_detail.html' def get_context_data(self,**kwargs): ctx = super().get_context_data(**kwargs) if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote(song=self.object, user = self.request.user) if vote.id: vote_url = reverse('music:song_vote_update', kwargs={'song_id':vote.song.id,'pk':vote.id}) #'pk':vote.id else: vote_url = reverse('music:song_vote_create', kwargs={'song_id':vote.song.id}) vote_form = SongVoteForm(instance=vote) ctx['vote_form'] = vote_form ctx['vote_url'] = vote_url return ctx class SongVoteCreateView(CreateView): form_class = SongVoteForm model = Vote def get_success_url(self,**kwargs): song_id = self.kwargs.get('song_id') return reverse('music:song_detail', kwargs={'pk':song_id}) def form_valid(self, form): user = self.request.user song_obj = Song.objects.get(pk=self.kwargs['song_id']) vote_obj, created = Vote.objects.get_or_create(song = song_obj, user = user) form.instance = vote_obj return super(SongVoteCreateView).form_valid(form) class SongUpdateView(UpdateView): form_class = SongVoteForm model = Vote def form_valid(self, form): user = self.request.user song_obj = Song.objects.get(pk=self.kwargs['song_id']) vote_obj, created = Vote.objects.get_or_create(song = song_obj, user = user) form.instance … -
I have created custom button in Django admin and when we click on it it should call views.py function and put some static value on admin form
from hellogymapp.admin import BillingAdmin,TechAdmin def get_changeform_initial_data(self, request): return { 'tickets_open': 145, 'tickets_closed' :123 } -
How to post request to my backend server with long string argument by Graphql
I wanna post a request from my website to back-end (django) by GraphQL. Here is my GraphQL request. Probably because the argument is too long, the request cannot reach my server but there is no error threw by Graphql which still show the status "200". How can I solve this problem? { sendMail(mailList: "abv@gmail.com abv@gmail.com abv@gmail.com abv@gmail.com ........... (1000 mail here )", content: "testing") { data { counter } ok } } -
One model for multiple raw query
I have multiple raw query. eg => raw query 1 : select field1,field2 from employee raw query 2 : select field3,field4 from employee Of course, the actual query will more complex than this and Now I have to create multiple models for each of raw queries. model1 : field1,field2 model2 : field3,field4 I just want to know can I create one big model like that => bigmodel : field1,field2,field3,field4 and for query 1, It will return field 1 and field 2 with values and field 3 and field 4 with null. for query 2, It will return field 3 and field 4 with values and field 1 and field 2 with null. It's possible? otherwise, I have to create a lot of models for each query. -
Are HStoreFields the only way to store key:value pairs using Django models?
I am looking to track user views of specific objects. e.g. if a user watches a specific video 3x I want to be able to see how many times that user has watched that specific video. One way of doing this would be tracking user history on every page through the use of GenericForeignKeys and ContentTypes but I read in TSoD that it is best to avoid GenericForeignKeys whenever possible - and for good reason. The other way to do this would be to store key:value pairs in the database and increment the value each time a user visits the page. To do this you would use an HStoreField. The issue with this is that it is PostgreSQL specific while I am still on the SQLite db Django starts off with. This isn't much of an issue because I planned to switch to PostgreSQL anyways but the whole scenario has me wondering: is there another way to accomplish this task that I am not seeing in all my research? Much thanks for any input in advance! -
Python functions are called too soon in Django
Even if I assign it to a variable, the API call triggers too soon. I've implemented a few ideas, as shown in the examples (not the actual code, but same principles). """ Example #1 """ fruit = 'banana' def search_engine(fruit): engine = { 'apple': google.search(Time="10 hours ago"), 'banana': yahoo.searchNow(Time="12 min ago"), 'pear': bing.searchNow(Time="13h ago"), } print(engine[fruit]) search_engine(fruit) """ Example #2 """ fruit = 'banana' def search_engine(fruit): GS = google.search(Time="10 hours ago") YS = yahoo.searchNow(Time="12 min ago") BS = bing.searchNow(Time="13h ago") engine = { 'apple': GS, 'banana': YS, 'pear': BS, } print(engine[fruit]) Let's assume that Time is an improper value, and will throw an exception regardless. in Example #1, however, "apple" is called first and throws an exception, when "banana" should be called instead. In Example #2, it throws an exception at "GS = google.search(Time....", instead of doing it for "YS = yahoo.searchNow..." I've only had this issue since trying to integrate my Python project into Django. -
Access-Control-Allow-Origin is set, but I'm still getting CORS Error
I'm trying to connect my a React Application to a Django Server. The React application is running on http://127.0.0.1:3000/ The response headers has Access-Control-Allow-Origin: http://127.0.0.1:3000 set, yet I am still seeing the error. I am currently using Django's corsheaders package as recommended everywhere. Decent example of the recommendation How can I enable CORS on Django REST Framework. But I have also tried custom middleware at this point. My Django Settings.py file contains the following MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] Django is on 8000, React on 3000 CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:3000', 'http://localhost:3000', 'http://127.0.0.1:8000', 'http://localhost:8000', ] My request in react looks like this. (It works when I run it directly, not through the browser) const fetch = require('node-fetch') const response = await fetch( url, { json: true, method: 'GET', headers: { 'Access-Control-Allow-Origin': '*', Accept: '*/*', 'Content-Type': 'application/json' } } ) Again, it is so strange that I am making the request from http://127.0.0.1:3000 and the response headers has Access-Control-Allow-Origin: http://127.0.0.1:3000 but for some reason it is still failing. Oh the error message in the browsers console is Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/query/?date=2019-10-25. (Reason: missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ … -
Trying to display output from the user input onto the same html screen
I'm sure this is not difficult, I'm just new to Django and would really appreciate some help. I've been trying to take two inputs ('sentence' variable, and 'word' variable) as CharFields. Then take those two inputs and create a new output with them. I can get this to print on the console but not to display it on the html page. Thank you. Here is what I got. --> form.html <div class="main"> <div class="container"> <div class="row"> <form class="content" method="post"> {% csrf_token %} {{ form }} {% if output %} <h3>{{ output }}</h3> {% endif %} <input type="submit" name="submit_cmd" value=Run /> </form> </div> </div> </div> --> views.py from django.shortcuts import render from django.http import HttpResponse from .forms import ContactForm import subprocess as sp import nltk from nltk.corpus import wordnet nltk.download('wordnet') def contact(request): syn = set() output = "" form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sentence = form.cleaned_data['sentence'] word = form.cleaned_data['word'] for synonym in wordnet.synsets(word): for l in synonym.lemmas(): if l.name() != word: syn.add(l.name().lower()) for new_wrd in list(syn): print(sentence.replace(word, new_wrd)) output += sentence.replace(word, new_wrd) return render(request, 'pk_app/form.html', {'form': form}) --> forms.py from django import forms class ContactForm(forms.Form): sentence = forms.CharField(required=True) word = forms.CharField(required=True) -
Django - CSS file not linking with template correctly
In my project, I attempt to link my html template to a CSS file that I have in my static folder. I have added STATIC_ROOT, STATIC_URL and STATICFILES_DIRS to my settings.py. In my static folder, I have a folder called styles, and within that, I have a file named signup.css . I have also ran python manage.py collectstatic. In my template I attempt to reference that CSS file to change the colour of my h1, however no change occurs. Template: {% load static %} <head> <link rel="stylesheet" href="{% static 'styles/signup.css' %}"> </head> <h1>YO</h1> <div id="signupformdiv"> <form class="signupform" action="{% url 'signup' %}"> </form> </div> signup.css: h1 { color: red; } The colour of my h1 remains black. Does anybody know the issue? Thank you. -
Queried Results from Database Disappear on Pagination: Django
I am new to using the Django framework. I am creating a form to take in User input to query a database. I want to display the queried results on the same page, below the from fields. I am able to do the same. However, upon implementing Pagination, and clicking the 'next' link, or trying to sort the results using 'order_by', the queried results disappear from the webpage. How can this be resolved? Below are my code files:\ views.py: def get(self, request, *args, **kwargs): paginated_objects = [] order_by = None form = QueryForm(request.GET) button_state = True if form.is_valid(): max_traj_len = form.data["traj_len_user"] print(form.data["submit"]) print(max_traj_len) order_by = request.GET.get('order_by', 'traj_len') ##default order_by is set here backtrack_flag = form.data["backtrack_user"] print(backtrack_flag) queried_objects = list(collection.find({'traj_len':{'$lte':int(max_traj_len)}})) paginator = Paginator(queried_objects, 25) page = request.GET.get('page') paginated_objects = paginator.get_page(page) button_state = request.GET.get('submit') return render(request, self.template_name, {'form': form,'object_list': paginated_objects, 'order_by': order_by, 'button_state': button_state}) template.html: {% extends 'base.html' %} {% block content %} <form action='' method='get'> {% csrf_token %} <table>{{ form.as_table }}</table> <input type="submit" name="submit" value="Query"> </form> {% if button_state == 'Query' %} <table id="studata"> <thead> <th><a href="?order_by=traj_id">Traj ID</a></th> <th><a href="?order_by=traj_path">Traj Path</a></th> <th><a href="?order_by=traj_len">Traj Length</a></th> <th><a href="?order_by=interpolated_id">Interpolated_ID</a></th> <th><a href="?order_by=inter_path">Interpolated Path</a></th> <th><a href="?order_by=inter_path_len">Interpolated Path Length</a></th> <th><a href="?order_by=backtrack">Backtrack</a></th> <th><a href="?order_by=reached_goal">Reached Goal</a></th> </thead> {% for … -
Psycopg2 failed with exit status of 1120 on Windows 10
I have a venv with Python 3.8 installed, updated computer from windows 7 to 10 and now I can't install Psycopg2 nor Psycopg2-binary. It is giving me the following error: I have tried: Installing from github with pip install git+https://github.com/nwcell/psycopg2-windows.git@win32-py25#egg=psycopg2. It still says Psycopg2 is not installed: Any suggestions? Thank you very much. -
Not able to display in Template the foreign key using ListView
I'm trying to display a photographic session with all of it photos, so I have the session name in one model and I have the pictures in another model linked by a foreign key. I'm not able to display it in the HTML I'm not sure if I'm using the ListView get_context_data correctly and I'm certainly sure the the html code is not correct but I have not found how to do it. views.py class SessionPictures(generic.ListView): model = PostSession template_name = 'photoadmin/gallery.html' def get_context_data(self, **kwargs): context = super(SessionPictures, self).get_context_data(**kwargs) context['picture'] = Images.objects.all() return context models.py class PostSession(models.Model): session_name = models.CharField(max_length=25) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.session_name) class Images(models.Model): name = models.ForeignKey( PostSession, related_name='images', on_delete=models.CASCADE, null=True, blank=True) picture = models.ImageField(upload_to='pictures') html {% extends 'base.html' %} {% load static %} {% block content %} <h2>Images</h2> <ul> {% for session in object_list %} <li>{{ session.session_name }}</li> <ul> <li>{{session.picture_set.all.url}}</li> </ul> {% endfor %} </ul> {% endblock %} I'm expecting this: Woods picture1.url picture2.url picture3.url Beach Picture4.url picture5.rul -
Bullet points in Django
Is there a model field to create a list of bullet points in Django? Like you would do for specifications of a product? If not how would I do this? Example Specifications: - feature - feature - feature - feature I don't have any code to show as I don't know where to start. I haven't found anything online of what I'm looking for.