Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not Found: /1/${url}data
I want to show a list of question on my quiz.html templates... Here is my views.py def quiz_data_view(request,pk): quiz = Quiz.objects.get(pk=pk) questions = [] for q in quiz.get_questions(): answers = [] for a in q.get_answers(): answers.append(a.text) questions.append({str(q):answers}) return JsonResponse({ 'data' : questions, 'time' : quiz.time, }) Here is my js file...in my js file i used ajax... const url = window.location.href const quizBox = document.getElementById('quiz-box') let data $.ajax({ type: 'GET', url: "${url}data", success : function(response){ // console.log(response) data = response.data data.forEach(el=>{ for(const [question,answers] of Object.entries(el)){ quizBox.innerHTML +=` <hr> <div class="mb-2"> <b> ${question}</b> </div> ` } }); }, error : function(error){ console.log(error) } }) here is my urls.py from django.urls import path from .views import ( QuizListView,quiz_view,quiz_data_view ) app_name='quizes' urlpatterns = [ path('',QuizListView.as_view(),name='main-view'), path('<int:pk>/',quiz_view,name='quiz-view'), path('<int:pk>/data/',quiz_data_view,name='quiz-data-view'), ] Here is my models.py from django.db import models # Create your models here. DIFF_CHOICE = ( ('easy','easy'), ('medium','medium'), ('hard','hard'), ) class Quiz(models.Model): name = models.CharField(max_length=120) topic = models.CharField(max_length=120) number_of_question = models.IntegerField() time = models.IntegerField(help_text="Duration in Minutes") required_score_to_pass = models.IntegerField(help_text="Required Score to Pass in %") difficulty = models.CharField(max_length=6,choices=DIFF_CHOICE) def __str__(self): return f"{self.name}-{self.topic}" def get_questions(self): self.question_set.all()[:self.number_of_question] class Meta: verbose_name_plural = 'Quizes' and here is my quiz.html....and here i want to show my question list {% extends "base.html" … -
How can I reuse a DRF class-based views POST method?
Now I want to reuse the post method of BundleList. Either I find out the absolute URL and use requests.post(URL) to send a request. The 2nd way is to reuse by return BundleList.as_view()(request) in a view function. But I can't set request.data = data. Request data is immutable. When I try to use url = reverse_lazy(BundleList.as_view(), request=request) print(f"{url = }") It just gives me: NoReverseMatch at /generateSampleBundle/ Reverse for 'my_app.views.BundleList' not found. 'my_app.views.BundleList' is not a valid view function or pattern name. The BundleList is a class-based view with get and post method. drfurlpatterns = [ # DRF URL endpoints path('bundles/', views.BundleList.as_view()), ] Can anyone help me out? -
why am I not able to see data with older date in my django project?
I have written a small views through Django rest framework to populate database table data in between two different date range. Below is the code snippet: from rest_framework.generics import ListAPIView from rest_framework import permissions from .models import Revenue from .serializers import DataListSerializers import datetime class DataListView(ListAPIView): serializer_class = DataListSerializers pagination_class = None queryset = Revenue.objects.all() permission_classes = [permissions.AllowAny] def get_queryset(self): start_date = datetime.date.today() end_date = start_date + datetime.timedelta(days=6) time_filter = self.queryset.filter(date__range=(start_date, end_date)) ser = DataListSerializers(time_filter, many=True).data return ser After this I have manually entered the data in the database through admin page. So, those data are of current date. Now, I imported a CSV file in the SQLite which has data from the year 2017, and the file was uploaded successfully. There after when I refreshed the admin page, it crashed and I could see error as shown below: return datetime.date(*map(int, val.split(b"-"))) ValueError: day is out of range for month With this I assume that the over ridden logic written in the 'get_queryset' method is not optimal. Please suggest the optimal solution for the use case. Thank you. -
Chrome extension requests with CSRF token
I have an extension that makes requests through the background page to my django server. I need to include the CSRF token for any POST requests, however when I do that I still get 403 error, because there is no Referer header in the request. Now I know the Referer header is set automatically by the browser, but in case of extension background page it is not set at all. There are two workarounds for this: using CSRF exempt on django or blocking the request to set the Referer header in the extension (using webRequestBlocking permissions), but I don't want to use either of them. Is there anything else I can do to resolve this either on client or server side? -
How do I overcome this? [closed]
Used to have a project which has been completed and deleted from my machine. Anytime I start a new project and run the server, the urls references the urls in the old project which has been deleted throwing an error in my current project. How do I fix this? -
I am having problem with the django and constantly getting error i.e. "local variable 'form' referenced before assignment"
I am having this error "local variable 'form' referenced before assignment". I am not sure what's wrong with the code . The form does not load and the if the form is assigned to different variable and used then the page loaded but the form does not load The model class from django.db.models.aggregates import Max from django.db.models.base import Model from django.db.models.fields import CharField # Create your models here. class Work(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='workimages/') summary =models.CharField(max_length=100) def __str__(self): return self.name class Contact(models.Model): name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=50, null=True) message = models.CharField(max_length=1000, null= True) def __str__(self): return self.name the view fucntion of the problem is posted below from .models import * from .forms import * # Create your views here. def home (request): work = Work.objects.all() if request.method == "POST": form = Contactform(request.POST or None) if form.is_valid(): form.save() context ={ 'work':work,'form':form,} return render(request, 'mysite/index.html',context) The template <form method="POST"> {% csrf_token %} <div class="row margin-bottom-small center-xs"> <div class="col-md padding-small"> {{ form }} </div> <div class="col-md padding-small"> <!-- <textarea placeholder="Your Message" name="" rows="8" class="margin-bottom-small"></textarea> --> <input type="submit" value="Submit"> </div> </div> </form> This default django forms in used bu from django import forms from django.db.models import fields from django.forms.forms import … -
pass custom queryset to django rest framework nested serializer
I have serializers in the following format: CounterPartyCompanySerializer: class CounterPartyCompanySerializer(serializers.ModelSerializer): class Meta: model = ClientCompany fields = ( "id", "company_name", "address_line1", ) extra_kwargs = { "id": { "read_only": False, "required": False, }, } CounterPartySerializer: class CounterPartySerializer(serializers.ModelSerializer): company = CounterPartyCompanySerializer() class Meta: model = Client fields = ( "id", "company", "client_name", ) extra_kwargs = { "id": { "read_only": False, "required": False, }, } and GiftAndEntertainmentSerializer: class GiftAndEntertainmentSerializer(serializers.ModelSerializer): counter_party = CounterPartySerializer() class Meta: model = GiftAndEntertainment fields = ( "id", "gift_type", "receipt_type", "counter_party", "value", ) Case-I :: It works when I do the following: result_list = GiftAndEntertainment.objects.all() serializer = GiftAndEntertainmentSerializer( result_list, many=True, context={"request": request} ) But, it doesn't work when I pass the custom queryset like: result_list = GiftAndEntertainment.objects.values( "gift_type", "receipt_type", "counter_party", "value" ).annotate( total=ExpressionWrapper(Sum("value"), output_field=DecimalField()) ) serializer = GiftAndEntertainmentSerializer( result_list, many=True, context={"request": request} ) Here, "gift_type","receipt_type" and "counter_party" are ForeignKey mapped entities and the queryset passes the primary-key id of these entities. I thought the serializer will convert the pk to its corresponding entities like its doing in the case-I but that is not happening automatically. Any help here would save my life. I have spent an entire day trying to achieve this but failed every-single time. -
Django filters for a ManyToMany field
I'm trying to build a filtering system for a list of posts. All the posts have an author/user and an account where they are posted. The post model has 2 ForeignKeys with the Author/User model and with Account model. The Author/User model has a ManyToMany relationship with the List model (the list model is like tags, categories, etc. for the users, and a user can belong to multiple lists at the same time). I want to filter the posts by lists, for example, I want to filter all the posts that belong to users who belong to the "Cars" list or the "Cars and Family" list at the same time (here I'm trying to say that I'd like to filter posts by one list or more, like to show all the posts that belong to users who belong to "Cars" list, or to "Cars and Family" lists). I'm not sure how can I filter a QuerySet of a model by a ManyToMany field of a ForeignKey field. I'll put my models, filters, views, and HTML to show what I've made so far. models.py # List model represents the lists that will hold the authors/users grouped and will be used for … -
EOF while scanning triple-quoted string literal while creating a TextField value for a django model. (how to correctly concat strings)
this is the model i am creating: class Notification(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="notifications") text = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) The "text" field is giving me issues. This is how i am trying to create an instance: Notification.objects.create(user=instance.post.owner, text=instanse.user.username + ' liked your post') "instance.user.username" is a CharField. What is the correct way of adding that to a string? -
contents in <form> tag is not displayed in server
I'm learning django framework currently. Everything went well till last night. From this morning the contents inside the <form> tag is not being displayed once the page is rendered through django code. Till last night it was working good and I didn't manipulate the code. I tried restarting the server many times, it didn't help. I opened the .html externally (not from django), it works fine, but not through django. Part of html code goes as, <div class="w3-top"> <div class="w3-bar w3-white w3-padding w3-card" style="letter-spacing:4px;"> <a href="#home" class="w3-bar-item w3-button">A simple TO-DO list using Django</a> <!-- Right-sided navbar links. Hide them on small screens --> <div class="w3-right w3-hide-small"> <a href="#about" class="w3-bar-item w3-button">About</a> <a href="#contact" class="w3-bar-item w3-button">Contact</a> </div> <div class="w3-right w3-hide-small"> <form action="enter/login"> <input type="submit" class="w3-bar-item w3-button" value="Login"/> </form> </div> </div> </div> and the result of this is, The Login button is missing which is inside the form, I found the Login button till last night and I can't find this from this morning. This is a single example and I have 3 <form> tags in my page and nothing is displayed when I run this in the localhost server. But externally this works good. -
Django urls.py update from using url to path
I am importing and upgrading a legacy Django app into my Django 3.2 project. The old app used Django 1.x url, I need to upgrade, using path instead. Here is the old code: urlpatterns = patterns( 'blog.views', url(r'^$', 'blogs', name='blogs_url'), url(r'^new-post$', 'new_blog_post', name='new_blog_post_url'), url(r'^upload-image$', 'upload_image', name='upload_image_url'), url(r'^uploaded-images$', 'uploaded_images', name='uploaded_images_url'), url(r'^edit/(\d+)/([^/]+)$', 'edit_blog_post', name='edit_blog_post_url'), url(r'^([^/]+)$', 'blog', name='blog_url'), url(r'^([^/]+)/(\d+)/([^/]+)$', 'blog_post', name='blog_post_url'), ) urlpatterns += patterns('', url(r'^(?P<blog_slug>[^/]+)/rss$', AllPostsFeed(), name='blog_rss_url')) Here is my changed code: urlpatterns = [ path('', blogs, name='blogs_url'), path('new-post', new_blog_post, name='new_blog_post_url'), path('upload-image', upload_image, name='upload_image_url'), path('uploaded-images', uploaded_images, name='uploaded_images_url'), path('edit/(\d+)/([^/]+)', edit_blog_post, name='edit_blog_post_url'), path('([^/]+)', blog, name='blog_url'), path('([^/]+)/(\d+)/([^/]+)', blog_post, name='blog_post_url'), path('(<slug:blog_slug>[^/]+)/rss', AllPostsFeed(), name='blog_rss_url') ] Although, I have removed most of the regex patterns (at least those starting or terminating strings, there are still remaining (e.g. from the edit/* route onward). What would be the correct parameter formulation for these (potentially incorrect) lines?: path('edit/(\d+)/([^/]+)', edit_blog_post, name='edit_blog_post_url'), path('([^/]+)', blog, name='blog_url'), path('([^/]+)/(\d+)/([^/]+)', blog_post, name='blog_post_url'), path('(<slug:blog_slug>[^/]+)/rss', AllPostsFeed(), name='blog_rss_url') -
I keep getting 403 respose error. I'm using django restframework with customized authentication method
Inspecting the header from postman i notice, the allowed method does not include the POST. I'm unable to make request for unauthenticated routes, i get 403. serializer_class = LoginSerializer permission_classes = [permissions.AllowAny] def post(self, request, *args, **kwargs): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: user = User.objects.get(email=request.data['email']) if user.check_password(request.data['password']): serialized_user = UserSerializer(user).data access_token = generate_access_token(user) return Response(data={'access_token': access_token, 'user': serialized_user}, status=status.HTTP_200_OK) else: return Response({'errors': 'Invalid credentials'}) except User.DoesNotExist: return Response({'errors': 'No user with such email!'})``` Here is a screenshot showing the postman header response. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/jEf0E.png -
How can I convert Inner Join and Group By to Django ORM?
I want to change this raw SQL to Django ORM but I couldn't manage to convert. most_read_students = LendedBook.objects.raw('SELECT student_id as id, name, surname, COUNT(*) as count FROM "Book_lendedbook" INNER JOIN User_student on Book_lendedbook.student_id=User_student.id where did_read=1 group by student_id order by count DESC LIMIT 5')` I tried this and I get close result.But unfortunately, I couldn't do what I want. Because I want to join this table with another table. most_read_students = LendedBook.objects.values('student_id').filter(did_read=True, return_date__month=(datetime.datetime.now().month)).annotate(count=Count('student_id')) When I use select_related with "User_student" table like this; most_read_students = LendedBook.objects.select_related('User_student').values('student_id', 'name', 'surname').filter(did_read=True, return_date__month=(datetime.datetime.now().month)).annotate(count=Count('student_id')) It throws an error like Cannot resolve keyword 'name' into field. Choices are: book, book_id, did_read, id, is_returned, lend_date, return_date, student, student_id But I should be able to get student properties like name and surname when I join "User_student" table. Thank you for your help! -
Is there a simple way to know if login has failed Django?
I am currently using Django built-in login feature. I only made my own form as you can see on this image: Login page It is really basic. Only two inputs and some formatting: <form action="#" class="login-form" method="post"> <input type="text" class="form-control input-field" placeholder="Username" name="username" required> <input type="password" class="form-control input-field" name="password" placeholder="Password" required> </form> When I enter a correct username and password, everything works and I am redirected on the correct page, but when I enter a wrong password, the login page is just reloaded, and nothing tells me the password/username was incorrect. I understand that, no matter if the password is correct or incorrect, I am redirected on the main page, but when I am not logged in (so when the password is wrong), this main page redirects me on the login page (because it is on login required). Do you know if there is a simple way to detect if a login failed and display it ? -
overwrite a model in Django
I want to overwrite the tik_id by using the function randomId so that I can generate random unique id, how can i do this?? class Tickets(models.Model): category = models.CharField(max_length=20) price=models.IntegerField() tik_id = models.CharField(max_length=20, blank=True) qr_code = models.ImageField(upload_to='qrcodes', blank=True) def __str__(self): return str(self.tik_id) def randomId(self, *args, **kwargs): tikIdCode= ''.join(random.choice(string.ascii_letters+string.digits) for i in range(8)) -
Why the fields are not getting poped in django
I have created two(ModelA, ModelB) models in models.py. I want to pop the field poster_img from ModelB for ModelC in serializer.py. I have done some part of this. but when I redirected it with http://127.0.0.1:8000/modelposter/ then I am getting JSON output like given in file. But I am not getting poster_img value in JSON file like this. This is my views.py file. There is no error showing while redirecting with http://127.0.0.1:8000/modelposter/ How can I poped the poster_img fields from ModelB? -
Search filter not working in Rest framework
A search filter was working fine in this and there's a need to filter out the list with a user-defined distance and for that, a get function is written. Now, the filter is gone. It is appearing when I comment out the get functions. class ServiceProviderList(generics.ListAPIView): queryset = ProfileCompletion.objects.all() serializer_class=ProfilecompletioneSerializer filterset_class=SnippetFilter filter_backends = [DjangoFilterBackend,SearchFilter] filterset_fields = ['fullname', 'category','departments','services'] search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name'] def get(self,request,*args, **kwargs): pk=self.kwargs.get('pk') customer = CustomerProfile.objects.get(user=pk) Dist = request.GET.get("distance") rad=float(Dist) radius=rad/111 print(radius) query = ProfileCompletion.objects.filter(location__distance_lte=(customer.location,radius)) serializer = ProfilecompletioneSerializer(query,many=True) data = serializer.data return Response({"message":"Listed Successfully.","data":data}) -
Two layer cache implementation in django
My final goal is to have a two-layer cache for every function that I want (probably a self-implemented decorator is needed) I have multiple VMs running the same Django server. The first cache layer is memory, and the second layer is a shared Redis between VMs. The process works as follows, a function is decorated for two-layer caching. In the case of function calls, the server looks for the item inside its in-memory cache. if it couldn't find it, then it will check in the shared Redis. How can I achieve this? I already have this code snippet: from cachetools.func import ttl_cache from cache_memoize import cache_memoize @ttl_cache(maxsize=settings.A_NUMBER, ttl=settings.CACHE_TIMEOUT) @cache_memoize(settings.CACHE_TIMEOUT) def my_fucn(arg1, arg2): some logic here. Django settings: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': env.str('REDIS_MASTER'), } I read this (How to use 2 different cache backends in Django?) but I don't whether it's possible to use them as a decorator. Thanks! -
Query a Barcode in django model
I have created Barcodes in my model using the following format: "YNT" + str(pk).zfill(4) + str(i.item.pk).zfill(4) + str(j + 1).zfill(5) where pk id the GRN ID and it looks like the following example: YNT0103000500055 Now when I am scanning the barcode I want to check if the item actually exists or not for that I have done this: c = request.GET['code'] try: #len(YNT) = 3 #len(grn) = 4 #len(product) = 4 #len(serial) = 5 grn = int(c[3:7]) #103 product = int(c[7:11]) #5 serial = int(c[11:]) #55 print("grn", grn) print("grn", product) print("grn", serial) obj = Grn.objects.filter(pk=grn, items__item=product) print("obj.items.item_quantity", obj.items.item_quantity) if obj.items.item_quantity>serial: res = Product.objects.get(pk=product).description I am able to get the object but how do I check the serial count i.e. serial is less or equal than the quantity of that product in the GRN GRN Model: class GrnItems(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=0) item_price = models.IntegerField(default=0) label_name = models.CharField(max_length=25, blank=True, null=True) class Grn(models.Model): reference_no = models.CharField(max_length=500, default=0) inward_date = models.DateTimeField(blank=True, null=True) items = models.ManyToManyField(GrnItems) -
UnboundLocalError: local variable 'insert' referenced before assignment on server side
I am new to this StackOverflow, actually, I am built a keyword research application and it is running successfully on a local server but when I deployed it into the Cpanel i.e server side it is throwing me the error like : UnboundLocalError: local variable 'insert' referenced before assignment: def funcurlscrpping(url): urldata = requests.get(url) soup = BeautifulSoup(urldata.content, "html") title = soup.title.string print ('TITLE IS :', title) meta = soup.find_all('meta') for tag in meta: if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['keywords']: insert = tag.attrs['content'] print(insert) data = insert.split(',') return data def funcurlscrppingwithkeyword(ids): for id in ids: videourl= 'https://www.youtube.com/watch?v='+ id urldata = requests.get(videourl) soup = BeautifulSoup(urldata.content, "html") title = soup.title.string print ('TITLE IS :', title) meta = soup.find_all('meta') for tag in meta: if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['keywords']: insert1 = tag.attrs['content'] print(insert1) data1 = insert1.split(',') return data1 def GetTags(request): if request.method == 'GET': url = request.GET['query'] type = request.GET['type'] valid=validators.url(url) if valid==True: obj1=[] obj1 = funcurlscrpping(url) if type == 'YouTube': return JsonResponse({"tags": obj1}, status=200) else: res = ['#' + x for x in obj1] return JsonResponse({"tags": res}, status=200) else: search_url = 'https://www.googleapis.com/youtube/v3/search' params = { 'part': 'snippet', 'q':url, 'key' : settings.YOUTUBE_DATA_API_KEY, 'maxResults' : 2, } video_ids = [] r … -
Instagram follower count.. Why is there no reliable way?
A task I've been wanting to finish for awhile is to have a dashboard where you'll have a little Instagram logo with a number which is your follower count. This means I need the latest follower count everytime the user loads the page. I have had it working before with Beautiful Soup but it was heavy and ended up getting blocked. Why is there no way to simply get the follower count of an Instagram page (not necessarily my own)? Here I have my latest attempt. I did not know you can add /?__a=1 to the url and get JSON data about the account! This works if I request the page in the browser but as soon as I implement it with requests I get a 429 status code (too many requests) import requests response = requests.get('https://www.instagram.com/nike/?__a=1') print(response.status_code) # 429 # print(response.json()) # Expecting value: line 1 column 1 (char 0) -
Heroku django3.2 deployment broken /admin menu, all routes are working for normal users except for /admin, CollectStatic not working for heroku-live
I have seen/debugged/referred multiple blogs and Stackoverflow's answers and tried almost all, but I am not able to see the admin dashboard with proper UI, as static files(CSS here) are not loaded. My Project structure is main project is bookMyTicket and I created model/subapp as bookings. I have a git repository here and the project works fine locally, with Postgres, and even on the live server except for the /admin menu. For users, live app works fine as: Github-link, Running demo Locally I did set up properly static files then checked heroku local first and had same issue. So, I did run python manage.py collect static and it created around 130+ CSS files in staticfiles directory, to make it work locally for /admin, I tried doing same on live using command: heroku run python bookMyTicket/manage.py collectstatic but it gave error as : FileNotFoundError: [Errno 2] No such file or directory: '/app/bookMyTicket/static' I tried adding whitenoise in the middleware list: 'whitenoise.middleware.WhiteNoiseMiddleware' Database config is: DATABASES = { 'default': { "ENGINE": "django.db.backends.postgresql", 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '' } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) I have declared static root too and static url. STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, … -
how to properly write urls.py in django 3.2?
I knew there is so many question and solution about how to properly writing urls.py dan views.py But still I can not solve my problem. my django version is 3.2 Here is my project urls.py from django.contrib import admin from django.urls import path, include admin.site.site_header = 'Catat Kolam' admin.site.site_title = 'CatatKolam' urlpatterns = [ path('admin/', admin.site.urls), path('catatkolam', include('catatkolam.urls')), ] Here is my app's urls.py from django.urls import path from . import views urlpatterns = [path('helloworld', views.helloworld , name='helloword')] Here is my views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def helloworld(request): return HttpResponse("Hello world") But still I got Using the URLconf defined in proj.urls, Django tried these URL patterns, in this order: admin/ [name='index'] admin/ login/ [name='login'] admin/ logout/ [name='logout'] admin/ password_change/ [name='password_change'] admin/ password_change/done/ [name='password_change_done'] admin/ autocomplete/ [name='autocomplete'] admin/ jsi18n/ [name='jsi18n'] admin/ r/<int:content_type_id>/<path:object_id>/ [name='view_on_site'] admin/ auth/group/ admin/ auth/user/ admin/ catatkolam/konfig/ admin/ catatkolam/kolam/ admin/ catatkolam/bahandasar/ admin/ catatkolam/bahancampuran/ admin/ catatkolam/tebar/ admin/ catatkolam/monitoring/ admin/ ^(?P<app_label>auth|catatkolam)/$ [name='app_list'] admin/ (?P<url>.*)$ The current path, admin/catatkolam/helloworld, matched the last one. Kindly please give me any clue to fix ths problem Sincerely bino -
I am working with django authentication and got fascinated by the hidden field in login form, can someone explains how the below line of code works?
<form action="{%url 'login'%}" method="POST"> {%csrf_token%} {%bootstrap_form form%} <input type="submit" class="btn btn-success" name="" id=" value="login"> <input type="hidden" name="next" id="" value="{{}}"> </form> I know that the URL contains the next keyword storing our previous path but I am just curious how this form influence it and btw i used loginrequiredmixin for authorization. -
Slicing geometry with geodjango based on another geometry
I have a PostgreSQL database set up and am using Geodjango to interact with the geometry saved in this database. My use case is as follows: In the database I have a complicated, large multi-polygon containing all the parks in the country. This is contained in a single geometry field. I have another record that contains the boundaries of my region. What I want to do is somehow truncate/slice the multi-polygon so that it removes those that are not within the boundaries. Sample code: region = Shapefile.objects.get(pk=1) region_boundaries = region.geometry # this contains the boundaries for the region all_parks_in_country = Shapefile.objects.get(pk=2) parks = all_parks_in_country.geometry # and this one now has all the national parks # .... And here is where I am stuck! I am providing visuals below. First map showing the entire country and in green the national parks. Second map showing in purple outline the boundaries of my region. Third map showing in red those (parts of!) the national parks multi-polygon that should ideally be 'cut out' of the national geometry.