Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS Elastic Beanstalk + Django: environment set up crashes
I'm trying to deploy Django project with Elastic Beanstalk, but can't create environment cause it crashes at the phase of installing dependencies (packages) from requirements.txt. My commands: eb init -p python-3.6 app eb create env-test Logs: ------------------------------------- /var/log/eb-activity.log ------------------------------------- inflating: /opt/python/ondeck/app/frontend/templates/frontend/base.html inflating: /opt/python/ondeck/app/frontend/templates/frontend/list.html inflating: /opt/python/ondeck/app/frontend/templates/frontend/login.html inflating: /opt/python/ondeck/app/frontend/templates/frontend/registration.html inflating: /opt/python/ondeck/app/frontend/tests.py inflating: /opt/python/ondeck/app/frontend/urls.py inflating: /opt/python/ondeck/app/frontend/views.py inflating: /opt/python/ondeck/app/manage.py inflating: /opt/python/ondeck/app/requirements.txt creating: /opt/python/ondeck/app/todo/ extracting: /opt/python/ondeck/app/todo/__init__.py inflating: /opt/python/ondeck/app/todo/asgi.py inflating: /opt/python/ondeck/app/todo/settings.py inflating: /opt/python/ondeck/app/todo/urls.py inflating: /opt/python/ondeck/app/todo/wsgi.py [2021-01-28T14:16:47.373Z] INFO [2647] - [Application deployment app-68c0-210128_161500@1/StartupStage0/AppDeployPreHook/03deploy.py] : Starting activity... [2021-01-28T14:16:51.915Z] INFO [2647] - [Application deployment app-68c0-210128_161500@1/StartupStage0/AppDeployPreHook/03deploy.py] : Activity execution failed, because: Collecting asgiref==3.3.1 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/89/49/5531992efc62f9c6d08a7199dc31176c8c60f7b2548c6ef245f96f29d0d9/asgiref-3.3.1-py3-none-any.whl Collecting certifi==2020.12.5 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/5e/a0/5f06e1e1d463903cf0c0eebeb751791119ed7a4b3737fdc9a77f1cdfb51f/certifi-2020.12.5-py2.py3-none-any.whl (147kB) Collecting cffi==1.14.4 (from -r /opt/python/ondeck/app/requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/1c/1a/90fa7e7ee05d91d0339ef264bd8c008f57292aba4a91ec512a0bbb379d1d/cffi-1.14.4-cp36-cp36m-manylinux1_x86_64.whl (401kB) Collecting chardet==4.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/19/c7/fa589626997dd07bd87d9269342ccb74b1720384a4d739a1872bd84fbe68/chardet-4.0.0-py2.py3-none-any.whl (178kB) Collecting coreapi==2.3.3 (from -r /opt/python/ondeck/app/requirements.txt (line 5)) Downloading https://files.pythonhosted.org/packages/fc/3a/9dedaad22962770edd334222f2b3c3e7ad5e1c8cab1d6a7992c30329e2e5/coreapi-2.3.3-py2.py3-none-any.whl Collecting coreschema==0.0.4 (from -r /opt/python/ondeck/app/requirements.txt (line 6)) Downloading https://files.pythonhosted.org/packages/93/08/1d105a70104e078718421e6c555b8b293259e7fc92f7e9a04869947f198f/coreschema-0.0.4.tar.gz Collecting cryptography==3.3.1 (from -r /opt/python/ondeck/app/requirements.txt (line 7)) Downloading https://files.pythonhosted.org/packages/7c/b6/1f3dd48a22fcd56f19e6cfa95f74ff0a64b046306354e1bd2b936b7c9ab4/cryptography-3.3.1-cp36-abi3-manylinux1_x86_64.whl (2.7MB) Collecting defusedxml==0.7.0rc2 (from -r /opt/python/ondeck/app/requirements.txt (line 8)) Downloading https://files.pythonhosted.org/packages/30/b7/84b057e7437171d18c742d762cd42f44430624ddb459c9c02ab80295460d/defusedxml-0.7.0rc2-py2.py3-none-any.whl Collecting Django==3.1.5 (from -r /opt/python/ondeck/app/requirements.txt (line 9)) Downloading https://files.pythonhosted.org/packages/b2/8f/d27f35f0639103271231bc81a96ad9188e6b5bc878e140ccb0dc610ccef0/Django-3.1.5-py3-none-any.whl (7.8MB) Collecting django-templated-mail==1.1.1 (from -r /opt/python/ondeck/app/requirements.txt (line 10)) Downloading https://files.pythonhosted.org/packages/f3/ec/0f42b730e17ca087aa79a7aadecff7957a867709f04bd0354e72120e9f68/django_templated_mail-1.1.1-py3-none-any.whl Collecting djangorestframework==3.12.2 (from -r /opt/python/ondeck/app/requirements.txt (line 11)) Downloading https://files.pythonhosted.org/packages/8e/42/4cd19938181a912150e55835109b1933be26b776f3d4fb186491968dc41d/djangorestframework-3.12.2-py3-none-any.whl (957kB) Collecting djangorestframework-simplejwt==4.6.0 (from -r … -
is there any sense in select_for_update when using transaction.atomic?
@transaction.atomic() def some_function(): MyModelOne.objects.filter(name="Name").select_for_update().update(status='active') MyModelOne.objects.filter(code="abc").select_for_update().update(status='inactive') Is there any sense in code above? Or just transaction.atomic() is enough? -
how can i get a shipping cost of ordered items in an e-commerce website
i am working on an e-commerce website with django and i want to include the shipping cost in the checkout page. is there a way to calculate the shipping cost with django or javascript? -
How do i go about transferring my host server from Digital Oceans to Python Anywhere
I recently heard of Python Anywhere and i suddenly feel in love with how they offer their services. So now i've previously hosted this my django website with Digital Ocean but now i want to host it now on Python Anywhere. Please how do i go about it, i'm confused here. I've surfed the entire net for tutorials about it but no solutions was provided. -
choices value of select in an inline form in admin django
please I want to select the list of cycles by Program_de_bourse, know that in my actual form I can select all the cycles , but I just want to select the cycles linked to Program_de_bourse my foreign key Program_de_bourse = id of Program_de_bourse the model.py class Cycle(models.Model): Programme_de_bourse = models.ForeignKey(Programme_de_bourse, on_delete=models.SET_NULL, null=True) Objet_programme = models.CharField( max_length=30, choices=objet_CHOICES, verbose_name='Cycle' ) def __str__(self): return self.Objet_programme .. class Discipline(models.Model): Discipline = models.ForeignKey(Disc, on_delete=models.CASCADE, related_name='Discipline_cycle') Cycle = models.ForeignKey(Cycle, on_delete=models.SET_NULL, null=True) Programme_de_bourse = models.ForeignKey(Programme_de_bourse, on_delete=models.SET_NULL, null=True, related_name='Programme_de_bourse_id') def __str__(self): return str(self.Discipline) my admin.py class Programme_de_bourseAdmin(ExportActionMixin, admin.ModelAdmin): fieldsets = [ ('Programme', {'fields': ['Programme']}), #'classes': ['collapse'] # ] list_display = ["Programme",] inlines = [CycleInline, DisciplineInline, ConditionInline, EtablissementInline, DocumentInline] class DisciplineInline(ExportActionMixin, admin.TabularInline): ) model = Discipline enter image description here -
Which data has changed when editing a model instance in the admin site
Django 3.1.5 When in the admin site an instance of a model is edited, is there any way to find out which data has changed? -
Django Factory for model with Generic Foreign Key
I'm trying to write up a Factory for a model with a GFK for testing but I can't seem to get it working. I've referred to the common recipes in the docs, but my models don't match up exactly, and I'm also running into an error. Here are my models class Artwork(models.Model): ... region = models.ForeignKey("Region", on_delete=models.SET_NULL, null=True, blank=True) class Region(models.Model): # Could be either BeaconRegion or SpaceRegion region_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) region_object_id = models.PositiveIntegerField() region = GenericForeignKey("region_content_type", "region_object_id") class SpaceRegion(models.Model): label = models.CharField(max_length=255) regions = GenericRelation( Region, content_type_field="region_content_type", object_id_field="region_object_id", related_query_name="space_region", ) class BeaconRegion(models.Model): label = models.CharField(max_length=255) regions = GenericRelation( Region, content_type_field="region_content_type", object_id_field="region_object_id", related_query_name="beacon_region", ) Essentially, an Artwork can be placed in one of two Regions; a SpaceRegion or BeaconRegion. I've created the following Factorys for the corresponding models class RegionFactory(factory.django.DjangoModelFactory): region_object_id = factory.SelfAttribute("region.id") region_content_type = factory.LazyAttribute( lambda o: ContentType.objects.get_for_model(o.region) ) class Meta: exclude = ["region"] abstract = True class BeaconRegionFactory(RegionFactory): label = factory.Faker("sentence", nb_words=2) region = factory.SubFactory(RegionFactory) class Meta: model = Region class SpaceRegionFactory(RegionFactory): label = factory.Faker("sentence", nb_words=2) region = factory.SubFactory(RegionFactory) class Meta: model = Region class ArtworkFactory(factory.django.DjangoModelFactory): ... region = factory.SubFactory(SpaceRegionFactory) In my test, I try to create an Artwork using ArtworkFactory(), but it errors with AttributeError: The … -
django-libsass installation failed: error: command 'gcc' failed with exit status 1
I want to use SCSS in my Django project running with Docker in order to customize bootstrap But django-libsass 0.7 failed when build container (see traces below) whereas it did not failed when I install it locally in env seems to be comand gcc that failed I've read in forum that could be related to python-dev not installed but as you can see in my Dockerfile, it is as well as gcc FROM python:3.8.3-alpine # Set a work directory WORKDIR /usr/src/app # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl postgresql-dev postgresql-client RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev nano RUN pip3 install psycopg2 psycopg2-binary httpie django-cors-headers # install xgettext for i18n RUN apk add gettext # Install dependencies COPY requirements/ requirements/ RUN pip install --upgrade pip && pip install -r requirements/dev.txt # Copy the entrypoint.sh file COPY entrypoint.dev.sh . # Copy the project's files COPY . . RUN chmod +x entrypoint.dev.sh # Run entrypoint.sh ENTRYPOINT [ "/usr/src/app/entrypoint.dev.sh" ]``` ERROR: Command errored out with exit status 1: command: /usr/local/bin/python … -
iframe not displaying pdf page
Trying to load pdf in iframe. src is set to url received from database. <div class="row"> <div class="col-md-8"> <iframe runat="server" src="{{quotation.quotationFile.url}}" width="100%" height="500px"> </iframe> </div> </div> trying to load iframe with src received from database. but not displaying This content can’t be shown in a frame There is supposed to be some content here, but the publisher doesn’t allow it to be displayed in a frame. This is to help protect the security of any information you might enter into this site. -
Is database normalized?
I'm working on project in Django. I'm using SQLite databse. I found it very confusing to determine if my database is nomralized or not. App is about Formula One, users can make predictions about next race podium- table Ranking is in OneToOne relation with User. Every prediction belongs to one Ranking Table. Tables Driver and Team contains information about drivers and constructors whichc are currently in sport. Schedule is calendar for current season. Result table contains information about driver, race and points and position he finished in that race. HistoricResult contains same information but for races and drivers from past seasons, so data is stored as Chars and Integers instead of ForeignKeys. Table Season contains only year in which season was. Thanks for having look! -
How to mock a function in the signal Django?
Writing test cases for testing signal . When I save any model a signal is triggered @receiver(pre_save) def pre_save_handler(sender,instance): txn = get_txn() ins._state.operation = instance._state.adding Now I writing test cases for the same. I need to mock get_txn() to return (1,1,1,1) in above signal when following test case is triggered: def test_signal(self): TestPerson.objects.create("first_name"="name","last_name"="name") -
How to show multi-select input in Django Admin in a M2M through table
I have an Active Location Model class ActiveLocation(models.Model): name = models.CharField(max_length=512, blank=False, null=False) description = models.CharField(max_length=512, blank=True) created_at = models.DateTimeField(auto_now_add=True) last_modified_at = models.DateTimeField(auto_now=True) and a Seller Model with a M2M on the active location via a through table class Seller(models.Model): first_name = models.CharField(max_length=256, blank=True) localities_serviced = models.ManyToManyField( ActiveLocation, through='SellerActiveLocality', blank=True, related_name='%(app_label)s_%(class)s_seller_localities_serviced' ) created_at = models.DateTimeField(auto_now_add=True) last_modified_at = models.DateTimeField(auto_now=True) and this is what the SellerActiveLocality looks like: class SellerActiveLocality(models.Model): seller_id = models.ForeignKey(Seller, on_delete=models.PROTECT, blank=False, null=False) active_location_id = models.ForeignKey(ActiveLocation, on_delete=models.PROTECT, blank=False, null=False) meal_type = models.CharField( max_length=128, choices=meal_type_choices, blank=False, null=False, ) When I go to create a new row in the through table, I see this: My question is how do I convert the Active Location Id field from a drop-down to a multi-select field which Django shows by default when it's a M2M field without a through table rather than a drop down like it's showing right now? -
Django OneToOneField vs ForeignKey&Unique
I have a model in Django with the following classes (among others): class Product(models.Model): product = models.CharField(primary_key=True, max_length=50) class Meta: db_table = 'products' class Discipline(models.Model): discipline = models.CharField(primary_key=True, max_length=100) class Meta: db_table = 'disciplines' class Project(models.Model): project_name = models.CharField(primary_key=True, max_length=100) last_update = models.DateField() comments = models.CharField(max_length=150, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) main_discipline = models.ForeignKey(Discipline, on_delete=mode class ProjectDiscipline(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE, db_column='project_name') discipline = models.ForeignKey(Discipline, primary_key=True, on_delete=models.CASCADE, db_column='discipline') class Meta: db_table = 'projects_disciplines' unique_together = (('project_name', 'discipline'),) verbose_name_plural = 'Projects Disciplines' The trouble comes when I run the server and I find this message (it works but raises a Hint): planning.ProjectDiscipline.discipline: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. The ProjectDiscipline class gathers several disciplines for the same project, and therefore the primary key should be a compound one. I thought this could be done by setting "unique_together" with both "project_name" and "discipline" fields. But it tells me to use the OneToOneField. So... How should it be done? Should I set both fields (project_name and discipline) as OneToOneField linked to the models Project and Discipline respectively, and also keep the unique_together? Or is there … -
Django rest framework, do serializer require fields to be specified?
Let's say we have model: class CompanySource(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='company_source') source = models.CharField(max_length=1500) and we want to have seralizer for it and we use HyperlinkedModelSerializer it looks like this class CompanySourceSerializer(serializers.HyperlinkedModelSerializer): def create(self, validated_data): return CompanySource.objects.create(**validated_data) class Meta: model = CompanySource fields = ['id', 'company', 'source'] is it required to set source = serializers.CharField(max_length=1500) inside Serliazer and what does it contribute to? Thank you -
how do i get user info in classed based view
I tried the solutions I could find, but it's still not working. I need to get the info of the user that is signed in. here is the class-based view : class networthChart(APIView, View): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = [] default_items = [] user = self.request.user networth_history = user.networthTracker.objects.filter(user = user) the error I get it: AttributeError: 'AnonymousUser' object has no attribute 'networthtracker' why is it returning AnonymousUser? I have used the same code in a function-based view before and it works -
Adding choices but not showing in the selectbox
I am trying to add categories in my blog project. So that whenever user post a blog he will add category also but in the select box it is not showing I tried this : from django import forms from .models import Post,Category,Comment choices = Category.objects.all().values_list('name','name') choice_list = [] for item in choices: choice_list.append(item) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','title_tag','author','category','body','snippet','header_image') widgets = { 'title' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title of the Blog'}), 'title_tag' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title tag of the Blog'}), 'author' : forms.TextInput(attrs={'class':'form-control','value':'','id':'elder','type':'hidden'}), 'category' : forms.Select(choices=choice_list, attrs={'class':'form-control','placeholder':"blog's category"}), 'body' : forms.Textarea(attrs={'class':'form-control','placeholder':'Body of the Blog'}), 'snippet' : forms.Textarea(attrs={'class':'form-control'}), } Here Category model contains my categories -
How to set custom choices in Wagtail form?
I am fetching a list of items from another project, and want to show that list in my form. I tried overriding ModelChoiceField to define choices, but it is not working: from django.forms import ModelChoiceField class CustomChoiceField(ModelChoiceField): def _get_choices(self): # Overriding ModelChoiceField's _get_choices() method to set custom choices self._choices = my_utils.get_choices() return self._choices from wagtail.admin.forms import WagtailAdminPageForm from wagtail.snippets.widgets import AdminSnippetChooser class MyCustomForm(WagtailAdminPageForm): my_field = CustomChoiceField(queryset=SomeModel.objects.all(), widget=AdminSnippetChooser(SomeModel), required=False) I want to choose from the list that was returned by the API call, and whatever the user chooses, should be saved in the my_field. How can I achieve this? -
How can i let users to write to each other in messenger from my website?
Im working in Django and i have a form in user profile for facebook account. I want to integrate this to do something like down below but user to user not user to website. sth like this -
Raise validation error only when a new file is being uploaded
Django 3.1.5 I'd like to prevent saving a file with the same name. This is necessary for fingerprinting static assets (for caching purposes). For example: If a user has already saved a file main-1.css, s/he can't upload such a file anymore. In thic they sholuld rename it and upload as main-2.css. def _validate_file_existance(value): model = apps.get_model('staticassets', 'CssFile') try: existing_file = model.objects.get(file__contains=value) except Exception as e: return # File doesn't exist. # File exists. raise ValidationError('A file with such a name already exists. Change the file version or don't try to save it.') Used like this: class SvgFile(models.Model): alt = models.CharField(max_length=255, verbose_name="Alt", null=False, blank=True, default="") file = models.FileField(upload_to=svg_upload_to, verbose_name="SVG file", validators=[validate_svg_file_existence], ) Problem If I want to edit alt, this validator raises validation error. But I don't upload a new file. I just edit another field of the instance of an SvgFile. Could you help me solve the problem: Raise validation error only when a new file is being uploaded. Keep silence when the file field is not touched. -
How not to display a field when it's None in Django
I have this model: class MsTune(models.Model): name = models.CharField(max_length=255) # title (source) start_page = models.CharField(max_length=20, blank=True, null=True, default="") def __str__(self): if self.start_page != '' or self.start_page is not None or self.start_page is not "None" or self.start_page is not null: return '%s, %s' % (self.name, self.start_page) else: return '%s' % (self.name) As you can see, I want only name if start_page is empty, or name, start_page if start_page is filled. No matter how many conditions I put (see above), I keep getting name, None in my template. What am I missing? Also, is there a shorter code I can put in place, instead of the verbose if / else ? -
How to use hooks.py of django-paypal to check payment attributes sent?
I followed https://django-paypal.readthedocs.io/en/stable/standard/ipn.html to use PayPal Standard IPN of django-paypal for a Django e-commerce website. I do not understand how should I use the signal in hooks.py to ensure the attributes such as 'business' and 'amount' are not changed by others. I cannot find any post that gives a good example about it. Most of them just ignore the hooks.py file. Is this file 'hooks.py' necessary for security? If yes, what should I return in hooks.py (for both scenarios: Attributes are found changed and payment fails; and attributes are not changed and everything is good to go)? Thanks so much. views.py from django.core.urlresolvers import reverse from django.shortcuts import render from paypal.standard.forms import PayPalPaymentsForm def view_that_asks_for_money(request): # What you want the button to do. paypal_dict = { "business": "receiver_email@example.com", "amount": "10000000.00", "item_name": "name of the item", "invoice": "unique-invoice-id", "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('your-return-view')), "cancel_return": request.build_absolute_uri(reverse('your-cancel-view')), "custom": "premium_plan", # Custom command to correlate to some function later (optional) } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "payment.html", context) yourproject/hooks.py from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received def show_me_the_money(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is … -
ValueError returning a function from a function in a model during makemigrations
I have a model defined in Django 3.1 like class MyModel(models.Model): def get_path(path): def wrapper(instance, filename): # code to make the path return 'path/created/for/filename.jpg' return wrapper image = models.ImageField(upload_to=get_path('files/')) but when I do python3 manage.py makemigrations I am getting a ValueError: Migrations for 'myproject': myproject/migrations/0023_auto_20210128_1148.py - Create model MyModel Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Python/3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Python/3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Python/3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Library/Python/3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Library/Python/3.7/site-packages/django/core/management/commands/makemigrations.py", line 182, in handle self.write_migration_files(changes) File "/Library/Python/3.7/site-packages/django/core/management/commands/makemigrations.py", line 219, in write_migration_files migration_string = writer.as_string() File "/Library/Python/3.7/site-packages/django/db/migrations/writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/Library/Python/3.7/site-packages/django/db/migrations/writer.py", line 99, in serialize _write(arg_name, arg_value) File "/Library/Python/3.7/site-packages/django/db/migrations/writer.py", line 51, in _write arg_string, arg_imports = MigrationWriter.serialize(item) File "/Library/Python/3.7/site-packages/django/db/migrations/writer.py", line 271, in serialize return serializer_factory(value).serialize() File "/Library/Python/3.7/site-packages/django/db/migrations/serializer.py", line 37, in serialize item_string, item_imports = serializer_factory(item).serialize() File "/Library/Python/3.7/site-packages/django/db/migrations/serializer.py", line 199, in serialize return self.serialize_deconstructed(path, args, kwargs) File "/Library/Python/3.7/site-packages/django/db/migrations/serializer.py", line 86, in serialize_deconstructed arg_string, arg_imports = serializer_factory(arg).serialize() File "/Library/Python/3.7/site-packages/django/db/migrations/serializer.py", line 159, in serialize 'Could not … -
Pass get_queryset in Context
Need help on passing the returned value from get_queryset to the context for rendering, I am reading the Django documentation on Class-based Views and I keep getting the same error name 'querySet' is not defined, any insight on what I'm doing wrong would be appreciated. class SearchPropertyListView(ListView): template_name = "search/search_list.html" def get_queryset(self): querySet = Property.objects.all() city_or_neighborhood = self.request.GET.get('city_or_neighborhood') category = self.request.GET.get('category') purpose = self.request.GET.get('purpose') if city_or_neighborhood != '' and city_or_neighborhood is not None: querySet = querySet.filter(Q(city__title__icontains=city_or_neighborhood) | Q(neighborhood__title__icontains=city_or_neighborhood) ).distinct() elif category != '' and category is not None: querySet = querySet.filter(category__title=category) elif purpose != '' and purpose is not None: querySet = querySet.filter(purpose__title=purpose) return querySet def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) city = City.objects.all().annotate( num_property=Count("property")).order_by("-num_property") categories = Category.objects.all() purposes = Purpose.objects.all() featured = list(Property.objects.filter(featured=True)) shuffle(featured) context['city'] = city context['categories'] = categories context['featured'] = featured context['purposes'] = purposes context['querySet'] = querySet return context -
Optimize repeteted queryset
I have few querysets that I use in every single view (>50). Is there a way to write once for all and keep the queryset result available for all views ? def MyView(request): company= Company.objects.get(User=request.user) user_info= User_infos.objects.get(User= request.user) groups= request.user.groups.values_list('name',flat = True) I'm using those results for filtering purposes like Product.objects.filter(Company = company) -
Fetching multiple entries of same id in django
I am trying to make a query and retrieve all the data listed under that particular user with the help of the primary key. I am getting the data but it consists of only one data but I should get three. Here is the views: def eachlead(request, pk): # print(pk) lead = Lead.objects.get(id=pk) leadinfo = LeadDetail.objects.filter(id=pk) print(list(leadinfo)) return render(request, "onelead.html", {'lead': lead, 'leadinfo': leadinfo}) Here is models: class LeadDetail(models.Model): Lead = models.ForeignKey(Lead, on_delete=models.CASCADE) files = models.FileField(blank=True, upload_to='media') tasks = models.TextField(max_length=1000) def __str__(self): return self.Lead.first_name class Lead(models.Model): lead_status = ( ('Potential', 'Potential'), ('Prospect', 'Prospect'), ('Negotiation', 'Negotiation'), ('Converted', 'Converted'), ('Failed', 'Failed') ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) age = models.IntegerField(default=0) city = models.CharField(max_length=25, null=True) country = models.CharField(max_length=30, null=True) email = models.EmailField(max_length=50, null=True) agent = models.ForeignKey('Agent', on_delete=models.CASCADE, null=True) status = models.CharField(max_length=15, choices=lead_status, null=True) avatar = models.ImageField(null=True, upload_to='media') def __str__(self): return self.first_name The response I am getting is [<LeadDetail: Test1111>] or [{'id': 1, 'Lead_id': 1, 'files': 'media/dummy.pdf', 'tasks': 'Meeting at 19:00 Friday'}] but there are 3 tasks under this ID: