Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelSerializer required field data from instance
I have following serializer: class TrackGroupSerializer(serializers.ModelSerializer): class Meta: model = TrackGroup fields = ('id', 'name', 'report', 'tracks') # `report` is FK I am taking report id from url, so I thougth that this will work: ... track_group = TrackGroup(report=report) serializer = TrackGroupSerializer( instance=track_group, context=dict(request=request), data=request.data ) if serializer.is_valid(): ... This doesn't work because serializer has error for field report as the field is missing and is required. What is a correct way to provide data like report and have it still listed in TrackGroupSerializer fields as this serializer is used to return all data in response. Thanks -
Why does gunicorn serve static files on port 8000 only?
I have installed python 3.5.2, django 2.1.5 and gunicorn v 19.9.0 on a raspberry pi 3. django and gunicorn are installed in the same virtual env. I am ultimately going to use nginx as a proxy server, but feel like I have to solve this problem first. When running a gunicorn server listening on port 8000, I can open local browser and point to localhost:8000/admin. The django admin app static files are served up just fine in this case. If I restart the gunicorn server with port number 8001 (or any other number for that matter), it still serves up the app, but no static files. The port number is the only thing changed. Change it back to 8000, works fine. Any other port, no static files. I can't find anything on this issue. starting gunicorn with: gunicorn proj-name.wsgi:application --bind 127.0.0.1:8000 django project settings file: import os os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = ["localhost", "192.168.1.20", "raspberrypi", "*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dcpages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'dcdjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
query set object in django template
Trying to display query set in a template. Does not show the objects in my templates/home.html page. I'm using templates/posts.html to be included inside the templates/home.html page. Not really sure how I should debug this or what I should do. This is my posts/posts.views def posts_list(request): # if request.user.is_authenticated(): queryset = Post.objects.all() context = { "object_list": queryset, "user": "username" } return render(request, "posts.html", context) This is my posts/models.py class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField() publish = models.DateField(auto_now=False, auto_now_add=False) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return str(self.user.username) This is my templates/post.html <!DOCTYPE html> <html lang="en"> <body> <h1>What's on your mind, {{ user }}</h1> { % for obj in object_list %} {{obj.user}}<br/> {{obj.content}}<br/> {{obj.timestamp}}<br/> {% endfor %} </body> </html> This is my templates/home.html {% if user.is_authenticated %} <h1>Homepage</h1> <!-- Posts template --> {% include "posts.html" %} <a href="{% url 'logout' %}">Logout</a> {% endif %} -
How should I setup my development environent for Django if I use 2 computers?
I'm new to webdev and this will be my first real project. I'm working on a Django website that will probably use Django CMS. It will be a blog + some custom apps that will perform actions based on forms + a link to Wikidata API. The code will be on GitHub and released open source. I need to use 2 different Windows 10 computers with PyCharm. (Alternatively I could use a cloud IDE.) The site will be hosted on a VPS with Ubuntu and VestaCP, running Apache and MySQL. I have seen that Django provides a local development environement. Since I will be using 2 computers... Should I install this environment on my computers or is it wiser to have the environement installed on my server ? If I shall install the dev environment on my server, how can I proceed to modify the files locally ? pushing with git each time ? If I install the environment on my computers, should I have a MySQL installation on each window or should I use a remote database connection to my server ? Sorry for all these questions. I'm feeling like there is a "best" way to do it that … -
Using Webpack and Django settings
I try to use Django-webpack-loader with Django and VueJs but I am not able to use correct settings with my complex project setup to load webpack bundle. My project layout is Endofyogavidya --dist/bundle.js manage.py webpack.config.js --Yogavidya ----apps ----static --------main.js --------App.Vue ----templates ----settings ------base.py ------development.py In my settings.py PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) STATIC_URL = '/public/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "dist"), ) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': '', 'STATS_FILE': os.path.join(PROJECT_ROOT, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': ['.+\.hot-update.js', '.+\.map'] } } My index.html is not working because with these settings django tries collect my assets to '/home/ytsejam/public_html/endofyogavidya/yogavidya/settings/dist'. How can I adjust my folder settings correctly ? Thanks -
what does {variable_name} in an url pattern mean in Django?
I'm reading Django Rest Framework documentation on router (https://www.django-rest-framework.org/api-guide/routers/) and encounter this: ^accounts/{pk}/$ I understand ^ means start of line, $ means end of line and everything but {pk}. What does it mean? -
I need to create something that will allow the user to filter by year a project on the website i am building with django
So basically i am trying to add a filter by year button on my website and make it work in django. I tried making the javascript for it and it works but i have no idea on how to make it work with django. `from django.db import models from django.contrib import admin class Employer(models.Model): Name = models.CharField(max_length=250) Logo = models.ImageField(upload_to='media', blank=True) Website = models.URLField(blank=True) Description = models.CharField(max_length=250) def __str__(self): return self.Name class Course(models.Model): Name = models.CharField(max_length=250) Logo = models.FileField(blank=True) Website = models.URLField(blank=True) Level = models.IntegerField(blank=True) Description = models.CharField(max_length=1000) def __str__(self): return self.Name class Team(models.Model): Name = models.CharField(max_length=250) dateCreated = models.DateTimeField(auto_now_add=True) teamDescription = models.CharField(max_length=1000) Logo = models.FileField(blank=True) yearGroup = models.IntegerField() def __str__(self): return self.Name class Project(models.Model): Name = models.CharField(max_length=250) Client = models.CharField(max_length=250) startDate = models.DateTimeField(auto_now_add=True) endDate = models.DateTimeField(blank=True, auto_now=True) Completed = models.BooleanField(default=True) briefDescription = models.CharField(max_length=250) company = models.ForeignKey(Employer, on_delete=models.CASCADE) image = models.FileField(blank=True) def __str__(self): return self.Name class Team_and_Project(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) description = models.TextField() def __str__(self): return str(self.team)+" : "+str(self.project) class Credentials(models.Model): Initials = models.CharField(max_length=250) schoolUsername = models.CharField(max_length=250) schoolPassword = models.IntegerField() Permissions = models.BooleanField() teamID = models.ForeignKey(Team, on_delete=models.CASCADE) class Team_and_Project_Image(models.Model): team_project = models.ForeignKey(Team_and_Project, on_delete=models.CASCADE) image = models.FileField() def __str__(self): #return str(self.team_project.team)+" : "+str(self.team_project.project) return str(self.team_project) + … -
Django TestCase Mixin is tested individually, how to prevent?
I wrote a Django testcase mixin for testing serializers. The serializers I want to test make use of this mixin and are working as expected. However, the mixin itself has a bad habit of being tested without being in a /tests directory. I'm wondering what could cause this issue and how I can resolve this. I have the following structure: | /project | /shared | /mixins | testcase.py | /users | /tests | /serializers | test_serializer.py | manage.py Expected is that users.tests.serializers.test_serializer TestCase which extends the shared.mixins.testcase.SerializerTestCaseMixn runs the tests from the mixin. When running ./manage.py test users runs the tests perfectly. The issue starts when running ./manage.py test without a specific app. What happens is that the shared.mixins.testcase.SerializerTestCaseMixn.test_something is executed as an individual TestCase. Though only the method name contains test_ in the mixin, but does not extend TestCase nor is in a /tests/* directory. Some example code: shared.mixins.testcase.SerializerTestCaseMixin class SerializerTestCaseMixin: x = None def test_something(self): self.assertNotNone(x) users.tests.user.serializers.test_serializer.py class UserSerializerTestCase(UserTestCaseMixin, TestCase): x = 10 def test_xxx(self): ... So when running ./manage.py test users the test in mixin passes, since x is set to 10 and is not None. When running ./manage.py test the tests in users app passes, but … -
How to handle Back option in Django formtools wizard with select2 fields
I am trying to build a wizard using django-formtools SessionWizardView. For some of the fields in the wizard I would like to utilize the Select2 library. Currently I am using django-autocomplete-light and using both Select2 and Tag widgets. It all works well until I try to implement "Back" functionality in the wizard. When the back button is pressed, all non Select2 fields have the user-inputed value, but I cannot make the Select2 fields have the user-selected value. The form asks again to select the required values. Select2 fields are using ajax requests to load the data. What is the best way to make Select2 fields keep the selected value when going back to previous wizard form? I'm using: Django==2.1, django-autocomplete-light==3.3.2, django-formtools==2.1 -
Storing Dynamic References to Multiple Fields in Multiple Tables
I have this somewhat convoluted problem that I will try to described as the following: Let's say that I need to create a read only table called "Variables" in which I would like to store several references to fields in multiple tables in a way that any change in the original value would reflect in the stored value in the "Variables" table. As I said, this table would be read only and changes follows only in one direction. To further make things more complicated, let's say that I want also to store the values generated by some model's methods. So far, I created a big mess using signals to keep the table updated. It works, but I'm not happy with this solution since it requires a lot of hard-coded stuff, and is turning out of control. I'm looking to a more scalable solution in which I could add or remove a reference to some field in some table by just updating the "Variable" table in question. Makes sense? Please help me to avoid to try to use Django’s GenericForeignKey because, with the exception of model's methods issue, is the solution that I'm more inclined to try. -
SMTPSenderRefused at /password-reset/ does not work although my environmental variables are set up
I am able to reset password when in settings.py I write this EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "anymail_id@gmail.com" EMAIL_HOST_PASSWORD = "any_password" But my code does not send mail when I write this in my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('dbu') EMAIL_HOST_PASSWORD = os.environ.get('dbp') Although my environment variables are set then also my code does not send mail For proof that my environmental variables are set is that when I run a python code given below then output comes as: anymail_id@gmail.com any_password For this code import os db_user = os.environ.get('dbu') db_password = os.environ.get('dbp') print(db_user) print(db_password) I get output as: anymail_id@gmail.com any_password This means my environment variables are set.So the why I am not able to send mail when I writ below Code: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('dbu') EMAIL_HOST_PASSWORD = os.environ.get('dbp') -
override templates in django-allauth
I have read all the possible solutions I can find on StackOverflow and been through the allauth documents. Still not able to point to my local (in my Django project) templates instead of the allauth ones (i.e. login, signup, etc.) 1. Moved my applications before the allauth ones in settings.py INSTALLED_APPS, so that it looks like this: 'users', #my custom user model app 'date_track.apps.DateTrackConfig', # main app 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.twitter', ] 2. Modified my project structure and moved allauth templates (login, signup, etc.) to this location. The structure now looks like this: my_project/templates/allauth/ inside this dir I have the 3 allauth dirs: 1. account 2. openid 3.socialaccount And inside these dirs I have all the allauth templates, plus, base.html 3. I have modified my TEMPLATES Setting in settings.py to look like this: 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'allauth','accounts', 'socialaccount')], Yet, whenever I access the link off my home page (which inherits from my project's base.html), it heads right over to the templates in: site-packages/allauth/templates/account directory. base.html has the links to the templates as follows: {% if user.is_authenticated %} <li class="nav-item"> <p><h6>You are Logged in as <I>{{user.username}}</I></h6></p> </li> <li class="nav-item"> <a class="nav-link active" href="{% url 'account_email' %}">Email</a> </li> <li … -
NoReverseMatch at /products/ , 'products ' is not a registered namespace
I'm making 2 apps in Django , the first one is called products , the second is called blog , I'm made the first one and everything was working correctly but when i added the second one , both didn't work : my urls.py contain : path('products/', include('products.urls')), path('blog/', include('blog.urls')), blog\urls.py contain : app_name = 'articles' urlpatterns = [ path('<int:id>/', article_detail_view, name='article_detail'), ] products\urls.py contain : app_name = 'products' urlpatterns = [ path('<int:id>/', product_detail_view, name='product_detail'), ] any help ? -
Django HTML5 iPhone numeric input
I am using simple widgets in my ModelForm to force the form to use certain input types. class NumberInput(Input): input_type = 'number' and then later in the form widgets = {'assetNumber': NumberInput()} This works but not for number inputs on iPhones. According to this link I need to use <input type="number" pattern="\d*"/> <input type="number"/> is not showing a number keypad on iOS However adding that to the NumberInput class doesn't work. Any ideas about adding this pattern to the widget? Thanks! -
Parsing JSON with Python TypeError: list indices must be integers or slices, not str
i read about 10 to 12 answer but nothing help me. i wanna print the url shows in picute click to see this is my code : > from urllib.request import urlopen > import json as simplejson > link = "https://api.instagram.com/v1/users/self/media/recent/?access_token=2290710571.098b867.5cf99a24896b476982c70c47eb0a0413" > response = urlopen(link) data = simplejson.load(response) print > (data['data']['0']['image']['standard_resolution']['url']) but i get this error : TypeError: list indices must be integers or slices, not str i saw someone say put [0] in you code. but i dont get what it is. where to put it and ... -
Dynamically creating view not working as intended
I am trying to create a url and view for when a button on a page is pressed. The button correctly redirects to the url; however, the view does not load. I receive the error Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['view\\/profile\\/(?P<user_id>[^/]+)\\/$']. I have attached my code below and would greatly appreciate any help. views.py def profile(request, user_id): user = User.objects.get(id=user_id) form = TeacherProfileForm() context = {'form' : form, 'user' : user} return render(request, 'view/profile.html', context) urls.py path('profile/<user_id>/', views.profile, name='profile'), HTML with button that redirects to profile view {% for user in data %} <div class="row"> <div class="col-md-4 left"> <img src="{{ user.avatar.url }}" height="170" width="170"> </div> <div class="col-md-4 mid"> <h3>{{ user.first_name|capfirst }} {{ user.last_name|capfirst }}</h3> <h5>{% if user.instrument1 != "" %}{{ user.instrument1|capfirst }}{% endif %}{% if user.instrument2 != ""%}, {{ user.instrument2|capfirst }}{% endif %}{% if user.instrument3 != "" %}, {{user.instrument3|capfirst }}{% endif %}{% if user.instrument4 != "" %}, {{ user.instrument4|capfirst}}{% endif %}{% if user.instrument5 != "" %}, {{ user.instrument5|capfirst }}{% endif %}</h5> <p>{{ user.bio|capfirst }}</p> </div> <div class="col-md-4 right"> <br /> <x-star-rating value="5" number="5" id="rating"></x-star-rating> <br /> <br /> <br /> <a href="{% url 'view:profile' user_id=user.id %}"> <button type="submit" name="submit" class="btn blue_button">Book Lesson</button> </a> </div> … -
zappa giving 413 request entity too large error for Django form with mutiple images
I have a Django project that requires users to use add multiple images to a post article. I am using django and deploying it using zappa. I know that in Zappa the maximum size in the page load is 10mb. I have 1 post image and 7 prep images. When user adds 7 large files and then hits submit I get the error below HTTP413: PAYLOAD TOO LARGE - The server is refusing to process a request because the request entity is larger than the server is willing or able to process. Is there a way in which the images are added one by one instead of all at once so the form does not break and I don't get the above error class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) message = models.TextField() post_image = models.ImageField(upload_to='post_images/') def save(self, *args, **kwargs): im = Image.open(self.post_image) super(Post, self).save() output = BytesIO() basewidth = 700 wpercent = (basewidth / float(im.size[0])) hsize = int((float(im.size[1]) * float(wpercent))) im = im.resize((basewidth, hsize)) # after modifications, save it to the output im.save(output, format='JPEG', quality=40) output.seek(0) self.post_image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.post_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super().save(*args, **kwargs) Then I have the model that adds multiple … -
Running a .py file from a FileField
I have a model that contains a FileField. I use it to upload .py files. models.py class FileModel(models.Model): file = models.FileField(null = True, blank = True, upload_to = 'files') file_name = models.CharField(max_length=200) I want to retrieve the uploaded files and execute the code within a view. views.py def get_return_from_file(request): post = FileModel.objects.get(file_name__iexact='example_name') a = post.file.read() print ('a') Example uploaded python file 'example_name' def main(): return 'hello world' if __name__ == "__main__": main() However this returns b'def main():\n return 'hello world'\n if name == "main":\n main()' instead of 'hello world' How can I execute the code in the FileField and access it's returned values instead of just reading it as a string? Thanks! -
Django REST: OPTIONS request is registered as PUT
Whenever the browser sends an OPTIONS request, Django REST registers that as a PUT request. I was writing my permission code when I noticed it. I use the default request parameter that is passed into the def has_object_permission( self, request, view, obj ):. Using request.method will return the correct request method for every request except for OPTIONS. However, when I use request.method in a my get_permission( self, request, view ): function in a different part of the project, correct response is returned. Could there be something wrong with the has_object_permission() function? Currently I just check if the request is PUT, as I believe PUT requests are not used by Django anyway. But it would be nice if I could use the actual name instead. My Django REST version is 3.9.0 -
Django rest framework: AttributeError: 'NoneType' object has no attribute '_meta'
I am following this tutorial on youtube: https://www.youtube.com/watch?v=0d7cIfiydAc&index=5&list=PLillGF-RfqbbRA-CIUxlxkUpbq0IFkX60 I even copied the exact code for the third time from his github, just to be sure, but I am still getting this error, I am using rest api, and according to the traceback the problem lies in the serializer.is_valid line in api.py, I don't know what is the cause of the problem. api.py from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) }) serializers.py from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user Traceback File "/Users/tspc/.local/share/virtualenvs/workunteerpro-aGYRWm4E/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/tspc/.local/share/virtualenvs/workunteerpro-aGYRWm4E/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/tspc/.local/share/virtualenvs/workunteerpro-aGYRWm4E/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/tspc/.local/share/virtualenvs/workunteerpro-aGYRWm4E/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in … -
How can I create object with both file and string (nested+array) form-data request?
I'm trying to handle form-data with drf. I handled other cases - single file, multiple files (with only FILES) and so on. But now I'm trying to send multiple objects with data and other contents. This is my sample data with files (in unittest) data = { 'title': 'test_title', "indicators": [ { "brief": "test brief", "content": "test content", "chart": open('mediafiles/thumb_orgfund.jpg'), }, { "brief": "test brief 2", "content": "test content 2", "chart": open('mediafiles/thumb_orgfund.jpg'), } ] } Unlike other test, I cannot handle those data with form-data / I have to create indicator objects with those arrays. Also, it's hard to send such request from postman with form-data - I cannot make request with nested + array. If I trying to get files with request.FILES, I cannot match them with each object. Also, I cannot use bulk_create or even create cause the data (request.data) is not valid json type because of the MultiDict files. Is there any way to save the file and str once? Thank you for any advice. -
How to correctly link VueJs with Django Api
I have a simple question, I have followed a tutorial on Medium. I have integrated a Django Rest API with VueJs. Now I want my article list view to link to article detail view. But v-on:click is directing to wrong address in developer tools. When I click a link, I get "http://localhost:8000/tr/articles/api/articles/2/" with 404 error message. And in developer tools I am getting: N {url: "api/articles/2/", ok: false, status: 404, statusText: "Not Found", headers: M, …} This what I have achived until now. <div class="col col-xl-4 col-lg-4 col-md-6 col-sm-6 col-12" v-for="article in articles"> <div class="ui-block"> <!-- Post --> <article class="hentry blog-post" v-on:click="getArticle(article.id)"> <div class="post-thumb"> <img :class="{ full: fullWidthImage }" @click="fullWidthImage = !fullWidthImage" v-bind:src="article.image" alt="photo"> </div> <div class="post-content"> <a href="#" class="post-category bg-blue-light">THE COMMUNITY</a> <a href="#" class="h4 post-title">${article.title}</a> <p>${article.content}</p> </article> </div> </div> This is my script new Vue({ el: '#starting', delimiters: ['${','}'], components:{ 'articlelist': articlelist, }, data: { articles: [], loading: false, currentArticle: {}, 'fullWidthImage': false, message: null, newArticle: { 'title': null, 'content': null, 'author': null, 'image': null, }, }, mounted: function() { this.getArticles(); }, methods: { getArticles: function() { this.loading = true; this.$http.get(`/api/articles/`) .then((response) => { this.articles = response.data; console.log(response.data); this.loading = false; }) .catch((err) => { this.loading = false; console.log(err); … -
Django query function not properly filtering for user type
I am trying to filter all my users and select ones that have user is teacher = True and user has instrument1 ='Cello'. My function is displaying all the users, instead of just the teachers, that have user has instrument1 ='Cello'. I am wondering how to properly write my function so that it selects teachers as well. If users are a teacher they are saved in my database with a user.teacher=1, else user.teacher=0. views.py def teacher_list(request): data = User.objects.filter(Q(teacher=True) and Q(instrument1='Cello')) form = TeacherProfileForm() context = {'form' : form, 'data' : data} return render(request, 'view/teacher_list.html', context) HTML <div class="desktop"> {% for user in data %} <div class="row"> <div class="col-md-4 left"> <img src="{{ user.avatar.url }}" height="170" width="170"> </div> <div class="col-md-4 mid"> <h3>{{ user.first_name|capfirst }} {{ user.last_name|capfirst }}</h3> <h5>{% if user.instrument1 != "" %}{{ user.instrument1|capfirst }}{% endif %}{% if user.instrument2 != ""%}, {{ user.instrument2|capfirst }}{% endif %}{% if user.instrument3 != "" %}, {{user.instrument3|capfirst }}{% endif %}{% if user.instrument4 != "" %}, {{ user.instrument4|capfirst}}{% endif %}{% if user.instrument5 != "" %}, {{ user.instrument5|capfirst }}{% endif %}</h5> <p>{{ user.bio|capfirst }}</p> </div> <div class="col-md-4 right"> <br /> <x-star-rating value="5" number="5" id="rating"></x-star-rating> <br /> <br /> <br /> <a href="{% url 'view:profile' user.id %}"> <button type="submit" … -
I have done something like this and it throws: UnboundLocalError at / local variable 'context' referenced before assignment error
after modifying the code like: class Index(FrontendMixin,TemplateView): template_name = "myapp/frontend/index.html" def get_context_data(self,**kwargs): super().get_context_data(**kwargs) context = [] if Post.objects.filter(deleted_at__isnull=True).count() > 1: context['Allpost'] = Post.objects.filter(publish=True).order_by('-created_at') context['mostrecentnews'] = News.objects.filter(publish=True, deleted_at__isnull=True).order_by('-created_at')[:1] else: context = [] return {'context':context} it throws TypeError at / list indices must be integers or slices, not str error. class Index(FrontendMixin,TemplateView): template_name = "myapp/frontend/index.html" def get_context_data(self,**kwargs): super().get_context_data(**kwargs) if Post.objects.filter(deleted_at__isnull=True).count() > 1: context['Allpost'] = Post.objects.filter(publish=True).order_by('-created_at') context['mostrecentnews'] = News.objects.filter(publish=True, deleted_at__isnull=True).order_by('-created_at')[:1] else: context = [] return {'context':context} -
Display query set object in django template
I have a model Post that I'm trying to display all the posts onto a template. I'm including the post.html onto the home.html.... I found a similar problem to my question but the objects still are not getting displayed. https://stackoverflow.com/questions/14321515/accessing-query-set-object-in-django-template I tried the to use python manage.py shell to create an object. So first I did this. Post.objects.all() <QuerySet [<Post: test>, <Post: admin>]> then I tried to create a new posts. Post.objects.create(user="test", content="New comment") but got this error: ValueError: Cannot assign "'test'": "Post.user" must be a "User" instance. Tried to troubleshoot and couldn't resolve it, I figure this is the root of my problem why the objects aren't showing up in the templates. This is my posts/posts.views def posts_list(request): # if request.user.is_authenticated(): queryset = Post.objects.all() context = { "object_list": queryset, "user": "username" } return render(request, "posts.html", context) This is my posts/models.py class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField() publish = models.DateField(auto_now=False, auto_now_add=False) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return str(self.user.username) This is my templates/post.html <!DOCTYPE html> <html lang="en"> <body> <h1>What's on your mind, {{ user }}</h1> {{ for obj in object_list }} {{obj.user}}<br/> {{obj.content}}<br/> {{obj.timestamp}}<br/> </body> </html> This is my templates/home.html {% if user.is_authenticated …