Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-filter AssertionError: Cannot filter a query once a slice has been taken
I'm using Django-filter ,I want to slice the rows ,just want the first 75 row: def hist_view_render(request): all_obj = RunStats.objects.all().order_by('-create_dttm')[:75] hist_filter = RunStatsFilter(request.GET, queryset=all_obj) paginator= Paginator(hist_filter.qs, 15) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) context = {'response': response,'filter': hist_filter} return render(request, 'runstat_hist.html',context) I have tried put the [:75] in different places ,but I always receive the error: Cannot filter a query once a slice has been taken The only way that works is slice it in the template ,but I want to find a way to slice it in the views.py. Any friend can help ? -
How can I paginate the attributes from a model?
I have a single for each series, but I want to paginate inside this page. I want to paginate the episodes because some series have more than 100 episodes and it is too much for a single page. class SerieDetailedView(DetailView): template_name = "tailwind/series_detail.html" model = Serie slug_url_kwarg = "serie_name" slug_field = "name" context_object_name = "project" def get_object(self, queryset=None): return Serie.objects.get(name=self.kwargs["serie_name"]) In this case, I have this as my model: class Serie(models.Model): name = models.CharField(max_length=150, unique=True) finished = models.BooleanField(default=False) episodes = ArrayField(base_field=models.CharField(max_length=100), default=list) published_at = models.DateTimeField(auto_now_add=True) I’m just getting how to paginate all the series, but it’s different, I want to paginate a thing that is inside the series. I’ve tried to do it, but it has not worked because is a single page: class SerieDetailedView(DetailView): template_name = "tailwind/series_detail.html" model = Serie slug_url_kwarg = "serie_name" slug_field = "name" context_object_name = "project" paginate_by = 10 def get_object(self, queryset=None): return Serie.objects.get(name=self.kwargs["serie_name"]).episodes.order_by('-published_at') -
association user with forms
I'm making something like this: admin creates form manually, and user is automatically created with this form. But I need to add association that form to a new automatically created user, that's where I'm stuck. How can I make user auto registration to associate that form I need this because I want to then to show 'filtered, created' form by user. Views.py def create_driver_view(request): if request.method == "POST": add_driver = DriverForm(request.POST) add_driver_files = request.FILES.getlist("file") if add_driver.is_valid(): email = request.POST['email'] usern = 'test' passw = 'test' user = User.objects.create_user(email = email, username = usern, password = passw) user.save() f = add_driver.save(commit=False) f.user = request.user f.save() for i in add_driver_files: DriversFiles.objects.create(driver_files=f, file=i) return redirect('drivers:list_driver') else: print(add_driver.errors) else: add_driver = DriverForm() add_driver_files = DriverFormUpload() return render(request, "drivers/add.html", {"add_driver": add_driver, "add_driver_files": add_driver_files}) Forms.py class DriverForm(forms.ModelForm): class Meta: model = Drivers fields = [ 'full_name', 'phone_number', 'email', 'address', 'country', 'state', 'city', 'zip', 'birth_date', 'license_no', 'license_exp_date', 'last_medical', 'next_medical', 'last_drug_test', 'next_drug_test', 'status', ] class DriverFormUpload(forms.ModelForm): class Meta: model = DriversFiles fields = [ 'file', ] widget = { 'file': forms.ClearableFileInput(attrs={'multiple': True}), } Models.py STATUS = ((0, 'Inactive'), (1, 'Active')) class Drivers(models.Model): full_name = models.CharField(max_length=50, default=None) phone_number = models.CharField(max_length=50, default=None) email = models.EmailField(unique=True,max_length=255, default=None) address = models.CharField(max_length=70, default=None) … -
Сreate a folder for user files when creating a user FastAPI?
How can I create a directory for user files when creating a user? I want to store files from a client in that client's directory the code executes without errors, but the directory does not creating in the specified directory... i have this, but it doesn't work def create_user(db: Session, request: UserBase): new_user = DbUser( # id create automaticly first_name = request.first_name, last_name = request.last_name, email = request.email, password = Hash.bcrypt(request.password) ) db.add(new_user) db.commit() db.refresh(new_user) path = f"/users_files/user_id_{new_user.id}/orders" try: pathlib.Path(path).mkdir(parents=True, exist_ok=True) except OSError: print("Create folder %s error" % path) else: print ("Folder create %s " % path) return new_user when i specify the path = f"../users_files/user_id_{new_user.id}/orders" the dedirectory is created but one level higher. -
How to ensure that the timezone is entered in the ISO UTC format within the request body?
I am using pydantic within FastAPI and I need to ensure that the timestamp is always entered in the UTC ISO format such as 2015-09-01T16:09:00:000Z. from typing import Optional from fastapi import FastAPI from pydantic import BaseModel, Field from datetime import datetime app = FastAPI() measurements = [ { "timestamp": "2015-09-01T16:09:00:000Z", "temperature": 27.1, "dewPoint": 16.7, "percipitation": 0 }, { "timestamp": "2016-09-01T16:09:00:000Z", "temperature": 21.3, "dewPoint": 12.3, "percipitation": 1.5 } ] class MeasurementIn(BaseModel): timestamp: datetime temperature: Optional[float] dewPoint: Optional[float] percipitation: Optional[float] @app.post("/measurements") async def create_measurement(m: MeasurementIn, response: Response): measurements.append(m) The above code is working but it is also accepting datetime in other formats. I want to strictly restrict it to UTC ISO Format. I have tried to change the timestamp to timestamp: datetime.utcnow().isoformat() but it is not working. -
how can i connect my google sql postgres to my django application?
I have create my google postgres instance on cloud sql service, and i couldn't connect it with my django application, in the link below they give sqlalchemy configuration, but nothing about the database host [cloud.google](https://cloud.google.com/sql/docs/postgres/connect-admin-proxy#debianubuntu ) This is my database credentials # GCP DATABASE CREDENTIALS DB_NAME=db_name DB_HOST= *** DB_PORT=5432 DB_USER=db_user DB_PASSWORD=password Not sure about the DB_HOST, i tried the public ip address of my db and it not working i got this error This is my Django settings : DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ.get("DB_NAME"), "USER": os.environ.get("DB_USER"), "PASSWORD": os.environ.get("DB_PASSWORD"), "HOST": os.environ.get("DB_HOST"), "PORT": os.environ.get("DB_PORT") # default postgres port } } -
How I can create fields into a model in dependence of another one?
I'm learning Django and I'm working in a test project. So in my models.py I have this (I know that is wrong but I don't know how to do that): from django.db import models class Diagram(models.Model): name = models.CharField(max_length=100) img = models.ImageField(upload_to='img/diagrams/', help_text="Size required: height = 1050px, width = 1506px.", max_length=None) def __str__(self): return self.name class DiagramReferences(Diagram): quantity_of_references = models.IntegerField() for i in range(quantity_of_references): title = models.CharField(max_length=50) coords = models.CharField(max_length=50) So I want to make a relation between both models, the first: Diagram contains the name of the Diagram and the respective image. In the other I want to select the first which was already created and assign him how many references it has and create a field for each reference. -
How to fix heroku h10 error for my deployed app
This is the error my heroku logs show anytime I run my app 2022-11-09T16:52:49.620009+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-11-09T16:52:49.620009+00:00 app[web.1]: mod = importlib.import_module(module) 2022-11-09T16:52:49.620009+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/init.py", line 127, in import_module 2022-11-09T16:52:49.620010+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-11-09T16:52:49.620010+00:00 app[web.1]: File "", line 1030, in _gcd_import 2022-11-09T16:52:49.620010+00:00 app[web.1]: File "", line 1007, in _find_and_load 2022-11-09T16:52:49.620010+00:00 app[web.1]: File "", line 984, in _find_and_load_unlocked 2022-11-09T16:52:49.620011+00:00 app[web.1]: ModuleNotFoundError: No module named 'dlcfogbomoso.wsgi' 2022-11-09T16:52:49.620081+00:00 app[web.1]: [2022-11-09 16:52:49 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-11-09T16:52:49.644507+00:00 app[web.1]: [2022-11-09 16:52:49 +0000] [10] [INFO] Booting worker with pid: 10 2022-11-09T16:52:49.647154+00:00 app[web.1]: [2022-11-09 16:52:49 +0000] [10] [ERROR] Exception in worker process 2022-11-09T16:52:49.647155+00:00 app[web.1]: Traceback (most recent call last): 2022-11-09T16:52:49.647156+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-11-09T16:52:49.647156+00:00 app[web.1]: worker.init_process() 2022-11-09T16:52:49.647156+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-11-09T16:52:49.647156+00:00 app[web.1]: self.load_wsgi() 2022-11-09T16:52:49.647157+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-11-09T16:52:49.647157+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-11-09T16:52:49.647157+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-11-09T16:52:49.647157+00:00 app[web.1]: self.callable = self.load() 2022-11-09T16:52:49.647158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-11-09T16:52:49.647158+00:00 app[web.1]: return self.load_wsgiapp() 2022-11-09T16:52:49.647158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-11-09T16:52:49.647158+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-11-09T16:52:49.647159+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-11-09T16:52:49.647159+00:00 app[web.1]: mod = importlib.import_module(module) 2022-11-09T16:52:49.647159+00:00 app[web.1]: File … -
create a django serializer to create three model instance at once
{ "product_name": "CRVRVgfhghg", "product_price": "0.01", "product_location": "KIKUYU,KENYA", "product_description": "VFVFVFVFVFVF", "product_category_name": "livestock", "product_farmer_name": "james", "product_category_data": { "product_category_name": "livestock", "product_category_description": "livestock one" }, "product_product_file_data": { "product_file_name": "ok" } } i have three tables: product_category,product and product_product_files...what i want is to populate all the three tables at once using one view and url pattern... is there a way i can do this using serializers?? -
How can I refactor my code to clear off - "local variable 'data' referenced before assignment"
My code returns is intended to return queryset based on selected dates or months however these two are almost similar yet only one works. Here is my both forms.py class DateInput(forms.DateInput): input_type = 'date' class MonthInput(forms.DateTimeInput): input_type = 'month' class DateRangeInputForm(forms.Form): start = forms.DateField(widget=DateInput()) end = forms.DateField(widget=DateInput()) class MonthRangeInputForm(forms.Form): start = forms.DateField(widget=MonthInput()) end = forms.DateField(widget=MonthInput()) This is the query view that works. def milk_records_range_per_day(self, request): if request.method == "POST": form = forms.DateRangeInputForm(request.POST) if form.is_valid(): data = (models.Milk.objects.filter(milking_date__date__range=( form.cleaned_data['start'], form.cleaned_data['end'])) .annotate(date=functions.TruncDate("milking_date")) .values("date") .annotate(amt=Sum('amount_in_kgs'))) labels = [c['date'].strftime("%d-%m-%Y") for c in data] values = [x['amt'] for x in data] ....... Though this one throws a reference error : local variable 'data' referenced before assignment def milk_records_range_per_month(self, request): if request.method == "POST": form = forms.MonthRangeInputForm(request.POST) if form.is_valid(): data = (models.Milk.objects.filter(milking_date__month__range=( form.cleaned_data['start'],form.cleaned_data['end'])) .annotate(month=functions.TruncMonth("milking_date")) .values("month") .annotate(amt=Sum('amount_in_kgs'))) labels = [c['month'].strftime("%m-%Y") for c in data] values = [x['amt'] for x in data] ..... Model: class Milk(models.Model): amount_in_kgs = models.PositiveIntegerField(validators=[MinValueValidator(0), MaxValueValidator(50)]) milking_date = models.DateTimeField(auto_now_add=True) ... -
APIView PUT request being handled as a GET request
I'm building an APIView to handle a PUT request for a model with choicefields as input. Originally, I created a GET and PUT definition for my APIView class, however when my build is deployed, my PUT request is being received as a GET request! On my dev deployment, the request is received as a PUT request every time. When I move it to a production deployment however, the only times I can get the request to properly send a PUT request is by using Postman. When I try any other way the request is received as a GET request. Removing the definition of GET from my APIView does not help, it simply returns a 405 method not allowed. I've looked around and don't seem to see any other people with this issue. What could cause a request to be misinterpreted like this? Where would be a good place to start looking? Can I force the use of PUT at this endpoint? In the meantime I'm going to try moving from APIView to one of the specific generics mixins to see if this resolves my issue. -
How to allow boolean True on just one model in table in Django?
I've got a model where I would like there to be able to have one set as the 'app default'. In this model I added a field named is_app_default in order to help accommodate this. class TreeLevel(models.Model): id = models.BigAutoField(primary_key=True) short_description = models.CharField(max_length=200) long_description = models.TextField() is_app_default = models.BooleanField(default=False) class Meta: verbose_name = "Tree Level" verbose_name_plural = "Tree Levels" class Layer(models.Model): id = models.BigAutoField(primary_key=True) tree_levels = models.ManyToManyField(TreeLevel) description = models.TextField() class Meta: verbose_name = "Layer" verbose_name_plural = "Layers" The Layer model links to TreeLevel with an m2m. Ultimately I would like the is_app_default TreeLevel automatically added to every Layer m2m relationship - which is why there can only be one TreeLevel with is_app_default set as True. My potential solution(s): Users with admin may be creating new TreeLevel objects - so I need to make sure they aren't setting that Boolean in any new models. I think I can override the save() method on TreeLevel to check the DB to see if another with that boolean as True exists - if so? Don't save the 'new' one and return an error. But I think this hits the database - causing unnecessary queries potentially? Then additionally, I would also need to override … -
how to define the environment variable DJANGO_SETTINGS_MODULE?
I am trying to chainedForeignKey using https://django-smart selects.readthedocs.io/en/latest/installation.htmland i got following error : ` django.core.exceptions.ImproperlyConfigured: Requested setting USE_DJANGO_JQUERY, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. ` your text``from django.db import models your textfrom smart_selects.db_fields import ChainedForeignKey Create your models here. your textclass City(models.Model): your textname = models.CharField(max_length = 25, null = True) your textclass Area(models.Model): your textname = models.CharField(max_length = 25, null = True) your textcity = models.ForeignKey(City, on_delete = models.CASCADE) your textclass Store(models.Model): your textstore = models.CharField(max_length = 50) your textcity = models.ForeignKey(City, on_delete = models.CASCADE) your textarea = ChainedForeignKey(Area, chained_field='city', chained_model_field= 'city') -
select instances in manaytomany field using django rest
I'm trying to build a friend add system using Django Rest And these are my codes #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) pic = models.ImageField(upload_to="img", blank=True, null=True) friends = models.ManyToManyField('Friend', related_name = "my_friends" , blank=True , null=True) def __str__(self): return self.user.username class Friend(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE) def __str__(self): return self.profile.user.username #serializers.py class FriendSerializer(serializers.ModelSerializer): class Meta: model = Friend fields = ('profile',) class ProfileSerializer(serializers.ModelSerializer): friend = FriendSerializer(many=True, read_only=False) class Meta: model = Profile depth = 3 #this is return foreinkey name instead of id fields = "__all__" def update(self, instance, validated_data): friends_data = validated_data.pop('friend') instance = super(ProfileSerializer, self).update(instance, validated_data) for friend_data in friends_data: friend_qs = Friend.objects.filter(profile = friend_data['profile']) if friend_qs.exists(): friend = friend_qs.first() else: friend = Friend.objects.create(**friend_data) instance.friend.add(friend) return instance #views.py class UserProfile(RetrieveUpdateDestroyAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class UserFriends(RetrieveUpdateDestroyAPIView): queryset = Friend.objects.all() serializer_class = FriendSerializer #urls.py urlpatterns = [ path('' , ArticleList.as_view() , name = 'list'), #we used as_view() cause we used class based views path('<int:pk>' , ArticleDetail.as_view() , name = 'detail'), path('users/' , UserList.as_view() , name = 'user-list'), path('users/<int:pk>' , UserDetail.as_view() , name = 'user-detail'), path('profile/<int:pk>' , UserProfile.as_view() , name = 'user-profile'), ] My intention is to send a json like this -> … -
How to filter queryset from inside the serializer?
I want to always apply a filter to a serializer (filter the queryset). lets say I have: class Company(models.Model): name = models.CharField(max_length=90, unique=True) city = models.CharField(max_length=90,) active = models.BooleanField(default=True) class CompanySerializer(serializers.ModelSerializer): class Meta: model=Company fields=['id', 'name', 'city'] so when I call the serializer for a list filtered by city (or any other fields added in my real code) as shown below it returns Companies from that city and only "active=True" query_set = Company.objects.filter(city=request.POST(city) ) srl = serializers.CompanySerializer(query_set, many=True) return Response(srl.data) because I may want to call the serializer from other parts of the code. and I want to keep the records for reference but never show to any client. I have tryed to modify the queryset from from init but it does not work. I actually print() the modified queryset to make sure it was filtered and it prints the filtered queryset, I do: def __init__(self, instance=None, data=empty, **kwargs): instance.filter(active=False) self.instance = instance print(self.instace) #this prints the filtered queryset OK but it sends the response without the "active=False" filter. -
SEO in django template project
I'm new in django, I'm working on a djanog project and i want to render dynamic meta tags foe SEO and titles for every page in it, but i don't know how can it can help please I want it to be something like this: <title>Veb-studiya bilan aloqa - Eson</title> <meta name="description" content="Veb-studiya Eson - bu professional veb-studiya. Biz o&#039;z ishimizni sevamiz va sizning internet tarmog&#039;idagi biznesingizni rivojlantiriramiz. " /> <meta name="robots" content="index, follow" /> <meta name="googlebot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1" /> <meta name="bingbot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1" /> <link rel="canonical" href="https://eson.uz/aloqalar/" /> <meta property="og:locale" content="uz_UZ" /> <meta property="og:locale:alternate" content="ru_RU" /> <meta property="og:type" content="article" /> <meta property="og:title" content="Veb-studiya bilan aloqa - Eson" /> <meta property="og:description" content="Veb-studiya Eson - bu professional veb-studiya. Biz o&#039;z ishimizni sevamiz va sizning internet tarmog&#039;idagi biznesingizni rivojlantiriramiz. " /> <meta property="og:url" content="https://eson.uz/aloqalar/" /> <meta property="og:site_name" content="Eson" /> <meta property="article:publisher" content="https://www.facebook.com/netsonuz" /> <meta property="article:modified_time" content="2022-01-10T07:20:26+00:00" /> <meta name="twitter:card" content="summary_large_image" /> <script type="application/ld+json" class="yoast-schema-graph">{"@context":"https://schema.org", -
Python: Basic OCR / Image to Text library
I have a very simple use case for OCR. .PNG Image then extract the text from the image. Then print to console. I'm after a lite weight library. I am trying to avoid any system level dependency's. Pytesseract is great, but deployment is a bit annoying for such a simple use case. I have tried quite a few of them. They seem to be designed for more complex use cases. Note: White text is not necessarily suitable for OCR. I will change the image format to suit the OCR Library. -
How to create a python listener microservice with flask
I need to build a listener microservice that is going to listen to events through a websocket and I had been assigned to do this task with python+flask. I worked before with Django and I know i can create a command that is always running, but i don't see any documentation about doing something similar with Flask. What i want is understand how to build a flask+python application that is always up and running listening for some events. Any ideas? -
How to host Django Channels (ASGI) with amazon_ec2?
The REST endpoints work completely fine, but the WS endpoints aren’t even registered as WS connection attempts. When I connect to wss://lms-backend-wiomf.ondigitalocean.app/ws/teacher/, it shows [lms-backend] [2021-07-05 03:51:44] Not Found: /ws/teacher/ [lms-backend] [2021-07-05 03:51:44] 10.244.59.39 - - [05/Jul/2021:03:51:44 +0000] "GET /ws/teacher/ HTTP/1.1" 404 2560 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" how can I successfully host my asgi application on aws-ec2 any one plz help -
Can anyone suggest me a best Logging System for my applications?
I am trying to implement a log system in my flask and django apps. I don't want to store it in a text document. Because these files are keep on storing all the logs and at some stage I can not open/read them because of the larger size. Is there any other way to have a log system apart from this? -
How to run a process in Django view without "Apps aren't loaded yet" error?
In Django view, I'm trying to run a process as shown below. *I use Django 3.1.7: # "views.py" from multiprocessing import Process from django.http import HttpResponse def test(): print("Test") def test(request): process = Process(target=test) process.start() process.join() return HttpResponse("Test") But, I got this error below: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. So, I put the code below to settings.py to solve the error above following this solution: # "settings.py" import django django.setup() But, another error below is raised even though my SECRET_KEY setting is not empty: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. So, how can I run a process in Django view without Apps aren't loaded yet error: -
No module named 'core' django app deployed in Railway
Hi i'm having this error when i'm trying to make a post through admin, everything else works fine except for this module error. Let me be clear i'm a complete newbie, but i think that maybe is path problem?, but i don't know how to modified or change it while is hosted on Railway. my requirements.txt asgiref==3.5.2 boto3==1.26.4 botocore==1.29.4 Django==4.1.2 django-cors-headers==3.13.0 django-crispy-forms==1.14.0 django-environ==0.9.0 django-storages==1.13.1 environ==1.0 gunicorn==20.1.0 jmespath==1.0.1 Pillow==9.2.0 psycopg2==2.9.5 python-dateutil==2.8.2 s3transfer==0.6.0 six==1.16.0 sqlparse==0.4.3 tzdata==2022.5 urllib3==1.26.12 my procfile: web: gunicorn proyecto_web.wsgi --log-file - Change the path on virtual environment but i don't know how. -
Django Verbatum like template tag to show verbatim and rendered nodes
I am trying to make a template tag that will show a section of code verbatim, and also render it, it is to help me demo some code for my own tooling. Say I have this in a template: {% example %}import * as fancy from "{% static 'jslib/fancy.min.js' %}";{% endexample %} I wish to output it as (I will add some divs and styling, but this is distilling the problem into it's simplest form): import * as fancy from "{% static 'jslib/fancy.min.js' %}"; import * as fancy from "/static/jslib/fancy.min.js"; I looked at the django {% verbatum %} tag and tried to copy the logic: # django.template.defaulttags.py @register.tag def verbatim(parser, token): nodelist = parser.parse(('endverbatim',)) parser.delete_first_token() return VerbatimNode(nodelist.render(Context())) nodelist.render(Context()) prints out text nodes for the django verbatim tag, but if I copy the code my example tag prints out say StaticNodes and other types of nodes. The reason why is I think the django parser has some special checks to see if it is a verbatim node and handles if differently, as shown in the code below: # django.template.base.py -> def create_token if self.verbatim: # Then a verbatim block is being processed. if content != self.verbatim: return Token(TokenType.TEXT, token_string, position, lineno) … -
Django does not recognize my {% endblock %} tag in the html file
I get this error while trying to run my Django project: "Invalid block tag on line 7: 'endblock'. Did you forget to register or load this tag?" I am trying to make a base-template (base.html) and use it on my html file (index.html). The name of my Django project is "mysite", the name of the app in my Django project is "myapp" It looks like Django does not recognize my {% endblock %} tag, but i don't know why. This is the base-template file (base.html): {% load static %} <html lang="en"> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet", href="{% static 'myapp/style.css' %}"> <title>Document</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button … -
How to create order in admin after payment is completed
I'm making a website where you buy stuff and pay through PayPal. I am done with the PayPal part now I am trying to get a situation where after the payment is complete in checkout the item purchased goes to orders in the admin. This is the order model.py: class Order (models.Model): product = models.ForeignKey(Coinpack, max_length=200, null=True, blank=True, on_delete = models.SET_NULL) created = models.DateTimeField(auto_now_add=True) this is the PayPal code part in checkout.html: <script src="https://www.paypal.com/sdk/js?client-id=idexample&currency=USD"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var total = '{{checkout.price}}' var productId = '{{checkout.id}}' function completeOrder(){ var url = "{% url 'complete' %}" fecth(url, { method: 'POST', headers:{ 'content-type':'aplication/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'productId':productId}) }) } // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: total } …