Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax call doesn't prefix window.location.href if url starts with /
I have been seeing this behavior while trying to translate some backend calls. What happens is that $.ajax gets called with given arguments and the call that is made may or may not have the current location of the window (current url). For instance, At localhost:8000, a .js file calls $.ajax({ type: "GET", async: false, url: /myendpoint/v1/, data: champs, dataType: 'html', success: function (response) { something... } }) The result request translates to: curl "http://myendpoint/v1/" ^ -H "Accept: text/html, */*; q=0.01" ^ -H "Referer: http://localhost:8000/" ^ -H "X-CSRFToken: a-csrf-token" ^ -H "X-Requested-With: XMLHttpRequest" ^ -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36" ^ -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" ^ --data-raw "some-data=1" ^ --compressed The preflight and the actual request fail. The preflight naturally gives a network/dns resolution error (failed) net::ERR_NAME_NOT_RESOLVED since "http://myendpoint/v1/" is not a valid hostname. However, if I declare the url without the leading slash, it actually calls the good host with the proper relative URL. Having http://localhost:8000 and a relative url to the server as /myendpoint/v1/ seems correct to me. I tried debugging ajax to see what it does but I didn't get to any conclusion. The RFC specification talks a bit … -
Pytest test suite randomly has errors on GitHub Actions without changes
I have a problem with running my tests for a Python project inside Github Actions. Locally the test suite works like a charm and always succeeds. When it is run on Github Actions it succeeds in 1 out of 3 runs with no changes between the individual runs. It seems as the creation of the Django app during the test doesn't always work as expected. Even though I try to assure it is created inside the pytest fixture. @pytest.fixture def installed_app(settings): app_name = f'test_theme_{str(uuid.uuid4()).replace("-", "_")}' app_path = Path(app_name) call_command("tailwind", "init", app_name) while not app_path.is_dir(): time.sleep(1) settings.INSTALLED_APPS += [app_name] settings.TAILWIND_APP_NAME = app_name app_label = app_name.split(".")[-1] app_path = Path(apps.get_app_config(app_label).path) yield app_name, app_path if app_path.is_dir(): shutil.rmtree(app_path) I am confused what the reason is. I also tried it with Travis CI with the same problem. Any help is highly appreciated. Here is the code of the tests. Tests: https://github.com/oliverandrich/django-tailwind-postcss/blob/main/tests/tests.py Pytest fixture: https://github.com/oliverandrich/django-tailwind-postcss/blob/main/tests/conftest.py ============================= test session starts ============================== 9 platform linux -- Python 3.7.10, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 10 django: settings: tests.test_settings (from ini) 11 rootdir: /home/runner/work/django-tailwind-postcss/django-tailwind-postcss, configfile: pyproject.toml 12 plugins: django-4.1.0, cov-2.11.1 13 collected 11 items 14 15 tests/tests.py .....E 16 17 ==================================== ERRORS ==================================== 18 ___________________ ERROR at setup of test_tailwind_install ____________________ 19 20 … -
Conflito sqlite durante o merge do git [closed]
Estou trabalhando com outra pessoa num projeto Django e ela é dona do repositório principal. Eu tenho um fork desse repositório e quero atualizá-lo com o original. Criei o upstream: git remote add upstream <endereço-do-repositorio.git> Depois: git fetch upstream Até aí correu bem, mas na hora de mergear (git merge upstream/master) apresentou o erro: warning: Cannot merge binary files: db.sqlite3 (HEAD vs. upstream/master) Unlink of file 'db.sqlite3' failed. Should I try again? (y/n) n error: failed to create path 'db.sqlite3': perhaps a D/F conflict? Auto-merging db.sqlite3 CONFLICT (content): Merge conflict in db.sqlite3 Automatic merge failed; fix conflicts and then commit the result. Eu entendi que o problema são as divergências do meu banco com o da outra pessoa, mas como podemos resolver pra conseguir trabalhar em equipe sem causar interferências no projeto principal? Obrigada. -
URL resolution in Django with two patterns
There is a need to provide options to task and subtask in Django. where example task is abc_123 ,example subtask is xyz-987 example.com/abc_123/options example.com/abc_123/xyz-987/options My urls.py file urlpatterns = [ url(r'^/(?P<taskId>.+)/options$', views.AvailableOptions.as_view()), url(r'^/(?P<taskId>.+)/(?P<subtaskId>.+)/options$', views.AvailableOptions.as_view()), ] It is working fine when only taskId is sent. When both task and subtaskId is sent. The pattern is taking abc_123/xyz-987 as taskId. I need url to be resolved as abc_123 and xyz-987 as taskId and subtaskId respectively -
How can I make celery more robust with regards to dropped tasks?
Occasionally (read: too often) my celery setup will drop tasks. I'm running the latest celery 4.x on Django 1.11 with a redis backend for the queue and results. I don't know exactly why tasks are being dropped, but what I suspect is that a worker is starting a job, then the worker is killed for some reason (autoscaling action, redeployment, out-of-memory...) and the job is killed in the middle. At this point probably it has exited the redis queue and it won't be picked up again. So my questions are: How can I monitor this kind of thing? I use celerymon, and the task is not reported as failed, and yet I don't see in my database the data that I expected by the task that I suspect failed. How can I make celery retry such tasks without implementing my own "fake queue" with flags in the database? How do I make celery more robust and dependable in general? Thanks for any pointers! -
Django: Annotating price to row, then grouping rows by field, and annotating price sums to groups
My situation: Working on a delivery thingie. I have a Customer, which has one price sheet. The price sheet has pricing zones that are based on postal codes. The customer has DeliveriesOrders, which can have multiple Deliveries (pickups, drop offs) and the price is calculated according the postal code. The way I calculate prices to Delivery rows is: sheet_zones = customer.price_sheet.price_sheet_zones.filter(postal_codes__code=OuterRef("postal_code")) delivery_orders = DeliveryOrder.objects.select_related("customer") \ .prefetch_related( Prefetch( 'deliveries', queryset=Delivery.objects.annotate(price=Subquery(sheet_zones.values("price"))).order_by("-is_pickup"), to_attr="priced_deliveries" ) ) This enables me to have a price annotated for each Delivery row. I however cannot annotate a Prefetch-field, as it results in an error, so .annotate(Sum("priced_deliveries")) doesn't work. I am scratching my head quite hard to get a Sum of all deliveries in a delivery_order. But even more I am scratching my head how to group all deliveries by a field called "reference", and Sum all delivery prices per reference. Pertinent models: class DeliveryOrder(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, related_name="delivery_orders") class Delivery(models.Model): delivery_order = models.ForeignKey(DeliveryOrder, on_delete=models.SET_NULL, null=True, related_name="deliveries") is_pickup = models.BooleanField(default=True) reference = models.CharField(max_length=64, blank=True, null=True) postal_code = models.IntegerField() Customer related models: class PriceSheet(models.Model): name = models.CharField(max_length=255) class Customer(models.Model): name = models.CharField(max_length=255) price_sheet = models.ForeignKey(PriceSheet, on_delete=models.SET_NULL, blank=True, null=True, related_name="customers") class PriceSheetZoneItem(models.Model): price_sheet = models.ForeignKey(PriceSheet, on_delete=models.SET_NULL, null=True, related_name="price_sheet_zones") zone … -
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/index.html
I am a beginner. I am trying to follow a tutorial to make a social media clone. I've searched SO before I asked this question so please don't mark it as duplicate. What I've done so far: connect to server again add the apps in settings.py installed_apps After a user signs up I get: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/index.html Here is my code below: urls.py urlpatterns = [ path("", views.HomePage.as_view(), name="home"), path("admin/", admin.site.urls), path("test/", views.TestPage.as_view(), name="test"), path("thanks/", views.ThanksPage.as_view(), name="thanks"), path("accounts/", include("accounts.urls", namespace="accounts")), path("accounts/", include("django.contrib.auth.urls")), path("posts/", include("posts.urls", namespace="posts")), path("groups/", include("groups.urls", namespace="groups")), ] views.py from django.urls import reverse from django.http import HttpResponseRedirect from django.views.generic import TemplateView class HomePage(TemplateView): template_name = "index.html" def get(self, request, *args, **kwargs): if request.user.is_authenticated: return HttpResponseRedirect(reverse("test")) return super().get(request, *args, **kwargs) class TestPage(TemplateView): template_name = "test.html" class ThanksPage(TemplateView): template_name = "thanks.html" index.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Star Social</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- Optional theme --> <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> --> <!-- Alternative to Bootstrap 3 Glyphicons --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet"> <link rel="stylesheet" href="{% static 'social_media/static/social_media/css/master.css'%}"> </head> <body> <nav class="navbar navbar-expand-lg bg-dark mynav" role="navigation" id="navbar"> … -
Image response from DetailView in Django
I'd like to have a DetailView respond with an image file that is saved to the model/object. I have seen this related question but what I am doing is a little different. I have the following model/views/urls - this allows me to display the image in an img tag inside a template when accessing the url localhost/MY-SKU-FIELD. I'd rather not use a template and just respond with the image directly. # models.py from django.db import models class SignModel(models.Model): sku = models.CharField('SKU', max_length=50) sign_image = models.ImageField(upload_to='images/sign') # views.py from django.views.generic import DetailView from signs.models import SignModel class SignDetailView(DetailView): model = SignModel template_name = 'signs/sign_detail.html' slug_url_kwarg = 'sku' slug_field = 'sku' # urls.py from django.urls import path from signs.views import SignDetailView urlpatterns = [ path('<slug:sku>', SignDetailView.as_view(), name='sign-detail'), ] {# 'signs/templates/sign_detail.html #} <img src="{{object.sign_image.url}}" alt=""> Based on the related question/answer, I figure I need to define my own get() method, then fetch the image, and then respond accordingly, but I'm not quite sure how to fetch the image based on the object fetched in DetailView. I've tried fetching with r = requests.get(self.sign_image.url) but that is clearly not working. How do I get the image and respond correctly? -
Bootstrap5 Streched-link doesn't work with a simple card
I have small problem, streched-link doesnt want to work with my card, I tried everything from Bootstrap docs. Tried also removing buttons cause i've read that they doesn't "live well" with streched-link. I use django-bootstrap-v5 (is it good to use this btw.?) This is my code: <div class="card mb-3" style="width: 81rem;"> <div class="row g-0"> <div class="col-md-4"> <a type="button" class="streched-link" href="{% url 'bloger:post' post.id %}"> <img class="img-fluid" src="..."> </a> </div> <div class="col-md-8" style="max-height: 11rem;"> <div class="card-header d-flex bd-highlight"> <small class="text-muted p-1 flex-grow-1">Added {{ post.date_added|timesince:currentdate}} ago.</small> <small class="text-muted p-1 flex-grow-3">Komentarze: {{ post.blogcomment_set.count }}</small> </div> <div class="card-body" style="max-height: 10rem;"> <h4 class="card-title">{{post.title|title}}</h4> <p class="card-text" style="max-height: 8.4rem;"><i>{{post.truncated_text}}</i></p> <a class="streched-link btn btn-danger" href="{% url 'bloger:post' post.id %}">Read more</a> </div> </div> </div> </div> -
Add data to JWT payload using Django drf-social-auth2 library
I want to add data (such as the token expiration date or user info) to the payload of the JWT generated by this library. I don't have any serializer or view implemented, because the library manages the serializers and the views. I only have to declare the following URL in the urls.py file: urlpatterns = [ ..., path('auth/', include('drf_social_oauth2.urls', namespace='drf')), .../ ] and then I can make POST requests to generate or refresh the JWTs to auth/token/. I've seen solutions (of people that use other libraries) that try to modify the library, and others that implement a serializer and a view, but since the library I'm using is in charge of this task, I don't know how to address this problem. Note: The maintainers of the library indicate that drf-social-auth2 (the library I'm using) relies on python-social-auth and django-oauth-toolkit. The current decoded payload of a JWT is the following { "token": "sXF6EE6jlZRmKhx1mgodOCdUMuSE1I" } -
Saving a ZipFile to FileField in Django
I have the following model in Django: class AksOrder(models.Model): zip_file = models.FileField(upload_to='aks_zips/%M/%S/', blank=True) and in my views I have in essential these functions: def gen_zip(pk, name, vars): zipObj = ZipFile(os.path.join('/tmp/', str(name) + '_' + str(pk) + '.zip'), 'w') zipObj.write(pdf_files[0].path, '/filea.pdf') zipObj.write(pdf_files[1].path, '/fileb.pdf') def aksorder_complete(request, pk): ao = get_object_or_404(AksOrder, id=pk) zipObj = generate_shop_zip(ao.c.pk, ao.dl, ao.vars) ao.zip_file.save('file.zip', zipObj) I did not only try this version, but this one seems the most reasonable and logic one to me. I get a There is no item named 65536 in the archive. When I modify it slightly and close the file at the end of zip-writing in the first function, I get a ValueError: Attempt to use ZIP archive that was already closed message. Both times, the zip-File is generated properly in /tmp/ I could not work arount it. And that's only locally, I need to do it for S3 later... -
Post something if you are already in a group Django
I'm new to Django, and I've just finished an Udemy course based on Python and Django. It's a social media clone project, where, if you are logged in, you can create groups and posts in that group. The problem is that a user can post in any group whether it has joined it or not. I've been asked to code a function that allows a user to post something in a group only if the user is already in that group. It's a daunting task for me. Thank you. -
Get file from server with URL. (DJANGO)
I work in a web app that is used to run a program for students (this program can take some hours to finish) and I used to send the result file via email automatically to the student, but some files are bigger than the maximum size gmail allows to send as attachment. I'm thinking about sending a link via email where the student will click and the file will be downloaded, but I don't know how to create that. The web app works like this: the student uploads some files to the page and clicks run when the student clicks run, those files are copied to a directory in the server, togheter with the program that will run on those files. when the program finishes, it create an output file on that same directory. This is the file that I used to send via email (let's say its path to this file is '/program/<student_name>/output.txt') now, what I wanted to do is send a link via email so when the student clicks on it, it downloads the file in that path. -
How can I access get only the dates in a list? python
I wrote this code: lastDay = Borrowing.objects.values('end_date') print("the list is: ",lastDay) The output is the list is: <QuerySet [{'end_date': datetime.date(2022, 9, 30)}, {'end_date': datetime.date(2021, 7, 26)}, {'end_date': datetime.date(2021, 9, 26)}]> i need only the dates, how can i get rid of {'end_date': datetime.date()} -
HTML form doesn't wan't to send an image
I have a complicated task and for now I don't know reason why things don't work correctly. So I have 2 services - my Django main server and OCR service. OCR service is built with FastAPI and only takes image, processes it and returns response as JSON with data from image. That's how my fastapi file looks like: from fastapi import FastAPI, File, UploadFile, Request import celery_launch from cleaning_folders import cleaning_folder from config import save_img_from_form f_app = FastAPI() def save_img_from_form(image): ts = time.time() * 1000 digit = random.randint(0, 9) file_name = "img_{digit}_{ts}.jpg".format(digit=digit, ts=ts) with open(os.path.join('temp_img', file_name), 'wb') as buffer: shutil.copyfileobj(image.file, buffer) return buffer @f_app.post("/api/ocr") async def send_request(image: UploadFile = File(default='Any', media_type='multipart/form-data')): buffer = save_img_from_form(image) response = celery_launch.ocr_process( selected_town='Templates/Chernomorsk', raw_img_path=buffer.name, selected_billing_type=1 ) json_response = response.get() cleaning_folder('temp_img') return json_response so save_img_from_form() gets an image object from request and saves it to the disk for next processing. Then celery runs and does all OCR process and then returns a dict. So when I use Swagger UI as interactive API testing service, it all works, so in Swagger UI I can load my image through html input and then click the button to run my endpoint. And then I get right JSON as response. … -
python: Django Page not found (404) and I've tried every thing I can so Help me please
app urls.py from django.urls import path from . import views urlpatterns = [ path('hello', views.index, name='index') ] project urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include("hello.urls")) ] views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return HttpResponse("Hello, World!") and I've rewatched the tutorial several times and still cant find the error. -
Django MultipleObjectsReturned error on form submit
I've got quite the mysterious MultipleObjectsReturned error that just popped up after weeks of not having an issue. I'm hoping is just something simple that I'm missing. I've got an Order model, an OrderLine model, which has an Item foreign key. Each Item has a foreign key to a Product. Here are the dumbed down models: class OrderLine(models.Model): order = models.ForeignKey(Order, related_name="lines", on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True) class Product(TimeStampedModel): ... class Item(TimeStampedModel): product = models.ForeignKey(Product, related_name='items', on_delete=models.CASCADE) Now, when I use Django admin to edit an OrderLine which has more than one Item in the ModelChoiceField queryset: I get the following error during form clean: get() returned more than one Item -- it returned 2! Upon closer inspection of the logs, it appears the ModelChoiceField is getting passed the correct Item id/pk, but the self.queryset.get(**{key:value}) is somehow returning 2 Items from a single id/pk, even though the Items have different id/pks (49 and 50): Again, this only happens when the OrderLine form's Item field has more than one object in the queryset. If it's only a single Item, it saves just fine. Any ideas why I'm getting this error now? Thanks! The only thing I can think has … -
Vue3 / Vuex changing store state doesn't update computed prop
I work on a ecommerce website build with VueJS 3 and django. Currently facing some issues with the cart functionality. I want to update the amount of items inside the cart without reloading the page, so just updating the cart component. For this I set up a vue app which looks like this: Vue.js <li class="nav-item" id="navbar-app"> <a class="nav-link" href="#">Cart ([[ numItems ]])</a> </li> ...js const store = { state: { numItems: {{ cart.get_cart_length }} }, mutations: { increment(state, quantity) { console.log(quantity) state.numItems += quantity } } } const Navbarapp = { delimiters: ['[[', ']]'], store: store, computed: { numItems() { let cart_items = store.state.numItems return cart_items } } } Vue.createApp(Navbarapp).use(store).mount('#navbar-app') The get_cart_length function just queries the amount of items: cart.py def get_cart_length(self): return sum(int(item['quantity']) for item in self.cart.values()) If a user adds an item to the cart a fetch function is running. Everything works fine if I update the page I get correct results and correct items so this is not the problem. I tried to trigger the store that the computed prop numItems will update like this: (inside the fetch function) ... .then((res) => { this.store.commit('increment', 1) }) ... this throws an error: Cannot read property 'commit' of … -
Loop results from python into django
I have a simple application that queries a remote URL for a city code. views.py import requests import json def home(request): return render(request, 'app_sitecode/home.html', {'site_code':''}) def lookup_code(request): locode_url = 'https://pkgstore.datahub.io/core/un-locode/code-list_json/data/05f6ccfe0cd03ab51bed07273b982df9/code-list_json.json' try: city = request.GET.get('city') r = requests.get(locode_url) raw_data = (json.loads(r.content)) res = None for sub in raw_data: if sub['Name'] == city: res = sub print(res) print('') #break city_code = res['Location'] country_code = res['Country'] state = res['Subdivision'] site_code = country_code + "-" + city_code return render(request, 'app_sitecode/home.html', {'site_code':site_code, 'name': city, 'country': country_code, 'state': state}) except: return render(request, 'app_sitecode/home.html', {'cleartext':'', 'city':'INVALID CITY'}) When I query for a city, I get valid returns. For example I query the city Stoughton. I see that two Stoughton's were found (python output below). One is Stoughton, WI and one is Stoughton, MA. {'Change': None, 'Coordinates': None, 'Country': 'US', 'Date': '9307', 'Function': '--3-----', 'IATA': None, 'Location': 'SOU', 'Name': 'Stoughton', 'NameWoDiacritics': 'Stoughton', 'Remarks': None, 'Status': 'RQ', 'Subdivision': 'MA'} {'Change': None, 'Coordinates': '4255N 08913W', 'Country': 'US', 'Date': '0201', 'Function': '--3-----', 'IATA': None, 'Location': 'ZTN', 'Name': 'Stoughton', 'NameWoDiacritics': 'Stoughton', 'Remarks': None, 'Status': 'RL', 'Subdivision': 'WI'} The struggle I am having is how to loop the results in the html file. Currently the html file prints only the last entry found. … -
How i can to return json serializable with django rest framework?
i have a custom apiview to query item in cart. i got a instance but when i return response it display error like this Object of type Order is not JSON serializable here is my code class getCart(APIView): def get(self, request, format=None): try: order = Order.objects.get(user=request.user, confirm=False) except Order.DoesNotExist: order = Order(user=request.user, confirm=false) order.save() return Response(order) -
Django two dependent dropdowns
models.py class Document(models.Model): word_type = models.CharField(max_length=255, choices=[('noun', 'noun'), ('verb', 'verb'), ('adjektive', 'adjektive')], default='noun') word = models.CharField(max_length=255) article = models.CharField(max_length=255, choices=[('the','the'), ('-','-')], default='') forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ['word_type', 'word', 'article'] def __init__(self, *args, **kwargs): super(DocumentForm, self).__init__(*args, **kwargs) if self.instance.word_type == "noun": self.fields['article'].choices = [('the', 'the')] else: self.fields['article'].choices = [('-', '-')] I have a model 'document'. When creating a document object in django admin, I want the article dropdown (actual language has several articles) only to show up when 'noun' is selected as word type. Currently I got it working to update the choices to '-' if it's not a noun, but the dropdown only updates with init. So I'm looking for a way to update the article dropdown automatically when word type changes. Maybe there is another (better) way of doing it, would be great if there was a solution to make article dropdown completely disappear when 'verb' or 'adjective' is selected as word type. I'm fairly new to django, couldn't find a solution for this since most tutorials assume article and word_type are dependent models, which is not the case for me. -
Many to Many field POST requests on API Django Rest Framework
So I have 3 models of interest: models.py class Author(models.Model): #Author of books name = models.CharField(max_length = 100) @property # This is code to get the books linked to an author def books(self): book = Book.objects.filter(authors = self.id) return ', '.join(map(str,book)) #This makes the book list in this format "A, B, C" def __str__(self): return self.name.title() class Genre(models.Model): #Genre of books name = models.CharField(max_length = 50, unique = True) @property def books(self): book = Book.objects.filter(genre = self.id) return ', '.join(map(str,book)) def __str__(self): return self.name.title() class Book(models.Model): name = models.CharField(max_length = 150,) #Name of books authors = models.ManyToManyField(Author,) #Many to many because multiple books can have multiple authors genre = models.ManyToManyField(Genre) def __str__(self): return self.name.title() Those are the models, and both genre and author have a many to many relation with books serializers.py class AuthorListSerializer(serializers.ModelSerializer): class Meta: model = models.Author fields = ('name',) class GenreListSerializer(serializers.ModelSerializer): class Meta: model = models.Genre fields = ('name',) class BookListSerializer(serializers.ModelSerializer): authors = AuthorListSerializer(many = True,) #To represent the relationship as a string instead of id genre = serializers.SlugRelatedField(many = True, queryset = models.Genre.objects.all(),slug_field = 'name') class Meta: model = models.Book fields = ('name','authors','rating', 'genre') class BookDetailSerializer(serializers.ModelSerializer): publisher = serializers.SlugRelatedField(queryset = models.Publisher.objects.all(), slug_field= 'name') #To display publisher … -
Django - 'UserViewPermissionClass' object has no attribute 'authenticate' with custom permissions
I'm trying to use custom permissions in my class based views. When I try to run one of my views, I get a WrappedAttributeError : 'UserViewPermissionClass' object has no attribute 'authenticate' Here are my custom permissions : class UserViewPermissionClass(BasePermission): def has_permission(self, request, view): if request.method == 'GET': return request.user.is_admin elif request.method == 'POST': return True # default logic class UserView(APIView): authentication_classes = ( UserViewPermissionClass,) This is the class based view that I'm trying to run : class HandleUsers(UserView): def get(self, request): """Only for admin""" try: users = User.objects.all() except User.DoesNotExist(): return HttpResponse(status=404) serializer = UserSerializer(users, many=True) return Response(serializer.data) def post(self, request): """For everyone""" serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error) Here are my settings for rest framework : REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], } After doing some research I saw that my error could be due to my DEFAULT_PERMISSION_CLASSES. However I cannot see what could be blocking. Thank you in advance for your help. -
It is secure to send sensitive data in context parameter of function Template.render (Django)?
I have to use some data from an object into one of my templates. The question is, Can I send that object via context parameter of function render from class django.template.backends.django.Template or it will create a vulnerability? Thank you for your answers :) -
How to query specific percentage of objects(e.g, 50,70,) in Django ORM
How can I query a particular percentage of database objects in Django ORM. Am unable to use limiting query set as it requires that the length of objects be specified. I only want get like 48 precent, 30 precent, or 70 Percent of the Django objects in the ORM.. Here's a sample code:: percentage = 60 results =Model.objects.filter()[: percentage]. I simply need a way to query a particular percentage of the objects. Thanks friends. I hope to hear from you all.. Please note that I want to query percentage i.e. 60 percentage, not the exact number of query because I don't know the exact counts Thanks