Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is a good way for private hosting of a (django) website?
Let's say I have created a website using the django framework. I would like to to host it and access the website by my own AND by certain people that I choose. I don't want to host it on a public domain on the internet. What I can do: Host the website on a local computer (let's say a Raspberry Pi with RaspbianOS) with a certain IP address and port Access the website from anywhere using VPN Now I do not like the VPN solution as I also have other devices in my network. I want certain people to be able to access the website but I don't want them in my network. What is a good way to achieve what I want or is there maybe even a way? -
Update column in Django with child columns
I have 2 models Parent, Child class Parent(models.Model): id = Base64UUIDField(primary_key=True, editable=False) cost = models.DateTimeField(default=None, blank=True, null=True) class Child(models.Model): id = Base64UUIDField(primary_key=True, editable=False) cost = models.DateTimeField(default=None, blank=True, null=True) parent = models.ForeignKey(Parent, related_name= "children", related_query_name= "child") I need to populate cost column of Parent objects to maximum cost of all children of that parent I have tried to annotate to a new column new_cost, and its works. parents.annotate(new_cost=Max('child__cost')) But I need to populate values to existing column cost. Tried something like this, but not working. parents.update(cost=Max('child__cost')) -
nginx configuration error: try to open a file which does not exist in sites-enabled
I tried to check the nginx configuration with sudo nginx -t output: nginx: [emerg] open() "/etc/nginx/sites-enabled/django1" failed (2: No such file or directory) in /etc/nginx/nginx.conf:60 nginx: configuration file /etc/nginx/nginx.conf test failed I once created django1 but I removed/deleted this project. Now Iam trying to start a new project but cannot solve this issue. I googled a lot and tried to change the nginx.conf file but without success. Does anyone know whats going wrong here? Best alex -
BLEACH_DEFAULT_WIDGET django
I have django-bleach in my project. In models use: class Post(models.Model): title = models.CharField(max_length=255) content_2 = HTMLField() In settings.py: BLEACH_DEFAULT_WIDGET = 'wysiwyg.widgets.WysiwygWidget' How to write the correct path to process the bleach for HTMLField in BLEACH_DEFAULT_WIDGET ? -
Reduce mysql query ( Fulltext-search ) execution runtime, server-side?
VPS: ubuntu Django (latest) Python3.6 Mysql Current Code: posts = mytable.objects.raw('SELECT id, MATCH (tags) AGAINST (\''+some.tags+'\') as score FROM table ORDER BY score desc;') Excution Time (5 runs): 6.103515625e-05 6.4849853515625e-05 6.318092346191406e-05 8.034706115722656e-05 8.273124694824219e-05 The table have col name tags, how do I performing a search effectively. Considering the data in table is large (20k+ rows). is there a better way. or something with Django ORM. -
Django - What is the reason for "can't set attribute" error in this form?
In my Django project, I'm receiving the "can't set attribute" error on runtime, when loading a CreateView which looks like this: class DonationCreateView(InventoryEditingPermissionMixin, CreateView): model = Donation template_name = 'inventories/donation/donation_form.html' form_class = DonationForm success_url = reverse_lazy('donations_list') success_message = 'Donación creada correctamente' def form_valid(self, form): obj = form.save() ammount = obj.ammount autotank = obj.auto_tank tank = SaleWarehouseTank.objects.filter( warehouse__id=autotank.pk).last() tank.current_level -= ammount tank.save(update_fields=['current_level']) self.object = obj return HttpResponseRedirect(self.get_success_url()) def get_context_data(self, **kwargs): context = super(DonationCreateView, self).get_context_data(**kwargs) context['autotanks'] = SaleWarehouse.objects.filter(type=0) context['user_type'] = self.request.user.user_type context['clients'] = Client.objects.all() context['initial_client_name'] = '' context['is_update'] = False return context def get_form_kwargs(self): form_kwargs = super(DonationCreateView, self).get_form_kwargs() form_kwargs['user'] = self.request.user return form_kwargs And "DonationForm" looks like this: class DonationForm(forms.ModelForm): client_name = forms.CharField(required=False, label='Cliente') region = forms.ModelChoiceField(queryset=Region.objects.all(), required=False, label='Región') def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) self.user_type = user.user_type super(DonationForm, self).__init__(*args, **kwargs) self.fields['auto_tank'].required = False self.fields['client'].required = False self.fields['client'].widget = forms.HiddenInput() if user.user_type == 'region_admin': self.fields['auto_tank'].queryset = SaleWarehouse.objects.filter(type=0, region__id=user.region_id) elif user.user_type == 'admin': self.fields['auto_tank'].queryset = SaleWarehouse.objects.filter(type=0) def clean(self): cleaned_data = self.cleaned_data client_name = cleaned_data['client_name'] if client_name.strip() == '': cleaned_data['client'] = None else: if Client.objects.filter(social_reason__icontains=client_name).count() > 0: cleaned_data['client'] = Client.objects.filter(social_reason__icontains=client_name).last() else: raise forms.ValidationError('Por favor, elige un cliente de la lista, o deja el espacio en blanco') region = cleaned_data['region'] auto_tank = cleaned_data['auto_tank'] … -
How to apply multiple if condition filter in djago template
I am rendering two filter from my views to html template. 1) notifications_approved 2)notifications_pending. I am using this two filter separately in my html. Is there any way to use this two filter together in if statement? here is my code: #html template {% if notification in notifications_approved %} {% endif %} {% if notification in notifications_pending %} {%endif%} I tried this but it's not rendering anything's in my template: {%if notification in notifications_approved or notifications_pending %} {%endif%} I also tried this {%if notification|notifications_approved or notification|notifications_pending %} {%endif%} #getting TemplateSyntaxError views.py def ShowAuthorNOtifications(request): notifications_approved = Notifications.objects.filter(notification_type="Comment Approved").order_by('-date') notifications_pending = Notifications.objects.filter(notification_type="New Comment").order_by('-date') -
MongoDB migration from local host to a Linux server
So, I have a Django app, that is connected to a MongoDB database on my local machine. I brought my Django app on a Redhat Linux server. So, now I need MongoDB to be installed on the server: 1- Do I need to have access to the root on Linux server to install MongoDB? 2- I could not find any straight forward instruction to what to do for migration of MongoDB. Do know any references? I appreciate if you could help me with this. Thanks -
How to automate createsuperuser with django on Heroku?
I am trying to have Django superusers automatically created on my review apps on Heroku. As per this answer that points to an older version of these Django docs I should be able to run createsuperuser non-interactively and rely on environment variables for DJANGO_SUPERUSER_EMAIL, DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_PASSWORD. However, I still get asked for a username, when I run this: $ heroku run python manage.py createsuperuser --noinput -a myapp-pr-3 Running python manage.py createsuperuser --noinput on ⬢ myapp-pr-3... up, run.9300 (Free) CommandError: You must use --username with --noinput. I have the environment variables and they are correctly set. Is there something I am overlooking? -
Styling items on a webpage to scroll right to left in one row
I have created a webpage that lists products from the database using for loop. The products are displayed in many rows where the user needs to scroll down to view them. Like this: current display But I want the items to display on one row, where the user will scroll the items on that single row, right to left. So that it displays like this: desired display Which code do I add so as to achieve the above? Below is my current code: html <div class="container my-5"> <h2 class="my-5">Products</h2> <div class="row"> {% for product in object_list %} <div class="col-md-6 col-sm-12 col-lg-3"> <figure class="card card-product"> <div class="img-wrap"> <a href="{% url 'shopapp:productdetail' pk=product.pk %}"><img src="/media/{{ product.mainimage }}" style="width:100%; height:300px;"></a> </div> <figcaption class="info-wrap"> <h6 class="title">{{ product.name }}</h6> <div class="action-wrap"> <div class="price-wrap h5"> <span class="price-new">${{ product.price|floatformat:2 }}</span> <span class="price-old"><strike>${{ product.oldprice|floatformat:2 }}</strike></span> </div> </div> </figcaption> </figure> </div> {% endfor %} </div> </div> css .card{ height: 385px; margin-bottom: 20px; } .card-product:after{ content: "" display: table; clear: both; visibility: hidden; } .card-product .price-new, .card-product .price{ margin-right: 5px; color: #0000FF; } .card-product .price-old{ color: #ff0000; } .card-product .image-wrap{ border-radius: 3px 3px 0 0; overflow: hidden; position: relative; height: 220px; text-align: center; } .card-product .img-wrap img{ max-width: 100%; max-height: … -
After creating a configuration file named db-migrate.config in .ebextnsions, code is not deploying its showing instances error (i)what to do?
container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: portfolio.settings -
Detail page error after using slugify in django
I am getting this error when i click on any item detail page. Generic detail view must be called with either an object pk or a slug in the URLconf. URL: path('item/<slug:item_slug>/', ItemDetailView.as_view(), name='item_detail'), VIEW: class ItemDetailView(DetailView): model = Item slug_field = 'item_slug' MODEL: class Item(models.Model): title = models.CharField(max_length=100) description= RichTextField(blank=True, null=True) main_image= models.ImageField(null=True, blank=True,upload_to='images/') date = models.DateTimeField(auto_now_add=True) item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT) slug = models.SlugField(unique=True, blank=True, null=True) # new def save(self, *args, **kwargs): if not self.slug and self.title: self.slug = slugify(self.title) super(Item, self).save(*args, **kwargs) def __str__(self): return self.title -
docker Can't connect to MySQL server on 'localhost'
Error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 99] Cannot assign requested address)") My docker-compose.yaml version: "3" services: web: container_name: antiquely build: ./ # command: python manage.py runserver 0.0.0.0:8000 command: "bash -c 'python manage.py runserver 0.0.0.0:8000'" working_dir: /usr/src/antiquely ports: - "8000:8000" volumes: - ./:/usr/src/antiquely links: - db #mysql db: image: mysql container_name: mysql_container restart: always environment: MYSQL_DATABASE: baby MYSQL_USER: soubhagya MYSQL_PASSWORD: Thinkonce MYSQL_ROOT_PASSWORD: Thinkonce volumes: - /var/lib/mysql ports: - "3306:3306" Here is my docker-compose when i am running the application i am getting above error. Please take a look where i am doing mistake -
django/wagtail - object attribute showing None when admin panel states otherwise?
I'm having a problem understanding why my {{ post.categories }} in templates is showing itself with blog.PostPageBlogCategory.None when the admin panel shows a chosen category for the post object. Here is my model.py set up: from django.db import models # Create your models here. from django.db import models from modelcluster.fields import ParentalKey from modelcluster.tags import ClusterTaggableManager from taggit.models import Tag as TaggitTag from taggit.models import TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel, PageChooserPanel, StreamFieldPanel, ) from wagtail.core.models import Page from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.snippets.models import register_snippet class BlogPage(Page): description = models.CharField(max_length=255, blank=True,) content_panels = Page.content_panels + \ [FieldPanel("description", classname="full")] class PostPage(Page): header_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) tags = ClusterTaggableManager(through="blog.PostPageTag", blank=True) content_panels = Page.content_panels + [ ImageChooserPanel("header_image"), InlinePanel("categories", label="category"), FieldPanel("tags"), ] class PostPageBlogCategory(models.Model): page = ParentalKey( "blog.PostPage", on_delete=models.CASCADE, related_name="categories" ) blog_category = models.ForeignKey( "blog.BlogCategory", on_delete=models.CASCADE, related_name="post_pages" ) panels = [ SnippetChooserPanel("blog_category"), ] class Meta: unique_together = ("page", "blog_category") @register_snippet class BlogCategory(models.Model): CATEGORY_CHOICES = ( ('fighter', 'Fighter'), ('model', 'Model'), ('event', 'Event'), ('organization', 'Organization'), ('other', 'Other') ) name = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=80) category_type = models.CharField( max_length=100, choices=CATEGORY_CHOICES, blank=True) description = models.CharField(max_length=500, blank=True) panels = [ FieldPanel("name"), FieldPanel("slug"), FieldPanel("category_type"), FieldPanel("description"), ] … -
psycopg2.errors.InvalidTextRepresentation for Django migration to PositiveSmallIntegerField
Running a Django 1.11 app (Python 3.6.5) with a Postgres database. We originally had a CharField on a model that needed choice types, so, without thinking fully about the implications, I modified: foo = models.CharField(max_length=50, blank=True) to TYPE_1 = 1 TYPE_2 = 2 TYPE_3 = 3 MY_TYPES = ( (TYPE_1, _('Foo')), (TYPE_2, _('Bar')), (TYPE_3, _('Etc')), ) foo = models.PositiveSmallIntegerField(choices=MY_TYPES, default=TYPE_1, blank=True) ran and generated the migration file and redeployed the app to our test server on Heroku: remote: Running migrations: remote: Applying management.0084_auto_20210708_1730...Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute remote: return self.cursor.execute(sql, params) remote: psycopg2.errors.InvalidTextRepresentation: invalid input syntax for integer: "" remote: remote: remote: The above exception was the direct cause of the following exception: remote: remote: Traceback (most recent call last): remote: File "manage.py", line 19, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle remote: fake_initial=fake_initial, remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate remote: state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) … -
use csv file and plot data django
I have a simple app that import csv file and make plot but without having any error message it doesn't show plot It's part of my module: ... def plot_data(self): df = pd.read_csv("file.csv") return plotly.express.line(df) ... and it's part of my app file: import panel def app(doc): gspec = pn.GridSpec() gspec[0, 1] = pn.Pane(instance_class.plot_data()) gspec.server_doc(doc) -
Django - How to decrease page load times? Getting list of 1000 objects and using page pagination
In my django project, one of my pages, components.html is taking around 7-8 seconds to load. In my components_view view I do calls to get all objects (total count is less than 2,000) and then use page pagination to to only display 12 components on a single page, however it's still taking 7-8 seconds to load the page... How can I decrease load times for this page in particular - I thought page pagination would've solved this issue. Can I preload the data when the user accesses the home page? Server is a paid heroku server. views.py def components_view(request): # get objects from models subsystems = Subsystem.objects.all() subsystems = subsystems.order_by('name') component_types = ComponentType.objects.all() components = Component.objects.all() # gets around 1500 objects form_factors = FormFactor.objects.all() vendors = Vendor.objects.order_by('name').all() # gets 300 objects # page pagination COMPONENTS_PER_PAGE = 12 component_paginator = Paginator(components, COMPONENTS_PER_PAGE) page_number = request.GET.get('page') page_components = component_paginator.get_page(page_number) context = { 'subsystems': subsystems, 'component_types': component_types, 'components': page_components, 'form_factors': form_factors, 'vendors': vendors, } return render(request, 'main/components.html', context) Additional testing to see where / why it's taking so long: Page Components Size Load Time With Page Paginator 61.9 kB ~7 to 8 sec Without Page Paginator 1.1 MB ~7 to 8 sec When … -
Django Values() Method is not returing proper values
I am trying get only some of column names in my Model, I am trying to use below query but it is not working, Could you please help me. what is the right way to use it. view.py def get(self, request): ''' API function to Get all Objects ''' try: emp = EMP.objects.all() serializer = EmpSerializer(emp, many=True).data return Response({'status': 200, 'data': serializer, 'message': 'All data'}) except Exception as e: print(e) return Response({'status': 500, 'message': 'Something went wrong'}) Models.py class EMP(models.Model): A = models.AutoField(primary_key=True) B = models.CharField(max_length=70, blank=False, default='') C = models.CharField(max_length=10, blank=False, default='') D = models.CharField(max_length=200) E = models.CharField(max_length=10) F = models.CharField(max_length=10) G = models.CharField(max_length=10) H = models.CharField(max_length=100) Serializer.py class EmpSerializer(serializers.ModelSerializer): class Meta: model = EMP fields = ('A', 'B', 'C', 'D', 'E', 'F', 'G') But when I was trying with below quires I am able to get all columns emp = EMP.objects.all() If I am trying only some of the columns I am getting error emp = EMP.objects.values('A','B','C') Help me anyone, Thanks in advance !!! -
Getting a "duplicate key value violates unique constraint" with update_or_create() (non-default fields are unique_together)
This application is for an abuse department to better target clients who might be DNSBL/RBL listed and ensure they are compliant with anti-spam laws and policies and to safeguard other clients from collateral listings caused by clients who are infected or doing badness. The fields (ipaddress_id, rbl_id, blocked) are defined as "unique_together" in the Meta for the model. The idea behind using the blocked field as part of the unique_together definition is that it'll tell us when the last time the IP address was blocked and when it was not blocked by each RBL. I'm getting a key constraint error. Error: 2021-07-08 10:56:57.721 PDT [400] ERROR: duplicate key value violates unique constraint "core_rblhistory_ipaddress_id_rbl_id_blocked_0949c8f7_uniq" 2021-07-08 10:56:57.721 PDT [400] DETAIL: Key (ipaddress_id, rbl_id, blocked)=(1, 267, f) already exists. 2021-07-08 10:56:57.721 PDT [400] STATEMENT: INSERT INTO "core_rblhistory" ("ipaddress_id", "rbl_id", "added", "updated", "a_record", "txt_record", "status_url", "blocked") VALUES (1, 267, '2021-07-08T17:56:57.720732+00:00'::timestamptz, '2021-07-08T17:56:57.720748+00:00'::timestamptz, NULL, NULL, NULL::varchar(200)[], false) RETURNING "core_rblhistory"."id" The update_or_create() looks like this: RBLHistory.objects.update_or_create( ipaddress=ip_obj, rbl=rbl_obj, blocked=rbl_result["blocked"], defaults={ "a_record": rbl_result["a_record"], "txt_record": rbl_result["txt_record"], }, ) So I'm using the ipaddress, rbl, and blocked fields to select the record to be updated (if it exists) and the dict within defaults to be used if the record must … -
Error 1064, "You have an error in your SQL syntax" Python Django
I am receiving multiple SQL errors in my Django website post setup. I believe it's a version issue but can't point it out. The site was created with mysqlclient, but I have moved it to mysqlconnector. Full example error messages are: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION max_matches = 1000' at line 1") (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group, denomination, location, affiliation, released_by, affiliations, filetypes' at line 1") MySQL Version: 8.0 (used just for sphinx) Database using Postgres Using mysqlconnector init.py (main for site) imports pymysql, using install_as_MySQLdb() I auto-created models.py using python manage.py inspectdb>models.py, but am not sure if that even helped anything (the site was given with model files only controlled by app). Django is 2.0.13, python is 3.9 running with Six -
Bokeh datatable not rendering
I am getting below error while rendering BokehJS datatable component in template. bokeh-2.3.2.min.js:166 Uncaught (in promise) Error: Model 'StringFormatter' does not exist. This could be due to a widget or a custom model not being registered before first usage. I tried to manually include below styles and scripts, however issue still remains same and datatable is not displayed on UI. <link href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.9.min.css" rel="stylesheet" type="text/css"> <link href="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.9.min.css" rel="stylesheet" type="text/css"> <link href="https://cdn.bokeh.org/bokeh/release/bokeh-tables-0.12.9.min.css" rel="stylesheet" type="text/css"> <script src="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.9.min.js"></script> <script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.9.min.js"></script> <script src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-0.12.9.min.js"></script> Datatable code: from django.shortcuts import render from .models import Trend_Chart import pandas as pd from bokeh.models import NumeralTickFormatter, HoverTool, ZoomInTool, PanTool, ResetTool, SaveTool, ColumnDataSource from bokeh.models.widgets.tables import TableColumn, DataTable, StringFormatter, StringEditor from bokeh.plotting import figure, output_file, save from bokeh.embed import file_html, components from bokeh.resources import CDN # Construct Raw data data = dict( timeseries=["placeholdertext"], testvalue1=["placeholdertext"], testvalue2=["placeholdertext"], testvalue4=["placeholdertext"], testvalue5=["placeholdertext"] ) source = ColumnDataSource(data) columns = [ TableColumn(field="timeseries", title="Time Series"), TableColumn(field="testvalue1", title="Test Value1"), TableColumn(field="testvalue2", title="Test Value2"), TableColumn(field="testvalue3", title="Test Value3"), TableColumn(field="testvalue4", title="Test Value4"), ] data_table = DataTable(source=source, columns=columns, width=400, height=280) # save the results to a file # output_file("temp.html") # doc = curdoc() script, div = components(p) script1, table = components(data_table)``` Is there any other way to include simple datatable in django template? Any reference … -
In Django 3.2 I am getting this error: app ImportError: Module 'apps.articles' does not contain a 'ArticlesConfig' class
Research Preamble: What have I tried? I'm new to Django and learning my way through while trying to follow best practices. I'm working my way through Two Scoops of Django 3.x. Any questioning of structure should be directed to the authors. I'm hopeful that the question is solid enough to not be deleted in the first few minutes as I'm really stuck on this one. If this question is to be deleted I would appreciate guidance on how to improve how I ask questions in the future. I've read the how to ask good questions blog and am hopeful I'm following this guidance. If I did miss something please do more than provide a link to the blog. Please note that I have researched this question and the closest I came was a Q&A for Django 1.7 here: Django 1.7 app config ImportError: No module named appname.apps: This solution did not work for me (although it did give me a good path to try). Interestingly, they chose the exact same application structure as I did, over 5 years earlier. Please note that providing the projectname in config did not solve this for me as it did the OP. Other questions … -
What is the complete list of ways that the database can be updated with Django and the Django ORM?
I need the complete list of code paths that can update the database through the Django ORM. So far, I've found: A model's save method Queryset methods (update) Manager methods (bulk_*) Are there more? Is it possible to monkey-patch code in that runs every time one of these methods is called? -
How to determine the direction for displaying div elements?
I'm creating a website. I have a problem displaying div elements because they are displayed upwards. But I want them to appear downwards as in the second picture. How to solve this problem? How they display now: How I want them to display(I have done this manually): My HTML file: </form> {% if searched %} <div class="results"> {% for user in users_list %} <a href="{% url 'user_page' pk=user.pk %}"> <div class="result"> <div class="photo-circle"> <p class="userphoto"></p> </div> <p class="username">{{ user }}</p> </div> </a> {% endfor %} </div> {% else %} <p>Nic jste nevyhledali</p> {% endif %} My CSS file: .results { position: absolute; left: 50%; top: -10%; display: flex; flex-direction: column; gap: 50px; transform: translate(-50%,-50%); } .result { background-color: #FFFFFF; border-radius: 50px/50px; transform: translate(-50%,-50%); width: 35vw; height: 17vh; } .photo-circle { height: 15vh; width: 15vh; background-image: linear-gradient(to bottom right, #0390e2, #611be4); border-radius: 50%; position: absolute; top: 50%; left: 2%; transform: translate(0, -50%); } .userphoto { color: white; font-size: 400%; font-family: 'Quicksand', sans-serif; font-weight: 700; position: absolute; margin-left: 50%; margin-top: 45%; transform: translate(-50%,-50%); } a { text-decoration: none; } .username { font-family: 'Quicksand', sans-serif; font-weight: 650; text-indent: 10vw; color: black; font-size: 150%; position: absolute; top: 35%; transform: translate(0, -50%); } -
How do these different Django 'context' construction differ?
The basic concept of context in Django are well explained here and here, as well as Django doc. But I don't understand the following code that works in the Mozilla Django tutorial: class BookListView(generic.ListView): model = Book def get_context_data(self, **kwargs): context = super(BookListView, self).get_context_data(**kwargs) context['author_books'] = Book.objects.filter(author=self.kwargs['pk']) return context Why is it necessary to define context twice? Is it the same as: author_books = # 'author_books' defined book_list = # 'book_list' defined context ={ 'author_books': author_books, 'book_list': book_list, } Testing in Django shell didn't work for me as I'm still struggling with how to extract data from foreign-key items.