Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Do I Allow Users To Post Links In Django?
I dont need to have the full rich text editor but i want users to be able to post hyperlinks that work so is there a good way to do this in django forms or models? -
element.lable_tag as placeholder in Django
I want to style my user creation Form as a Registration in HTML like I already did in the login. This is my html code: {% csrf_token %} {% for field in registration_form %} <div class="signIn-input-group"> <div class="signInput-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> <input class="signIn-data-input" type="text" placeholder="{{field.label_tag}}" class="form-control" > </div> <div class="signIn-msg"> {% if field.help_text %} <small>{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p>{{error}}</p> {% endfor %} </div> </div> {% endfor %} This is what the Browser is displaying: <div class="signIn-input-group"> <div class="signInput-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> <input class="signIn-data-input" type="text" placeholder="<label for=" id_first_name"="">First name:" class="form-control" &gt; </div> <div class="signIn-msg"> </div> </div> How can I get rid of the First name:" class="form-control" > display? This also worked for my Login so why not here? best regards. -
How to run python script asynchronously in Django project?
I'm working on project where I scrap job offers and display it on my django app. My scrapper is an indenpendent python script based on requests and selenium. I need to run in Django background on every 5 minutes so it can scrap new data and insert it into my postgres db. Is there any recommended way of handling it ? I thought about running my script via windows scheduler as an external application and just add some psycopg2 things to update my database. I would appreciate any ideas :) -
React/Redux/Django: why this error - getState is not a function?
Im working on token authentication for my posts app (crud functionality) with react, redux and django. Using knox for the authentication. also, i pushed the frontend part of my code to bitbucket for better debugging. link here https://bitbucket.org/Yash-Marmat/frontend-part-of-posts-app/src/master/ i can't find what i missed in my code keep getting this error --> getState() is not a function (see pic below) -
How to form URLs
I am not sure about the exact terminology here. If we have the following URL: https://www.thewhiskyexchange.com/c/331/non-vintage-champagne If I load https://www.thewhiskyexchange.com/c/331/ it would automatically add(redirect to) "non-vintage-champagne". My questions are: What is the exact terminology/the methods that are used here? Is it important to add c/331/ and a redirect(or something similar) instead of a simple domain.com/non-vintage-champagne (or domain.com/products/non-vintage-champagne or something simpler) What exactly is c/331/? Do we need to structure it that way with a letter and number or we can also use simple words or similar? Any advice how to structure the URLs in a website? I am using Django + Vue 3 I am not sure if I am asking the right questions, so any additional information or links would be appreciated -
Django chained dropdown from DataFrame or dictionary
I am new to Django and have to get familiar with it. Problem I have is I need to create a survey type view with chained dropdowns. Tutorial I checked would actually create models (data in db) and jquery, but I don't need to store any data used in dropdowns, only end result. I get JSON data via API, then I use pd.DataFrame to clean it up. Clean data should be used in dropdowns eg Country -> City, without storing it. -
django "view on site" button wrong redirect after changing DB config
I tested adding another DB (holding documents) next to a 'default' DB (for auth etc.) and surprisingly that stopped 'VIEW ON SITE' button (in admin site) to work. So when I am in the admin site: http://localhost:8002/admin/reviewer/document/<uuid_here>/change/ and I click on "VIEW ON SITE" button, it takes me to http://localhost:8002/admin/r/7/<uuid_here>/ and delivers Page Not Found: Page not found (404) Request Method: GET Request URL: http://localhost:8002/admin/r/7/<uuid_here>/ Raised by: django.contrib.contenttypes.views.shortcut Content type 7 object <uuid_here> doesn’t exist You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. whereas previously (single 'default' DB for everything) it correctly redirected me to http://localhost:8002/reviewer/doc/<uuid_here> Any ideas what could the fix be? Here's my code, not sure what could be missing: docs_rev\docs_rev\settings.py DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'auth.sqlite3'), }, 'docs' : { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'docs.sqlite3'), }, } DATABASE_ROUTERS = [ 'reviewer.router.docsRouter', ] docs_rev\docs_rev\urls.py urlpatterns = [ path('admin/', admin.site.urls), path('reviewer/', include ('reviewer.urls')), path('', RedirectView.as_view(url='reviewer/', permanent=True)), path('accounts/', include('django.contrib.auth.urls')), ] docs_rev\reviewer\urls.py urlpatterns = [ path('', views.index, name='index'), path('docs/', views.DocsListView.as_view(), name='docs'), path('doc/<uuid:pk>/', views.DocDetailView.as_view(), name='document-detail'), ] docs_rev\reviewer\models.py … -
Vue - Pass props into vuex store?
I want to pass initial data into my vuex store as a prop from my template. I am using Django templates and loading vue and vuex via script tags. Is this possible? Example: index.html {{ initial_data }} <!-- Sent from django views --> <script src="{% static 'project/js/store.js' %}"></script>. -
Django bulk_update does not work as excpected with django crontab?
Im trying to create a crontab function to automatically update my objects every 1 min. I can see in terminal when debugging that my bulk_update works but they are not saved in my db and i cant figure out whats happening behind. Here is my model: from django.db import models from django_bulk_update.manager import BulkUpdateManager class Products(models.Model): name = models.CharField(max_length=200) stock = models.IntegerField() objects = BulkUpdateManager() class Meta: db_table = "products" verbose_name_plural = "products" def __str__(self): return self.name Crontab configuration settings: CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/1 * * * *', 'utils.tasks.getStockData') ] -Here is my crontab function where i need to bulk update: def getStockData(self): data = {foo} url = 'bar' try: r = requests.post(url,json=data, headers=headers, timeout=555) alpha = r.json() if r.status_code == 200: products = Products.objects.all() serializer = ProductsSerializer(products, many=True) bulkUpdate = [] for product in serializer.data: productUpdate = { "id":product['id'], "stock": 0 } for alphaProduct in alpha['entiteteTeReja']['artikujGjendjeRi']: if product['name'] == alphaProduct["KODARTIKULLI"]: productUpdate["stock"] = alphaProduct["gjendje"] Products.objects.all().update() bulkUpdate.append(productUpdate) bulk_update(products) except requests.exceptions.HTTPError as http_error: return { 'status': False} And here are my views: from django.http import JsonResponse from rest_framework import status from rest_framework.authtoken.views import APIView from utils.tasks import getStockData from .models import Products from .serializers import ProductsSerializer class SingleProductAPI(APIView): def … -
How do I export my Django project from PyCharm to other PC? Sharing on GitHub did not work
I have to return the office laptop and wish to export my Django project from here, I'm getting some errors while sharing it on GitHub, please guide me through this. -
I how to add multiple users to manytomanyFiled at ones
in book.who_can_see.add(author.id, [2, 3]) 🔴 payload["description"] return an array like [1,2] so it seems i should convert the array to pure numbers with commas like 2,3 but I have no idea how. @api_view(["POST"]) @csrf_exempt @permission_classes([IsAuthenticated]) def add_book(request): print({"request.data": request.data}) payload = request.data user = request.user try: author = Author.objects.get(id=payload["author"]) book = Book.objects.create( title=payload["title"], description=payload["description"], added_by=user, author=author, ) # 🔴 payload["description"] this return an array like [1,2] # book.who_can_see.add(author.id, 2, 3) book.who_can_see.add(author.id, [2, 3]) # it seems i should convert the array to pure numbers with commas like 2,3 book.who_can_see.add(author.id) serializer = BookSerializer(book) return JsonResponse({'books': serializer.data}, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
Filter based on counts django annotate query
I need to filter records based on total counts of records for vehicle_owner_organization_id , i.e if total counts in the collection for vehicle_owner_organization_id are greater than 1, then only go ahead with the following query getting monthly distinct counts. Is there an easy way to do this. Or do I need to run another query to filter. values = ['month', 'city_code'] transacting_users = list(FieldOpsBooking.objects.using( 'analytics').filter(**filter_query).annotate( month=TruncMonth('pick_up_at')).values(*values).annotate( count=Count( 'vehicle_owner_organization_id', distinct=True)).values(*values, 'count')) -
Djnago Background task not working some times
I am using Django background task. but the issues is sometimes its not working properly. task is not completing. some times the function is not getting called. My views.py def process_tasks(): process_tasks_cmd = "python manage.py process_tasks" process_tasks_args = shlex.split(process_tasks_cmd) process_tasks_subprocess = subprocess.Popen(process_tasks_args, shell=True) @api_view(["POST"]) @permission_classes([]) def test(request): process_tasks() fingerprint_sync(6, 5, 8) return Response(result, status=status.HTTP_200_OK) Tasks.py @background(schedule=django.utils.timezone.now()) def fingerprint_sync(EmployeeId,finger_activatn,device_code): """ FingerPrint Synchronization for employee After Creating FingerPrint, Sync the FingerPrint data to all Device Parameters: EmployeeId: pk of employee Returns: Background Process Execute if syncing not done- Data added to Synchronization table """ try: logging.getLogger("info_logger").info("Triggered Fingerprint sync") finger = FingerPrintInfo.objects.filter(~Q(FingerData=None), Employee=EmployeeId, Activation=finger_activatn)\ .order_by('FingerPrintId') logging.getLogger("info_logger").info("Finger data filtered and arranged") emp = Employee.objects.get(pk=EmployeeId) data = { "Employees": { "EmployeeId": emp.EmployeeId, "EmployeeCode": emp.EmployeeCode, "EmployeeName": emp.EmployeeName, "EmployeeStatus": emp.EmployeeStatus }, "FingerPrintId": finger[3].FingerPrintId, "FingerData": bytes(finger[3].FingerData).decode("utf-8") } logging.getLogger("info_logger").info("Corresponding employee identified") emp_device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"]),~Q(DeviceCode=device_code)) for div in emp_device: try: device = Device.objects.get(pk=div.DeviceId) url = protocol + div.DeviceCode + device_api["API4"] logging.getLogger("info_logger").info(url) resp = requests.post(url, json=data) logging.getLogger("info_logger").info(resp) if not resp.text.__contains__('200'): synchronization = Synchronization( Employee=emp, Device=div, SyncType=selection_type["Fingerprint"] ) synchronization.save() except Exception as ex: logging.getLogger("info_logger").info(repr(ex)) logging.getLogger("info_logger").info("Fingerprint not synced in " + div.DeviceCode) except Exception as ex: logging.getLogger("info_logger").info(repr(ex)) Here fingerprint_sync method is not calling every time. and not getting why . could anyone please … -
Python Django *png does not render; Image is broken
I am a novice in programming. I have created an app in django with python programming. I am trying to render some images on my web pages but they appear as broken. I don't seem to have a solution for this. const heartSrcOutline = '/static/network/image/heart_outline.png'; const editSrc = '/static/network/image/edit.png'; const postLimit = 10; var currentPage = 1; var currentFilter = 'all'; And the image is stored in image folder under my app. Please suggest some solution. PS: I tried changing the browser from edge to chrome but to no avail. -
Migration admin.0001_initial is applied before its dependency app.0001_initial on database 'default'
I am trying to make custom made user model for my project in Django. My models.py: class myCustomeUser(AbstractUser): username = models.CharField(default="abcdef", max_length=20, unique="True", primary_key=True) password = models.CharField(default="12345", max_length=20) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') industry_extrafield = models.TextField(blank=True) class Employee(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='employee_releted_user') industry = models.OneToOneField(Industry, on_delete=models.CASCADE, related_name='employee_releted_industry') employee_extrafield = models.TextField(blank=True) class Inspector(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='inspector_releted_user') inspector_extrafield = models.TextField(blank=True) class Admin(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='admin_releted_user') admin_extrafield = models.TextField(blank=True) in settings.py: AUTH_USER_MODEL = 'app.myCustomeUser' Here admin.site.register is also done in admin.py. Now it shows the following message in the terminal while I try to migrate or makemigrations: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Python\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "G:\Python\lib\site-packages\django\core\management\commands\makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "G:\Python\lib\site-packages\django\db\migrations\loader.py", line 295, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its … -
How do I add non-field related date range to Django admin form
I have a django admin page which is for viewing purposes only and rather than displaying data from the model, it is displaying data for a table linked by a foreignkey to an intermediate table which is linked via a foreign key to my model. I want to apply a date range filter on the third table. class Brand(models.Model): data ... class Organisation (models.Model): data ... brand = models.ForeignKey(Brand, on_delete=models.CASCADE) class DailyStat (models.Model): stat_type = model.CharField(max_lenth=11, choices=STAT_TYPE_CHOICES date = models.DateField() organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE) I then created a change_form.html template in 'templates/admin/brand' which displays the data from DailyStat which I want for the Brand. But I want to be able to filter this so I created a new form class BrandAdminForm(forms.ModelForm): from_date = forms.DateField(widget=admin.widgets.AdminDateWidget()) to_date = forms.DateField(widget=admin.widgets.AdminDateWidget()) class Meta: model = Brand fields = ['id','from_date','to_date'] And within the BrandAdmin definition, referenced it class BrandAdmin(admin.ModelAdmin): list_display = ['name','get_page_views','cqc_brand_id'] ordering = ['name'] search_fields = ['name'] form = BrandAdminForm These fields didn't automatically show in the detail page so I added the following within the form tags of {% block content %} of the change_form.html <table style="width:60%"> <tr> <td>From: </td> <td>{{ adminform.form.from_date }}</td> <td rowspan=2><button type="submit" value="Save and continue editing" class="btn viewsitelink">Filter</button></td> </tr> … -
Check if URL is valid on a Django formset
I have this model: class dateEvent(models.Model): link = models.URLField(null=True, blank=True) link_description = models.CharField(max_length=30, null=True, blank=True) event = models.ForeignKey('Event', on_delete=models.CASCADE) class Event(models.Model): title = models.CharField(max_length=200) [...] Views.py: [...] def event_edit_view(request, id): event = get_object_or_404(Event, id=id) active_user = request.user form_event = EventForm(request.POST or None, instance=event) DateEventFormSet = inlineformset_factory(Event, dateEvent, extra=5, can_delete=True, fields=('event', 'start_date_time', 'venue', 'link', 'link_description'), widgets={ 'venue': s2forms.Select2Widget(), 'link': forms.TextInput(attrs={'placeholder': 'http://'}), 'start_date_time': CalendarWidget(), 'description_link': forms.TextInput(attrs={'placeholder': 'Link description'}), }) form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), prefix="dateEvent", queryset=dateEvent.objects.filter(event__id=id)) if request.method == "POST": if form_event.is_valid() and request.POST['action'] == 'submit': if form_date_event.is_valid(): form_event.save() form_date_event.save() messages.success(request, 'Event updated successfully. See the <a href="/event-detail/' + str(id) + '">detail page</a>') return redirect('my-events') else: print(form_date_event.errors) elif form_event.is_valid() and form_date_event.is_valid() and request.POST['action'] == 'update': form_event.save() form_date_event.save() else: raise forms.ValidationError([form_event.errors, form_date_event.errors]) context = { 'event': event, 'id': event.id, 'form_event': form_event, 'form_date_event': form_date_event, } return render(request, "events/event-edit.html", context) [...] And template: <tbody id='date_body'> {{ form_date_event.management_form }} {% for formDate in form_date_event.forms %} <tr class="form-row-dateEvent"> <td>{{formDate.venue}}<br> </td> <td>{{ formDate.start_date_time}}</td> <td>{{formDate.link}}</td> <td>{{formDate.id}}{{formDate.link_description}}</td> </tr> {% endfor %} </tbody> How can I check if the URL (in the link field) entered by the user in the form is valid and throw an error if it's not? Of course the code must accept empty values, because it's … -
Json from backend which is built with Django Rest Framework is somehow undefined at frontend, built with React
I'm currently trying to learn the integration of Django Rest Framework and React.js, the former for the backend and the latter for the frontend, by building a simple to-do application. views.py from rest_framework import viewsets from . import models from .serializers import ToDoSerializer, ToDoContainerSerializer class ToDoContainerViewSet(viewsets.ModelViewSet): queryset = models.ToDoContainer.objects.all().order_by('created') serializer_class = ToDoContainerSerializer serializers.py from rest_framework.serializers import HyperlinkedModelSerializer from . import models as todo_model from rest_framework.serializers import ReadOnlyField class ToDoContainerSerializer(HyperlinkedModelSerializer): created_by = ReadOnlyField(source='created_by.id') class Meta: model = todo_model.ToDoContainer fields = ( 'url', 'id', 'created_by', 'todos_name', 'todos_important', 'todos_items_count', ) extra_kwargs = { 'url': { 'view_name': 'todos:todocontainer-detail', }, } models.py from django.db import models from core.models import TimeStampedModel from django.core.validators import MinValueValidator, MaxValueValidator class ToDoContainer(TimeStampedModel): created_by = models.ForeignKey( user_model.User, on_delete=models.CASCADE, related_name="todo_container") todos_name = models.CharField(max_length=50) todos_important = models.BooleanField(default=False) def todos_items_count(self): todo_items = len(self.todo.all()) return int(todo_items) def __str__(self): return str(self.todos_name) I built the views, serializers, models like above, and it seemed api generated properly like the below. And I tried to get the json of the above to frontend by using the axios module like the below. import React from 'react'; import axios from 'axios'; import ToDoCard from './ToDoCard'; class ToDoLists extends React.Component { state = { isLoading: true, toDos: [] }; getToDos = async … -
Error -Undefined variable: 'ModelSelect2Widget'
Happy New Year I am New to this field. I am working on Dependent Dropdowns for which i took reference from- https://django-select2.readthedocs.io/en/latest/extra.html on replicating the same With the following Code - Forms.py- class AddressForm(forms.ModelForm): class Meta: model=City country = forms.ModelChoiceField( queryset=Country.objects.all(), label=u"Country", widget= ModelSelect2Widget( search_fields=['name__icontains'], dependent_fields={'city': 'cities'}, ) ) city = forms.ModelChoiceField( queryset=City.objects.all(), label=u"City", widget=ModelSelect2Widget( search_fields=['name__icontains'], dependent_fields={'country': 'country'}, max_results=500, ) ) Getting Error-Undefined variable: 'ModelSelect2Widget' I also installed - INSTALLED_APPS=[ 'django_select2', 'django_q', ] Kindly Help Me in the same Thanks in Advance -
Problem with reading excel file using pandas in webapp
I am reading an excel file using pandas in my web app based on Django. It works perfectly fine on my system and on one of the instances I had launched on AWS EC2 servers. But when I tried to launch another instance, I am encountering several issues. Pandas is reading the rows and columns beyond the occupied range, with all the values NaN. dat1 = pd.read_excel('Data/Warm Up Cool Down Protocols.xlsx',sheet_name=None) warm_up = curr_WUCD[0] cool_down = curr_WUCD[1] #I am finding the warm_up cool_down values through a separate function WU_Exercise_df = dat[warm_up] CD_Exercise_df = dat[cool_down] I tried adding these lines but that too doesn't work: WU_Exercise_df = WU_Exercise_df.dropna(how='all') CD_Exercise_df = CD_Exercise_df.dropna(how='all') Could you please help me resolve this issue, and help me learn the cause of these disparities. I tried reconciling the versions of pandas and Django on all three places, and the same problem remains with two of those working perfectly fine while the third one giving this problem. -
Django: Map CreateView to an existing form template
I'm pretty new to Django and as an intern backend-developer, I'm asked to make a CreateView for a user to create a shop on the website. I need to make it so that it "maps" to a template my frontend colleague made, with all the fields and the styling already there. I only know how to make simple CreateViews that basically generates a form for you. But here I don't want it to do that, I want to use the already existing styled fields in the template, but I'm having a hard time finding how to do that. Here's my model (I haven't included all the lines for readability reasons, but I'll do if needed): class Dealer(models.Model, CloneMixin): dealer_check = models.ForeignKey("self",null=True, blank=True, on_delete=models.SET_NULL) published = models.BooleanField(null=True,blank=True, default=True) informed = models.BooleanField(null=True,blank=True, default=False) objectid = models.CharField(null=True,blank=True,max_length=100) language = models.ForeignKey(Language, null=True, blank=True,on_delete=models.SET_NULL) name = models.CharField(null=True,blank=True,max_length=100) street = models.CharField(null=True,blank=True,max_length=100) number = models.CharField(null=True,blank=True,max_length=100) city = models.CharField(editable=False,null=True,blank=True,max_length=100) phone = models.CharField(null=True,blank=True,max_length=100) email = models.CharField(null=True,blank=True,max_length=100) users = models.ManyToManyField(User,null=True,blank=True, related_name='dealers') isowner = models.BooleanField(null=True,blank=True, default=False, editable=False) created = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated = models.DateTimeField(auto_now=True, blank=True, null=True) Here's my form: class ShopCreateForm(forms.ModelForm): class Meta: model = Dealer fields = ["name", "email", "phone", "street", "number", "description"] And here's my view (You can … -
How to cause child class to save when parent class is saved?
Is there a way to call the save method of a Child class when the Parent class is saved? I have a field some_other_value on the Child class that is updated whenever the Child is saved, and this is based off a value some_value on the parent class. However, when I save the Parent class, it doesn't update the Child class since the child's save method isn't called. I was thinking of some sort of post_save signal, but thinking whether this would cause some sort of recursive loop. class Parent(models.Model): some_value = models.IntegerField(default=0) class Child(models.Model): some_other_value = models.IntegerField(default=0) def save(self, *args, **kwargs): self.some_other_value = self.some_value * 2 super().save(*args, **kwargs) -
Django STATIC_URL always points to local directory
I want to serve the static content generated by django in a different host with nginx. The server with the files has the name 'static-server' and I can't access it with django. The static file looks like this: STATIC_URL = 'http://static-server/static/' But the error log gives the following path: "GET /http:/static-server/static/admin/css/base.css HTTP/1.1" 500 145 Why is django looking for the files in local? How can I avoid this? -
Django hiding an item if object == None
In my template i'm trying to hide a paypal button if the email item is None. {% if object.email == None %} <h1>Nothing here </h1> {% else %} <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="business" value="{{ object.email }}"> </form> {% endif %} After testing by not entering the email in my form, the button still shows and the 'Nothing here' is not showing. -
Global variable doesn't work inside django views
I wanted to use some dummy data in my django views to work with templates. When posts variable is outside home function all im getting is empty body. Although when i move it inside everything displays as it should. from django.shortcuts import render posts = [ { 'author': 'Kamil', 'title' : 'Post 1', }, { 'author': 'Tomek', 'title' : 'Post 2', }, ] def home(request): context = { 'posts' : posts } return render(request, 'blog_app/home.html', context) Here is also my html <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p>By {{ post.author }}</p> {% endfor %} </body> </html>