Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tail a log in a django page
I would like to add a page in my django server which actively tail -f a log file (or update the page every few seconds). What is the best way to go about doing that. Does django provide any functionality to view a page actively? Any thoughts or pointers is really appreciated. -
How do I join three tables that are not all linked by foreign keys?
I want to join three tables without using raw sql. Two of the tables do not have Foreign key relationships: ``` SELECT table1.col1, table1.col2, table2.col3, table3.* FROM table3 JOIN table1 on table3.x_id = table1.x_id JOIN table2 on table2.x_id = table1.x_id WHERE <conditions> ``` So far I have not been able to use the Django ORM to do this. The closest I've come is .values() but since not all of the tables have direct foreign key links, the lookup fails. How can I do this using only the Django ORM? NOTE: I'm aware that the way I've explained this, obfuscated table names/columns and all might be difficult to understand. Please bear with me, I've been trying to solve this issue for the better part of 2 hours. -
How do I auto increment my results in a page?
I made this table but I can't figure out how to do the numbering. I want a top 10 list and I get all the data from a database. I essentially want to make it show '1' and the next '2' and the next '3' and so forth. How would I able to do this? https://imgur.com/a/9Isf941 def home(request): straatData = data.objects.all()[:10] count = data.objects.count() numbers = [] for dataCount in range(1, count + 1): numbers.append(dataCount) context = { 'data': straatData, 'count': numbers, } return render(request, 'home.html', context) I need to get the top numbers to show 1,2,3,4... as many as the results. But I don't know how to do it -
DynamoDB with Boto3 - ResourceNotFoundException during table.scan()
I'm using DynamoDB to make a Room Booking Website on Django. Every time I refresh the page, the console throws me a ResourceNotFoundException - Requested resource not found, which seems to be happening when I use table.scan(). On certain pages the table still loads, but on others' I'm shown a debug error. Here's a part of my code: dynamodb = boto3.resource( 'dynamodb', aws_access_key_id="XXXXXX", aws_secret_access_key="XXXXXX", region_name="eu-west-2" ) table = dynamodb.Table(table_name) response = table.scan(TableName=table_name) I'm entirely sure that the table_name value contains the correct string. What could be the problem? -
Migrating django database from sqlite to postgres error with psycopg2
I am trying to switch my django database from sqlite to postgres on my local machine. I am getting the following error when I try to run python manage.py migrate File "/Users/omarjandali/anaconda3/envs/splittapp/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' Now I did make changes to the settings.py file in order to switch it from the sqlite3 database to the postgres database. My code looks like this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'splitt', 'USER': 'splittadmin', 'PASSWORD': '*****', 'HOST': 'localhost', 'PORT': '5432', } } This is is what the databse looks like insode of the postgres shell splitt | splittadmin | UTF8 | en_US.UTF-8 | en_US.UTF-8 | I was also looking up how to grand all rpivileges of a database to a superuser and I was getting mixed results. -
the form does not save all the data in the database
I'm using the system for email confirmation, and it's working. But at the time of crashing in the database it only saves SEXO_CHOICES and STATE_CHOICES and if the email is confirmed or not, the rest simply does not save, but I still receive the confirmation email I need the data to be saved inside the database all of them model.py from django.db import models from django.core.files.images import ImageFile from django.core.mail import send_mail import math from multiselectfield import MultiSelectField from django.core.validators import RegexValidator from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver STATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins') ) PET_CHOICES = ( ('dog','Cachorro'), ('cat','Gato'), ('bird', 'Pássaros'), ('fish','Peixes'), ('rep','Reptéis'), ('horse','Cavalos'), ('rat','Roedores') ) SEXO_CHOICES = ( ('M','Masculino'), ('F','Feminino') ) class Usuario(models.Model): nome = models.CharField(max_length=50, blank=False) sobrenome = models.CharField(max_length=50, blank=False) user = models.OneToOneField(User, … -
Conflict between php and django with apache sites-available
I have a vps ubuntu 16, in which I have a web page in Wordpress and one in Django, I decided to update my server using the following command: sudo apt-get update && sudo apt-get upgrade After the update the website in Django stopped working and presents the following message: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at support@javiercb.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache / 2.4.37 (Ubuntu) Server at phraster.com Port 80 And in the log file it presents the following message: [Tue Jan 29 22: 41: 55.852599 2019] [wsgi: error] [pid 11606] [client 181.199.43.182:53977] Truncated or oversized response headers received from daemon process 'phraster': /var/www/phraster/javiercb/apache.conf/web.wsgi, referer: http://phraster.com/ I attach the two files of apache.conf Due to this problem I bought another vps and unfortunately the probleme you got. #Apache <virtualhost *:80> ServerName phraster.com ServerAlias www.phraster.com serverAdmin soporte@javiercb.com ServerSignature On ErrorLog /var/log/apache2/phraster.com_error.log LogLevel warn CustomLog /var/log/apache2/phraster.com_access.log combined DocumentRoot /var/www/phraster/javiercb <Directory /var/www/phraster/javiercb> Order allow,deny Allow from all </Directory> … -
Where do I need to place my Django tests so that they get executed?
I'm using Django and Python 3.7. I would like to create and run some unit tests. Per the Django documentation, I created this file ... ls ./mainpage/tests/test_models.py But when I run my tests using the command below, it says zero tests were executed ... (venv) localhost:mainpage_project davea$ cd /Users/davea/Documents/workspace/mainpage_project; source ./venv/bin/activate; python manage.py test Creating test database for alias 'default'... /Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py:1421: RuntimeWarning: DateTimeField Article.main_page_first_appeared_date received a naive datetime (2019-01-29 22:43:53.575128) while time zone support is active. RuntimeWarning) System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Destroying test database for alias 'default'... Below are the contents of my file. What am I missing? Where should I put my tests or how should they be named so that they get executed? from django.test import TestCase from mainpage.models import ArticleStat, Article class TestModels(unittest.TestCase): # Test saving an article stat that hasn't previously # existed def test_add_articlestat(self): id = 1 article = Article.objects.filter(id=id) self.assertTrue(article, "A pre-condition of this test is that an article exist with id=" + str(id)) articlestat = ArticleStat(article=article,elapsed_time_in_seconds=250,votes=25,comments=15) articlestat.save() article_stat = ArticleStat.objects.get(article=article) self.assertTrue(article_stat, "Failed to svae article stat properly.") -
How do I preserve data in Django templates on a drop-down menu?
I am trying to preserve form data on a registration template on a Django project. I am using ginger statements such as {{ old_data.[data] }}. I have no problem doing it with regular text input (like this): <div class="form-group"> <input type="text" name="zip_code" id="zip_code" class="form-control input-sm" placeholder="Zip" value="{{ old_data.zip_code }}"> </div> And with textarea (like so): <textarea type="area" name="area" id="area" class="form-control textarea" rows="3" placeholder="Please tell us briefly in what part of town you live and how far you are willing to travel for rehearsals and performances. i.e., 'I live in the Heights but I'm willing to drive anywhere within the loop.'">{{ old_data.area }} </textarea> But I cannot figure out how to do it with a drop-down menu. Here is my current code: <select class="form-control" name="primary_instrument" id="primary_instrument" placeholder="Primary instrument" value="{{ old_data.primary_instrument }}"> <option selected disabled>Primary instrument</option> {% for instrument in instruments %} <option value='{{ instrument.id }}'>{{ instrument }}</option {% endfor %} </select> Please help! -
how to build Web app using Python and html?
So I am new to coding. I am interested in Python3 and Html5 and CSS3. I have a little knowledge about each one. The question is: how do I build a website from scratch using Python3 (django?) as backend and html5 and css3 as frontend? What about js? nodejs? Can anyone help me and give me DETAILED answer? I would be grateful for a clear detailed answer. thank you. -
How do I reference my settings file from running my unit tests?
I'm using Django and Python 3.7. I have different database configurations per environment, so I wanted to create settings that only import the database config depending on the environment. I have this directory ... mainpage_project/settings and within it are these files. "base.py" contains settings that I wish to be included regardless of the environment taht is loaded ... (venv) localhost:mainpage_project davea$ ls mainpage_project/settings __pycache__ base.py dev.py prod.py test.py I have this in my mainpage_project/settings/test.py file ... from mainpage.base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'testdatabase' }, } But when I go to run my test file, I get the error complaining that it cannot execute the first line of the import, "from mainpage.base import *" ... (venv) localhost:mainpage_project davea$ cd /Users/davea/Documents/workspace/mainpage_project; source ./venv/bin/activate; python manage.py test Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv super().run_from_argv(argv) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 308, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 282, in create_parser self.add_arguments(parser) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 47, in add_arguments test_runner_class = get_runner(settings, self.test_runner) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/test/utils.py", line 301, in get_runner test_runner_class = test_runner_class or … -
Why does my application break when I try to use corsheaders?
I have a client with a django web application which pulls information from a different web application and displays it on a web page. The web application suddenly stopped working and the following message appeared in the server's supervisorctl: https://imgur.com/oKz6rTJ I didn't have much time, so I traced the error to the CorsHeaders middleware and commented it out from the website's settings.py while I work on a long term solution. To save people time researching, Cors is a middleware which allows web browsers to access your server even if it is in a different domain than the web page. (aka what the client uses to upload their data from one webapp to another) This image outlines what I commented out: https://imgur.com/a/tEBiYGU As mentioned, commenting out that middleware prevented it from loading any new data but the current graphs had no issues being displayed. This confirmed my suspicion that corsheaders was the sole problem. Now I had a bit more time to research the issue at home and realized that the crux of the issue is the fact that the middleware is what calls on the apps import: https://imgur.com/a/0812jFJ Now I will admit that while I have some python experience, I … -
Find Django model records that have more than one 'child' objects?
If I have two models in Django, Parent and Child, where Child has a foreign key relationship to Parent like this: class Parent(models.Model): parent_name = models.CharField(max_length=128, blank=False, default='no name') class Child(models.Model): child_name = models.CharField(max_length=128, blank=False, default='no name') parent = models.ForeignKey('app.Parent', on_delete=models.CASCADE, null=False) How can I find all instances of Parent records that at least two Child records? Ideally, the solution would use a single .filter() statement on Parent. -
Django UpdateView not validating new data
I'm using a CustomUserChangeForm and UpdateView to update my project users data. But for some reason it is not validating the new data (as to check for a username already being used), but the CustomUserCreationForm and CreateView do the validation fine. In my forms.py class CustomUserChangeForm(UserChangeForm): password = None class Meta: model = CustomUser fields = ('username', 'email', 'first_name', 'last_name') In my views.py class PerfilEdit(generic.UpdateView): model = CustomUser form_class = CustomUserChangeForm success_url = reverse_lazy('users:perfil') def get_object(self, queryset=None): return self.model.objects.get(pk=self.request.user.pk) Is there anyway to add a verification to this form? If any extra info is needed just say that I will add it to this post. -
Django add authentication to download
I'm trying to add authentication to a download i'm serving users. Without authentication I can download my file, but as soon as I add some kind of authentication, it seems like it doesn't actually run my if statement? def download_item(request, pk): item = get_object_or_404(Usertasks, pk=pk) output_path = item.OutputPath response = HttpResponse() print(request.user) if not request.user == item.user: return redirect('/account/login/') if request.user == item.user: response = HttpResponse() response['Content-Type']="" response['X-Accel-Redirect'] = output_path If I try to download the file, then it just redirects me to the login page. I added the print function to verificate that the correct user is actually trying to acces the file. My terminal will print out admin and my database value is also admin , so why is it redirecting me to my login page? -
int() argument must be a string, a bytes-like object or a number, not 'set'
I am not able to set up an ArrayReferenceField in Django using Djongo as the Engine. I am trying to build a Database which stores Projects of a student with the skills related to build that Project using ArrayReferenceField. The Form is generated through the Admin Page but in clicking save the following error is generated TypeError: int() argument must be a string, a bytes-like object or a number, not 'set' I looked into similar questions and none of them were able to answer my question. I even tried using ManyToManyField instead of it and it gives the same error.Can somebody help me with It. Thanks in advance. myapp/models.py enter code here class Skill(models.Model): id = models.AutoField(primary_key = True) skills = models.CharField(max_length = 30) class UserCredential(models.Model): first_name = models.CharField(max_length = 25) last_name = models.CharField(max_length = 25) email = models.EmailField() username = models.CharField(max_length = 50, unique = True) password = models.CharField(max_length = 25) skills = models.ArrayReferenceField(to=Skill , on_delete=models.CASCADE) class Project(models.Model): title = models.CharField(max_length = 100) user = models.ForeignKey(to=UserCredential , on_delete=models.CASCADE) description = models.TextField() req_skills = models.ArrayReferenceField(to=Skill , on_delete=models.CASCADE) myapp/serializers.py class ProjectSerializer(serializers.ModelSerializer): model = Project fields = "__all__" class Meta: ordering = ["title"] class SkillSerializer(serializers.ModelSerializer): model = Skill fields = ('skills',) Entire … -
SonarQube - Is there basic example/explanation of how coverage issues can be resolved?
I'm very new to using SonarQube/Cloud (so please be gentle!) and am trying to work out how to improve the '0% coverage on new code' that my code has. Here's an example: I added the code: validation_errors = [] for field in required: if field not in request.POST: validation_errors.append("field '{0}' missing".format(field)) if len(validation_errors) > 0: return JsonResponse({'errors': validation_errors}, status=400 ) and I have a (Django) test for this: def test_required_params(self): # no username response = self.client.post(self.url, { 'password': 'secret', 'media_file': self.video_file }) self.assertRaises(forms.ValidationError) self.assertEqual(response.status_code, 400) But when I run the sonar-scanner, in the online report, I get the message that these lines are not covered (see: https://sonarcloud.io/component_measures?id=django_oppia&metric=new_coverage&selected=django_oppia%3Aapi%2Fmedia.py) I'm sure I must have some very basic mis/non-understanding of what the coverage metric actually means. I'd really appreciate if someone could explain to me what I need to add/update in my code (just the specific example above), so the SonarCloud analysis doesn't continue to flag this as not covered. Thanks for your help - if you need any extra info on code/platform/versions etc, just let me know. -
Images fail to load in production Django site with Amazon S3
When working locally, all of the images on my site load perfectly. But in production when using Amazon S3, only some of the images work. Images put into an HTML file like this work both locally and in production: <img class="animal" src="/static/images/animals/cat.png" alt="Cat"> But background-images where the url is only in the CSS attached to a class in the HTML only work locally. When I inspect element on the background in production, and hover over the background-image url, it says "Could not load image." Clicking on the link takes me to an error message that looks like this: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>212121212</RequestId> <HostId>asdasdasdasd</HostId> </Error> The link to the actual image itself looks like this: https://mybucket.s3.amazonaws.com/static/images/animals/cat.1a1a1a1a.png?2b2b2b2b If I remove the 1a1a1a1a part before the .png, the picture loads. If I make any other changes to the css file, like changing background colors, that all works locally and in production. It's just these pictures that won't load in production. The images folder in my S3 bucket is set to public. I also went through a tutorial to set up CouldFront and … -
Django: how to build an endswith filter
I need to render image adobe_illustrator_file_logo.png if file.url ends with .ai. But if file.url ends with other termination like .png for exmaple I'll render the image of the object. I've searching documentation but apparently there is not a endswith built in filter. So I ended up playing with ifequals and slice filter. Logically it is the same: "if string is identical to the last 3 letters do this". However, it is not working, as nothing gets displayed. <td> {% ifequal cart_item.file.url|default:""|slice:"-3" ".ai" %} <img src="{% static 'img/admin/adobe_illustrator_file_logo.png' %}" alt="" class="float-left rounded custom_image"> {% endifequal %} </td> Note: <p>{{ cart_item.file.url }}</p> renders: <p>/media/files/working_precisely.ai</p> -
Create foreign fields TextInput using modelforms in django
I am creating user profiles in which Profile have OnetoMany relationship with Work_experience. I have tried {{ form.experience.job_title }} but it didn't work. How do I access Work_Experience fields and render them as TextInput? Django version: 2.0 Models class Work_Experience(models.Model): job_title = models.CharField(max_length=100, null=True, blank=True) company = models.CharField(max_length=100, null=True, blank=True) description = models.CharField(max_length=300, null=True, blank=True) exp_start_date = models.DateField(null=True, blank=True) exp_end_date = models.DateField(null=True, blank=True) class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) full_name = models.CharField(max_length=30, null=True, blank=True) experience = models.ForeignKey(Work_Experience, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.user.username) Template <div class="field"> <label>Job title<span class="red-txt">*</span></label> {{ form.experience }} </div> Form class ProfileSettingsForm(forms.ModelForm): class Meta: model = Profile fields = ['full_name','experience'] widgets = { 'full_name' : forms.TextInput({'class': 'form-control'}), 'experience' : forms.TextInput({'class':'form-control'}) } -
Django user groups in template tag with single database hit
How do I avoid multiple database calls in a template for a user's group(s). I can't rely on the default user in the template, as it does not (or I dont know how to) add the prefetch_related to get the user's group. So I add to the view: user = User.objects.all().select_related( ).prefetch_related( 'groups', ).get(pk=request.user.pk) In the template, if I want to check if a user is part of a group, I would do something like: {% if user|has_group:"Mechanic" %} and make a template tag (I've tried multiple types, but ultimately the template tag is not cached, and therefore will always hit the db again, even if it is using the user and its prefetch_related attributes) @register.filter(name='has_group') def has_group(user, group_name): lis = list(user.groups.all().values_list('name', flat=True)) grp = get_object_or_404(Group, name=group_name) if grp in lis: return True else: return False If I pass all group objects to the template, I can avoid calls by checking the group type against the user model's prefetch_related attributes, but now I have to pass every view I want to check this in every group model individually in the view mechGroup = Group.objects.all().filter(name='Mechanic') in the template {% if mechGroup in user.groups.all %} Is there a better/simpler way to do … -
Heroku migrate causes: (staticfiles.E001) The STATICFILES_DIRS setting is not a tuple or list
(first time post, so forgive me if this turns out sloppy...) Trying to migrate the database from my computer to heroku to run my app online. using: $ heroku run python manage.py migrate This returns: ?: (staticfiles.E001) The STATICFILES_DIRS setting is not a tuple or list. HINT: Perhaps you forgot a trailing comma? My '#static asset configuration' in settings.py is as follows: BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Based on searches, I've tried to turn this into a list with square brackets, adding a comma after the second ')', and a few other attempts. This is the second app I am creating from the same guide (python crash course). The app from the book is working. The one I created for myself as additional practice is the one running into this issue but the coding displayed above is identical between the two. I am not sure where else to look at this point. Any and all assistance would be infinitely appreciated. -
Django - TypeError at /statements/ int() argument must be a string, a bytes-like object or a number, not 'AnonymousUser'
In my Django project, I have a statement app which just stores the statements of the registered users. I was experimenting with it to learn Django and at some point, I asked myself how to show only the statements of the current user. So, I filtered the queryset based on the current user and then I have got this error message, when I wanted to see the statements. My views.py: from statements.models import Statement from statements.serializers import StatementSerializer, UserSerializer from rest_framework import generics from django.contrib.auth.models import User from rest_framework import permissions from statements.permissions import IsOwnerOrReadOnly from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.views import APIView from rest_framework.authtoken.models import Token from rest_framework.authentication import TokenAuthentication @api_view(['GET']) def api_root(request, format=None): return Response({'links':{ 'users': reverse('user-list', request=request, format=format), 'statements': reverse('statement-list', request=request, format=format) }}) class StatementList(generics.ListCreateAPIView): #queryset = Statement.objects.all() <--- with this, everything was fine but I wanted to get only the statements of the current user serializer_class = StatementSerializer authentication_classes = (TokenAuthentication,) permission_classes = (permissions.IsAuthenticatedOrReadOnly,) # I've overridden this method so that only the statements of the current user should be displayed (BUT this caused the error) def get_queryset(self): user = self.request.user return Statement.objects.filter(owner=user) def … -
How to use a atribbute of a object Many To Many in Django?
Hei, I'm sorry for the confuse question (I couldn't to write this better). I'm using Django 2.1 I've got these 2 models with a ManyToMany relationship: class Ingrediente(models.Model): produtor = models.ForeignKey('auth.User', on_delete=models.CASCADE, default=10) nome = models.CharField(max_length=200) descricao = models.TextField() quantidade = models.DecimalField(max_digits=10, decimal_places=3) custo = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.nome e class Produto(models.Model): nome = models.CharField(max_length=200) descricao = models.TextField() ingredientes = models.ManyToManyField(Ingrediente) utilitarios = models.ManyToManyField(OutrosCustos) def __str__(self): return self.nome I use the this view to return a list with all objects of Class Produto: def produtos_list(request): produtos = Produto.objects.filter() return render(request, 'egg_app/produtos_list.html', {'produtos':produtos}) And in my template I write this: <table class="table"> <thead> <tr> <th scope="col">Nº Produto</th> <th scope="col">Nome</th> <th scope="col">Ingredientes</th> <th scope="col">Custo</th> </tr> </thead> <tbody> {% for p in produtos %} <tr> <th scope="row">{{ p.pk }}</th> <td>{{ p.nome }}</td> <td>{{ p.ingredientes }}</td> <td>custo teste</td> </tr> {% endfor %} </tbody> But my result in the collum "Ingredientes" has been egg_app.Ingrediente.None and not the name of the Ingrediente of the relationship (between Ingrediente and Produto). In my django admin page, I associate this, so I'm sure about the relationship. -
How to remove duplicates from a chained queryset in Django?
I have 3 queries that I have chained together like so in a view: filter1 = Game.objects.filter(genres__name=str('2D')) filter2 = Game.objects.filter(genres__name=str('Action')) filter3 = Game.objects.filter(genres__name=str('Sports')) return chain(filter1, filter2, filter3) I want all games that are genre 2D, Action and Sports but not games that are all 3 at once, just every game that matches each genre (i.e. not a 2D action sports game), but when I use this queryset in a loop in my template, I receive duplicate games if they are both 2D and Action, for example. I have tried using distinct() on the chained queryset, however I get a warning saying Unresolved attribute reference 'distinct' for class 'chain'. Is there some sort of thing I can do on the template which keeps track of which games have already been looped through and build a list of them, so that if the same game comes up after the first queryset has been cycled through, it will miss the duplicate game out? E.g. for game in queryset: if game.id is in game_id_list: Dont display else: Display and add to game_id_list