Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not show image field
Not showing image when upload , what is problem ? setting.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = 'media/' html. {% for tt in article %} <div class="content_box"> <div class="content_l left"> <div class="horoscope_box_big"> <div class="blog_img1"> <img src="{{ tt.image.url }}" alt="{{tt.title}}" width="50%" /> {{ tt.image.url }} </div> <h1 class="blog_title1"> {{ tt.Title }} <div class="blog_descr1"><h1>more about</h1> <p> {{ tt.body }}</p> </div> </div> {% endfor %} models.py class Blogmodel(models.Model): Title = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="images/",null=True) body = RichTextField(blank=True, null=True) slug = AutoSlugField(populate_from='Title', unique=True,blank=True, null=True) def __str__(self): return self.Title views.py def blog_list(request): articles = Blogmodel.objects.all() args = {'articles':articles} return render(request,'blog.html',args) def blogDetail(request, slug): article = Blogmodel.objects.filter(slug=slug) args = {'article':article} return render(request,'blogdetail.html',args) urls.py from django.urls import path from .views import singCategory,Home,blog_list,blogDetail from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',Home,name= "Home"), path('horoscope/<slug:slug>/<slug:cat>',singCategory,name='singCategory'), path("blog/",blog_list, name="blog_list"), path("blog/<slug:slug>",blogDetail, name="blogDetail"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
File upload problem with AWS using Django
I have deployed my django app through cpanel. Static and media files are correctly served through AWS S3. But when i try to upload a file/pic it is not uploading and shows no error and redirects to home page with the url of the page on which file was uploaded. Home page URL: www.example.com, Upload page URL:www.example.com/upload. Bucket access is public. IAM user has full access to S3 I will be very thankful to you for your precious time and help. CORS Policy <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> Bucket Policy { "Version": "2012-10-17", "Id": "Policy1603207554013", "Statement": [ { "Sid": "Stmt1603207062804", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::django-bucket/*" }, { "Sid": "Stmt1603207552031", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::085459706277:user/django_user" }, "Action": "s3:*", "Resource": [ "arn:aws:s3:::django-bucket/*", "arn:aws:s3:::django-bucket" ] } ] } settings.py AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings STATIC_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' STATICFILES_STORAGE = 'stock_app.storage_backends.StaticStorage' # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'stock_app.storage_backends.PublicMediaStorage' storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticStorage(S3Boto3Storage): location = 'static' default_acl = … -
how to reflect changes made on postgres database of django from one pc to other
We three working with Django and postgres is the database. Whenever we push the code to GitHub. The database data is not reflecting. The data I stored is visible to me only. The postgres user, password and database name are same on all our laptops. How to make when I push that has to go their databases also. -
How to send multiple json objects to a django model serializer
This is my modelserializer class Testmasterserializer(serializers.ModelSerializer): class Meta: model = Dime3d_testmaster fields = ('visitId','testId','testType','status') I want to send multiple json object how can I send [{ "visitId": "wsTp6anrDBQE", "testId": "RVeaJn6n", "testType": "windlass", "status": "fine" }, { "visitId": "wsTp6anrDBQE", "testId": "Sq3LxKsNDP", "testType": "windlass", "status": "fine" } ] Like this. How can I do it. Is there anyway? I dont want to use nested serializer as in that one params is added as like this ["data" :{ "visitId": "wsTp6anrDBQE", "testId": "RVeaJn6n", "testType": "windlass", "status": "fine" }, { "visitId": "wsTp6anrDBQE", "testId": "Sq3LxKsNDP", "testType": "windlass", "status": "fine" } ] I dont want this -
Resend failed web socket messages django
I have setup django channels with redis: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": {"hosts": [(REDIS_HOST, REDIS_PORT)]}, } } On connection to my websocket channel I update a row in my database for the corresponding user/team - socket_channel - with the websocket channel_name. team.socket_channel = self.channel_name team.save() On disconnection, I remove this from the row. I have created a handler for my Team model: def send_ws_message(self, message: WSStruct) -> bool: channel_layer = get_channel_layer() if not self.socket_channel: logging.error(f"{self.username} is not connected to a socket") # TODO store message in redis return False async_to_sync(channel_layer.send)(self.socket_channel, message.dict()) return True I am wanting to add two pieces of functionality: When the team connects to the channel again they will receive all messages that were not received because of the team not actually being connected to the websocket (the TODO above). A sort of ack that the client actually received the websocket message and if not will store for sending on reconnection/ping-pong. I am assuming the best way to do this is with a redis store? But I would also like to not reinvent the wheel here as imagine this is a fairly common design? Any advice would be greatly appreciated. -
Problem with ValidationError function when writing your own validation
Problem with ValidationError function when writing your own validation. I want to write my own ValidationError function without using the clean prefix. When I use the ValidationError function, I expect the error to be displayed in a form, but the error is displayed in the console. What can you give me advice? if clean_data['email']!=user.email: if User.objects.filter(email=clean_data['email']).exists(): raise ValidationError('') -
Ajax is reloading the entire page while using django pagination
ajax : AJAX.update('update', {'target_url': SEARCH_URL, 'data': SEARCH_PARAMS, 'processor': function (data) { var $html = $(data.html); $('#update').replaceWith(data.html); } }); html : <div id="update" style="overflow-x: hidden;"> <table> <thead> ---------- </thead> <tbody> {% for yacht in page.object_list %} <tr> ----- </tr> {%endfor%} </tbody> </table> Table is using django pagination while we edit 3rd page its redirecting to page1. How can we restrict redirection to the first page using AJAX? -
Is Django Backend APi reliable with React Frontend
I need guidance or explanation about is Django Backend api is reliable or useful for React or not. Any One Full stack developer provide me detail. -
Django ORM query by model method returned value
I am trying to query fields that are model fields, not user fields. These is my models: class Itinerary(models.Model): days = models.PositiveSmallIntegerField(_("Days"), null=True, blank=True) class Tour(models.Model): itinerary = models.ForeignKey( Itinerary, on_delete=models.CASCADE ) start_date = models.DateField(_("Start Date"), null=True, blank=True) def get_end_date(self): return self.start_date + datetime.timedelta(days=self.itinerary.days) I am trying to query the Tour table like this below way: tour = Tour.objects.filter( get_end_date__gte=datetime.now() ) But it returning the error that i don't have such fields Can anyone help me in this case? -
django how to create instance of user
I am creating a simple application, successfully created for a single user, but I want to develop for multiple users, but unable to do so... i.e. user A can create his task and save in the database. similar B user can create tasks and store in the database. and each can see their own tasks I am newbie unable to proceed with the creation of instance can someone please guide me or point me to a blog ( searched online but no help ) I already asked this question however i was not clear ( django each user needs to create and view data Issue) hope now I am clear. My model : from django.contrib.auth.models import User, AbstractUser from django.db import models # Create your models here. from django.db.models import Sum, Avg class Task(models.Model): user = models.ForeignKey(User, null=True,on_delete=models.CASCADE) title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True,auto_now=False,blank=True) purchase_date = models.DateField(auto_now_add=False,auto_now=False,blank=True,null=True) price = models.FloatField(max_length=5,default='0.00',editable=True) def __str__(self): return self.title @classmethod def get_price_total(cls): total = cls.objects.aggregate(total=Sum("price"))['total'] print(total) return total Views def createTask(request): form = TaskForm() if request.method =='POST': form=TaskForm(request.POST) if form.is_valid(): form.save() return redirect('query') context = {'form':form} return render(request,'tasks/create.html',context) urls from django.urls import path from . import views urlpatterns = [ #path('', views.index, … -
Python Shell: Using Backslash to make multiple method calls on single Class Function?
Pardon the horrific title but I don't know how else to describe this. In a django tutorial I find class calls in the python shell that look like this: >>> Post.objects.filter(publish__year=2020) \ >>> .filter(author__username='admin') I assume that both .filter method calls are performed on the Post.objects class function. This way the object can be filtered for two conditions, published in year: 2020 and authored by user: admin. How would I write the same in the python editor instead of the shell? This doesn't work (obviously): Post.objects.filter(publish__year=2020).filter(author__username='admin') -
Customized django all-auth form not submitting
I am using the django all-auth login form. I wanted to customize the look of the form fields so I changed login.html within the account folder to look like this: <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {% for field in form.visible_fields|slice:'2' %} <div class="row form-group"> {% if field.name == 'login' %} <input type="text" placeholder="Email"><i class="fas fa-at"></i> {% else %} <input type="password" placeholder="Password"><i class="la la-lock"></i> {% endif %} </div> {% endfor %} <a href="{% url 'account_reset_password' %}">Forgot Password?</a> <button type="submit">Sign In</button> </form> The form renders exactly how I would like it to, however nothing happens when I click on submit. What is strange to me is that the form submits perfectly fine if in place of my for loop I simply type {{ form.as_p }}, it just doesn't look how I want. Can anyone see an error in my loop, or is there something else wrong here. I have been looking for a solution online but so far been unsuccessful -
How to change the primary key of manytomany table in django
I am changing the primary key of the legacy database. I was able to change the primary key by setting id as the primary key. Before class User(models.Model): name = models.CharField(max_length=5) email = models.CharField(max_length=5) age = models.CharField(max_length=5) After class User(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=5) email = models.CharField(max_length=5) age = models.CharField(max_length=5) Then python manage.py makemigrations python manage.py migrate This is working fine. But I also want to change the default primary key of the tables created via ManyToMany feild. User Model class User(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=5) email = models.CharField(max_length=5) age = models.CharField(max_length=5) UserProfile Model class UserProfile(models.Model): id = models.BigIntegerField(primary_key=True) address = models.CharField(max_length=5) father_name = models.CharField(max_length=5) pincode = models.CharField(max_length=5) user = models.ManyToManyField(User) The ManytoMany field creates table called User_user_userprofile with id as Autofield basically previous or default django primary key. id, user_id, userprofile_id ManytoMany Table Now, How to change the primarykey of ManytoMany Feild ie id created by Django? PS: Django: 1.11 Python: 2.7.5 DB: Sqlite3 3.7.17 2013-05-20 -
How do I add an arbitrary number of rows in my database via a Django ModelForm?
I have a situation where I want to insert an arbitrary number of rows in my database via a Django ModelForm. I looked here and here on Stack Overflow and here in the Django documentation, but wasn't able to figure it out for my use case. As far as my models go, I have an Employer, a JobListing and a Category_JobListing. I want the user to be able to select multiple categories (an undetermined number of them) and I want to place all of those Category_JobListings as models in my database. What I tried to do, as you'll see in the code below, is to override the widget for the category field of my Category_JobListing model to be CheckboxSelectMultiple, but that didn't work as I expected. The multiple checkboxes appear, but when I try to submit something I get the error saying ValueError at /submit-job-listing/ The Category_JobListing could not be created because the data didn't validate What follows are the relevant parts of the files in my project. models.py: class Employer(models.Model): # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES) short_bio = models.TextField(blank=True, null=True) website = models.URLField() profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True) admin_approved = models.BooleanField(default=False) def … -
Count the number of user using model_name
I'm taking model_name while user doing normal register. I want to count the number of user using model_name while registartion. Any help, would be much appreciated. thank you so much in advance. models.py : class CarOwnerCarDetails(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) car_company = models.CharField(max_length=20) car_model = models.CharField(max_length=10) serializers.py: class CarModelListSerializer(ModelSerializer): carmodel_user = SerializerMethodField() def get_carmodel_user(self, request): user_qs = User() user = CarOwnerCarDetails.objects.filter(user_id__id=user_qs) created_count = CarOwnerCarDetails.objects.filter(car_model=user).count() return created_count class Meta: model = CarModel fields = ['id', 'model', 'is_active', 'created', 'category_name', 'carmodel_user'] -
Django Best Practice to store cloud storage file url (s3/Alibaba OSS) inside relational database like postgres
I am using S3 and Alibaba OSS in my django project as the storage classes. Have used url field in the table to refer to the object in the storage. But the url is not permanent. Like for s3, we have pre-signed url, currently it expires in 1 hour. How can I make sure the url is always valid url ? What is the best practice to store url for storage system in this case ? what metadata should I store besides url, if I need to re-create the url after it gets expired ? May be bucket name etc. Also how can I refresh/re-create my url after it gets expired ? -
How do i show the Model Instance in Json format?
I have successfully created Following system but i am pulling off data in Json type and i have a problem of only being able to get User instance as id,not fully. { "id": "41c44068-583d-4287-b4d5-de3cca6c47d6", "email": "johnsmith@gmail.com", "username": "johnsmith97", "password": "pbkdf2_sha256$....", "followiing": [ "10e2a143-df41-4538-92e8-8a85a5f33a24", ], }, followiing = models.ManyToManyField('User', symmetrical=False, through='FollowUserModel', related_name='followingusers', blank=True,) How can I modify my code in such a way that I can give other details like email, username etc..? -
Unable to install wagtail on MacBook pro Catalina version 10.15.7
Please help, I am unable to install wagtail on my mac: Collecting wagtail Using cached https://files.pythonhosted.org/packages/14/8f/53808ec9eed396a5945aa746304ba23062f62d9291ac523e732e7de2a243/wagtail-2.10.2-py3-none-any.whl Requirement already satisfied: django-modelcluster<6.0,>=5.0.2 in ./pioneer/lib/python3.9/site-packages (from wagtail) (5.1) Requirement already satisfied: tablib[xls,xlsx]>=0.14.0 in ./pioneer/lib/python3.9/site-packages (from wagtail) (2.0.0) Requirement already satisfied: django-taggit<2.0,>=1.0 in ./pioneer/lib/python3.9/site-packages (from wagtail) (1.3.0) Requirement already satisfied: beautifulsoup4<4.9,>=4.8 in ./pioneer/lib/python3.9/site-packages (from wagtail) (4.8.2) Requirement already satisfied: django-filter<3.0,>=2.2 in ./pioneer/lib/python3.9/site-packages (from wagtail) (2.4.0) Requirement already satisfied: django-treebeard<5.0,>=4.2.0 in ./pioneer/lib/python3.9/site-packages (from wagtail) (4.3.1) Requirement already satisfied: djangorestframework<4.0,>=3.11.1 in ./pioneer/lib/python3.9/site-packages (from wagtail) (3.12.1) Requirement already satisfied: requests<3.0,>=2.11.1 in ./pioneer/lib/python3.9/site-packages (from wagtail) (2.24.0) Requirement already satisfied: html5lib<2,>=0.999 in ./pioneer/lib/python3.9/site-packages (from wagtail) (1.1) Collecting Pillow<8.0.0,>=4.0.0 Using cached https://files.pythonhosted.org/packages/3e/02/b09732ca4b14405ff159c470a612979acfc6e8645dc32f83ea0129709f7a/Pillow-7.2.0.tar.gz Requirement already satisfied: draftjs-exporter<3.0,>=2.1.5 in ./pioneer/lib/python3.9/site-packages (from wagtail) (2.1.7) Requirement already satisfied: Unidecode<2.0,>=0.04.14 in ./pioneer/lib/python3.9/site-packages (from wagtail) (1.1.1) Requirement already satisfied: Willow<1.5,>=1.4 in ./pioneer/lib/python3.9/site-packages (from wagtail) (1.4) Requirement already satisfied: l18n>=2018.5 in ./pioneer/lib/python3.9/site-packages (from wagtail) (2018.5) Requirement already satisfied: Django<3.2,>=2.2 in ./pioneer/lib/python3.9/site-packages (from wagtail) (3.1.2) Requirement already satisfied: xlsxwriter<2.0,>=1.2.8 in ./pioneer/lib/python3.9/site-packages (from wagtail) (1.3.7) Requirement already satisfied: pytz>=2015.2 in ./pioneer/lib/python3.9/site-packages (from django-modelcluster<6.0,>=5.0.2->wagtail) (2020.1) Requirement already satisfied: xlrd; extra == "xls" in ./pioneer/lib/python3.9/site-packages (from tablib[xls,xlsx]>=0.14.0->wagtail) (1.2.0) Requirement already satisfied: xlwt; extra == "xls" in ./pioneer/lib/python3.9/site-packages (from tablib[xls,xlsx]>=0.14.0->wagtail) (1.3.0) Requirement already satisfied: openpyxl>=2.6.0; extra == "xlsx" in ./pioneer/lib/python3.9/site-packages (from tablib[xls,xlsx]>=0.14.0->wagtail) … -
adding object from non related object in django admin
in Django admin I have Image and TravelPhoto models and these are not related to each other. As well as, in both models, there are similar fields class ImageAdmin(ModelAdmin): fields = ('name', 'photo') class TravelPhotoAdmin(ModelAdmin): fields = ('photo', 'country', 'city', 'date_traveled') my question is that how can I add photo of the TravelPhoto model to the Image model in Django admin. In short Image model is a collection of default images but super users should be able to add images from another model. I do not know how to implement but if anyone knows please can you help with this problem? Thanks in advance! Any help would be appreciated! -
Is there a way to fix this error in Django?
I'm trying to learn django and when I ran the server for the first few times It worked well, but suddenly today when I ran my server it threw me these error message below can anybody help? I am currently using windows 10 and for the ide i use visual studio code. PS C:\Users\홍우진\Desktop\crm1> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\홍우진\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, … -
creat a comment with product.id and owner
I'm trying to create a comment app for users to comment their opinion for a post under t post and for creating that comment I get (product.id, owner, comment) but every time that I try to post a comment it redirects me to the login page my model: enter image description here my form: enter image description here my view: enter image description here it returns invalid -
Non-english parameter for argparse
Python 3.7.9 Ubuntu 20.04 I am extending django 3.1 management command functionality and added arguments parser to one of my commands like this: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-c', '--clients', nargs='*', help='list of clients to handle') manage.py COMMAND -h -c [CLIENTS [CLIENTS ...]], --clients [CLIENTS [CLIENTS ...]] list of clients to handle The trouble is that I when I try to pass a non-english parameter like this: manage.py download_feeds -c ЖЫВТОНЕ and handle the argument like that: def handle(self, *args, **options): if options['clients']: # parameters are specified for param in options['clients']: print(str(param)) it prints me �������������� How to handle it properly? So I can get ЖЫВТОНЕ instead of messed up characters? -
Django: "'Blogmodel' object is not iterable"
i have error 'Blogmodel' object is not iterable my view.py def blog_list(request): articles = Blogmodel.objects.all() args = {'articles':articles} return render(request,'blog.html',args) def blogDetail(request, slug): article = Blogmodel.objects.get(slug=slug) args = {'article':article} return render(request,'blogdetail.html',args) url.py path("blog/",blog_list, name="blog_list"), path("blog/<slug:slug>",blogDetail, name="blogDetail"), htmlfile {% for tt in article %} <div class="content_box"> <div class="content_l left"> <div class="horoscope_box_big"> <div class="blog_img1"> <img src="https://horoskopi.ge/storage/blog/250-ოთხი ზოდიაქოს ნიშანი ყველაზე მაღალი ხელფასებით.png" alt="ოთხი ზოდიაქოს ნიშანი ყველაზე მაღალი ხელფასებით" /> </div> <h1 class="blog_title1"><!-- სათაურის--> <div class="blog_descr1"><h1>Info</h1> <p> {{ tt.body }}</p> </div> </div> {% endfor %} when i try without for loop it's working , what is reason ? -
How can i write this filter in my views.py
Hello I have such a question about model filtering, I would like to write a filter that will allow me to display individual tournament groups assigned to a given tournament only in the tab related to that tournament. this is my models.py class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) def __str__(self): return self.tournament_name class TournamentGroup(models.Model): group_name = models.CharField(max_length=256, null=True) tournament_name = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) def __str__(self): return self.group_name class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) user_group = models.ForeignKey(TournamentGroup, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name and this is my views.py file def content(request, pk): tournament = get_object_or_404(Tournament, pk=pk) tournament_groups = TournamentGroup.objects.filter(tournament_name=tournament) users = TournamentUsers.objects.filter(user_tournament=tournament) form = TournamentUsersForm() if request.method == "POST": form = TournamentUsersForm(request.POST) if form.is_valid(): form.save() form = TournamentUsersForm() return render(request, 'ksm_app2/content.html', {'tournament': tournament, 'users': users, 'form': form, 'tournament_groups': tournament_groups}) The user filter works correctly after he has chosen the right tournament but I have a problem with the team, I will appreciate any hint -
Show products in the chart
I created a price chart for the products, but when my products have a variety of colors or sizes, the price changes for each product are not separated, but displayed in general, but I want price changes for each color Be displayed separately. my chart model: class Chart(models.Model): name = models.CharField(max_length=100, blank=True, null=True) create = jmodels.jDateTimeField(blank=True, null=True) update = jmodels.jDateTimeField(blank=True, null=True) unit_price = models.PositiveIntegerField(default=0, blank=True, null=True) color = models.CharField(max_length=100, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='pr_update') variant = models.ForeignKey(Variants, on_delete=models.CASCADE, related_name='v_update') my variant model: class Variants(models.Model): name = models.CharField(max_length=100, blank=True, null=True) color = models.ForeignKey(Color, on_delete=models.CASCADE, blank=True, null=True) size = models.ForeignKey(Size, on_delete=models.CASCADE, blank=True, null=True) change = models.BooleanField(default=True) .... my view : def details(request, id): change = Chart.objects.filter(variant__change=True) .... my template : <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for product in change %}'{{product.color }}' , {% endfor %}], datasets: [{ label: 'price', data: [{% for product in change %} {{product.unit_price}},{% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, …