Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stop Celery caching Django template
I have Django 3.24, celery 4.4.7 and celerybeat 2.2.0 setup via the RabbitMQ broker. I have have a celery task that renders a Django template and then sends it to a number of email recipients. The Django template is dynamic in as much as changes can be made to it's content at any time, which in turn rewrites the template. The trouble is that on occasions, I have to restart celery to get it to re-read the template. My question is, is there any way of forcing celery to reread the template file, without requiring a full celery restart? celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backoffice.settings') app = Celery('backoffice') default_config = 'backoffice.celery_config' app.config_from_object(default_config) app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) celery_config.py from django.conf import settings broker_url = "amqp://someusername:somepassword@webserver:5672/backoffice" worker_send_task_event = False task_ignore_result = True task_time_limit = 60 task_soft_time_limit = 50 task_acks_late = True worker_prefetch_multiplier = 10 worker_cancel_long_running_tasks_on_connection_loss = True -
How to Improve IFrame Loading Speed?
I am working on a project for a client who is using Square booking and would like that embedded into their website. I have added an IFrame on the site which points to their booking page on Square's website, however this IFrame loads painfully slow. I am using Django templates for the front end of the website. Is there any way to make this IFrame load faster? Is there a way to load it in the background of the homepage so that it is cached when the user goes to the booking page? -
Issue with Django blog tutorial on youtube, class view and GET method not clear
Was following a youtube tut regarding a django blog but ran into an issue. Link to video: https://www.youtube.com/watch?v=CnaB4Nb0-R8&t=607s The tut says to use the following code in the blog app's view.py file: from django.views.generic. import ListView, DetailView from .models import Post from django.views import View class Blogview(ListView): model = Post template_name = 'blog.html' When I tried to implement the code this way, I was given an error referencing something to do with GET. Looking into it, I modified my code to look like the following: from django.shortcuts import render from .models import Post from django.views import View class Blogview(View): model = Post template_name = 'blog.html' def get(self, request): return render(request,'blog.html') The above version of code works now for me. I find it frustrating why I couldn't figure out why the youtube tutorial code seemed to be much simlified and worked just as expected, whereas when I tried it word for word it failed and had to include a reference to the get method. I'll let you know I did simplify my version of the template file 'blog.html' to be something as simple as a single line of text whereas the tutorial had a template file which took all the posts … -
(index):217 Uncaught TypeError: Cannot read property 'innerHTML' of null
receving error message. Ive tried everything i can think of and being a novice im at a loss. please help DisplayCart(cart); function DisplayCart(cart){ var cartString = ""; cartString += "<h5>This is your cart</h5>"; var cartIndex = 1; for(var x in cart){ cartString += cartIndex; cartString += document.getElementById("nm"+x).innerHTML + "QTY:" + cart[x]; cartIndex += 1; } -
Rendering django model data in html
I am creating a donation application that allows donors to donate stuff. I have a screen, called available supplies.html which renders out all of the donations from the database using a for loop. If someone wants the stuff in the donation, they can click on a view button and are redirected to a page that contains details about the donation. I am struggling with rendering these details out, because I need specific data. Is there any way I can do this? Basically, I want to display data for the donation the user clicked on. My code is down bellow. Donation Model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) HTML (I want the donation data that the user clicked on to render here) {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="/availablesupplies/">&#x2190; Back</a> <br> <br> <table class="table"> <tr> <th><h5>Date Posted: <strong>Date</strong></h5></th> <th><h5>Donor:<strong> User</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="">Accept</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div class="cart-row"> <div style="flex:2"></div> <div style="flex:2"><strong>Item</strong></div> <div style="flex:1"><strong>Category</strong></div> <div style="flex:1"><strong>Quantity</strong></div> </div> <div class="cart-row"> <div style="flex:2"><img class="row-image" src=""></div> <div style="flex:2"><p>Title</p></div> <div style="flex:1"><p>$20</p></div> <div style="flex:1"> … -
How does one count a foreign key item, esp 'author' created with Django's User model?
Need help getting a better grip with 1) accessing and counting foreign key items in Django and 2) counting foreign key item that is created through Django's built-in User: #1) The answer here suggests using Django's annotate function: eg. questions = Question.objects.annotate(number_of_answers=Count('answer')) (question being a foreign key item to answer). But it is not clear to me where this line belongs to (in the case of the example, question or answer), or which part of an app-models.py or views.py. I tested in both models.py and views.py Here are my models (only the essential lines here): class Post(models.Model): post = models.TextField(max_length=1000) author = models.ForeignKey(User, related_name="author", on_delete=models.CASCADE) class Comment(models.Model): comment = models.TextField(max_length=1000) commenter = models.ForeignKey(User, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, related_name='posts', on_delete=models.CASCADE, default=None, null=True) #2) How does one access a foreign key item created using Django's built-in model, User? Should I have created a model called "Author" first? -
How do I make the django admin site rely on my custom Django Rest Framework Token Authentication?
Throughout development of my application, the authentication has worked great. Using DRF I overrode DRF's TokenAuthentication to provide an expiring token, and then overrode ObtainAuthToken to create the authentication post request view. Now I'm trying to launch the application into production with DEBUG=False. The application seems to be running fine, but the django admin site will not let me log in to my super user (yes I created it with createsuperuser and have verified it exists in the database). The error I get back is: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. This confused me because I'm using Token authentication and not Sessions. In my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'custom_auth.authentication.ExpiringTokenAuthentication' ] } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] I believe the django.middleware.csrf.CsrfViewMiddleware was put in there by default when I created the application, and I assume this … -
customer Select a valid choice. That choice is not one of the available choices
please i want someone to help me solve this problem. if there's a better way i can write the codes, i will really appreciate. what i want is for the user to make order and get redirected to a page where the user will see all his orders . please someone should help out error message : customer Select a valid choice. That choice is not one of the available choices client model file from django.db import models # Create your models here. class ClientJob(models.Model): STATUS = ( ('Pending', 'Pending'), #('On-going', 'On-going'), ('Completed', 'Completed'), ) customer = models.ForeignKey('accounts.Customer', null=True,blank=True, on_delete= models.SET_NULL,related_name='client') job_name = models.CharField(max_length=50,unique =False) text_description = models.CharField(max_length=150,null=True) location = models.ForeignKey('accounts.Area' ,on_delete =models.CASCADE ,null=True,blank=True) address = models.CharField(max_length=200,unique =False) phone =models.CharField(max_length=15,unique =False) email = models.EmailField(unique = False) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS,default='Pending') def __str__(self): return self.job_name class Meta: verbose_name_plural = "Client Job" client forms.py file from django.db.models import fields from django.forms import ModelForm from django import forms from django.contrib.auth.models import User from .models import * class ClientJobForms(ModelForm): class Meta: model = ClientJob fields = ['job_name','text_description','location','address','phone','email','status','customer'] #fields ="__all__" def __init__(self, *args, **kwargs): super(ClientJobForms, self).__init__(*args, **kwargs) self.fields['location'].empty_label ='Your location' client admin file from django.contrib import admin from .models import … -
SimpleJwtAuthentication django
Does simplejwt authentication works with custom user model .if not ,is there any way to achieve. models.py class user_model(models.Model): username=models.CharField(max_length=200,blank=True,unique=True) email=models.CharField(max_length=200,blank=True) password=models.CharField(max_length=200,blank=True) age=models.CharField(max_length=200,blank=True) dob=models.CharField(max_length=200,blank=True) phone=models.CharField(max_length=200,blank=True) def __str__(self): return self.username -
Is there a way to submit multiple forms with a single button and unique hidden values?
Note: I have seen some posts that are quite similar to mine but I don't think those solutions help in my use case. My website (made using Django) has a page for collecting dues payments. There is one page per family, in which there will be multiple dues to be paid by each member. Currently, I have one submit button to each due as you can see in the code below. {% for due in dues %} <tr> <td>{{due.0}}</td> <td>{{due.1}}</td> <td>{{ due.3}}</td> <td>{{ due.4 }}</td> <td>{{ due.5 }}</td> <td><form action="/dues/?family-dues={{ familyprofile }}" method="POST" id= "dues-payment"> {% csrf_token %} <input type="text" placeholder="Enter Amount" name="amount"> <input type="hidden" value="{{due.2}}" name="due-id"> <input type="hidden" value="{{due.0}}" name="member-id"> <input type="hidden" value="{{duefamily.0}}" name="family-id"> <button id="submit-payment">Pay</button></form></td> </tr> {% endfor %} The issue with this is that, only one payment can be done at a time. Is there a way where I can instead submit all the forms in one go. So that the cashier can just enter the appropriate payments in each textbox and when its submitted all the textbox values(paid amount) along with the due id be returned in one go? Current Scenario Due ID 1 textbox(Value is 40) Pay Button Due ID 2 textbox(Value is 80) Pay … -
How can I access an attribute of a model which is a foreignkey to another model in the views.py file
For example I have two models .Brand model which is a foreign key to another model Item. The Brand model has an attribute best_seller which is a boolean field recording whether a certain brand of items is a best seller. In my views I want to filter only the items whose brand is a best seller.How can I do this This is how my models.py looks like class Brand(models.Model): title = models.CharField(max_length=100) best_seller = models.BooleanField(default=False) def __str__ (self): return self.title class Item(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) new_price = models.DecimalField(max_digits=7, decimal_places=2) image = models.ImageField(upload_to='static/images') old_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) slug = models.SlugField() description = models.TextField() featured = models.BooleanField(default=False) def __str__ (self): return self.title Then this the views.py file def home(request): brand = Brand.objects.filter(best_seller=True) bests = Item.objects.filter(brand=True).order_by('-id')[:12] context = { 'items': items, 'bests': bests } return render(request, 'home.html', context) After doing this there's nothing being rendered on the browser -
Nested fields/objects creation with DRF
It's me again with questions about the polls API I'm working on. I have three models: Poll, Question and Choice. from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Poll(models.Model): title = models.CharField(max_length=200, verbose_name="Naslov ankete") description = models.TextField(verbose_name="Opis ankete") author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="polls", verbose_name="Autor") pub_date = models.DateTimeField(auto_now_add=True, verbose_name="Datum objavljivanja") class Meta: ordering = ["pub_date", "title"] verbose_name = "Anketa" verbose_name_plural = "Ankete" def __str__(self): return self.title class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="questions", verbose_name="Anketa") question_text = models.CharField(max_length=200, verbose_name="Tekst pitanja") class Meta: # ordering = ["question_text"] verbose_name = "Pitanje" verbose_name_plural = "Pitanja" def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices", verbose_name="Pitanje") choice_text = models.CharField(max_length=200, verbose_name="Tekst opcije") votes = models.IntegerField(default=0, verbose_name="Glasovi") class Meta: # ordering = ["-votes"] verbose_name = "Opcija" verbose_name_plural = "Opcije" def __str__(self): return self.choice_text Whatever I put in the serializers, I can't achieve the creation of questions and choices at the same time with the poll. How should my serializers look like if I want to use the following JSON, but still be able to create questions and choices independently? { "title": "Favorite destinations", "description": "A few questions about traveling", "questions": [ {"question_text": "Which destination seems better for you?", "choices": [{"choice_text": "London"}, {"choice_text": … -
admin-path is removed from url, but can still be accessed (Django)
I have a django application of which I want to remove the Admin-access in production. Because of that I've removed the admin-url from the url.py file, but if I go to myapp.com/admin/login it still allows me to log in. Is there a way to disable admin-login in production?` -
Django Changing HTML Template Not Reflecting
I'm new to Django, I have created a webportal and recently came to know their is an issue in the portal. After changing the html content, its not reflecting the content in portal, still displaying old html data. Could someone please tell me, what needs to be done. Note: I have reloaded django from command prompt and verified, but getting the same issue, Thank You!! -
Merging a field in one model to another with ForeignKey, Django Subquery and OuterRef
I have two models, RetailLocation and Transaction, which share a one-to-many relationship respectively. My goal is to annotate RetailLocation with the date of the latest Transaction which corresponds to that RetailLocation. The model Transaction includes "r_loc_name" which is the exact same string as RetailLocation.name. I believe this field is redundant, and I expect there is a better solution using only the r_loc ForeignKey (and set) in RetailLocation, however I have not figured out how. Models class RetailLocation(models.Model): name = models.CharField(max_length=200, null=True) class Transaction(models.Model): date = models.DateTimeField(null=True) r_loc = models.ForeignKey(RetailLocation, null=True, on_delete=models.SET_NULL) r_loc_name = models.CharField(max_length=200, null=True) # Likely redundant Attempted Code loc_latest = RetailLocation.objects.all().annotate( latest_txn_time=Subquery( Transaction.objects.filter(r_loc_name=OuterRef("name")) .order_by("date") .values("date") .last() ) ) Another Attempt loc_latest = RetailLocation.objects.all().annotate( latest_txn_time=Value( Subquery( RetailLocation.objects.get(name=OuterRef("name")) .transaction_set.order_by("date") .last() .date ), DateTimeField(), ) ) My goal is to to reference RetailLocation.latest_txn_time, which would be the annotated datetime of the latest Transaction referenced to that RetailLocation. Thank you very much -
How do I get the data send by Ajax in Django?
I tried to get the data I send via Ajax with request.GET.get, but this does not work. Data is always None. I really appreciate any kind of help! This is my jQuery/Ajax code: $(document).ready(function(){ $(".jcf-select.jcf-unselectable").on('click', function(){ var sel = $('#sort').children("option:selected").val(); console.log(sel) $.ajax({ url: '/filter-data', data: sel, dataType: 'json', success:function(res){ console.log(res); $("#filter_products").html(res.order); } }); }); }); This is my view: def filter_data(request): if request.is_ajax: query = [] data = request.GET.get('data') if data == "gpv": query = data.order_by("price_with_shipping")[:150] elif data == "gp": query = data.order_by("lowest_price")[:150] elif data == "lp": query = data.order_by("liter_price")[:150] elif data == "tz": query = data.order_by("-lowest_price")[:150] t = render_to_string('homepage/ajax-products.html', {'order': query}) return JsonResponse({'order': t}) -
Cannot create django project in cmd
when I want to start a project with Django in cmd. I got an error. please I need help -
How do i pass a django url parameter to redirect function
I'm creating a blog website and I want it to be that when a user update a post, I want to redirect them to the view page for that article. the urls.py url_patterns = [ path('view/<str:id>/, views.viewPost, name='viewpost'), path('update/<str:id>/, views.updatePost, name='updatepost') ] My problem is that, I want to be able to redirect to the viewpost when I update a post I tried return redirect('viewpost' id) But it was giving me an error Thanks for your contribution -
Django SearchFilter Multiple models
Using Django 3.2 with Restframework. I'm trying for search filter and create a API with restframework which would output the searched term with its whole object. I had a little success on that with official doc. But from that I can only search in a single Model and not as globally. I found a blog on how to use multiple Models together? I tried for following from that: Views.py class GlobalSearchList(generics.ListAPIView): serializer_class = GlobalSearchSerializer def get_queryset(self): query = self.request.query_params.get('query', None) users = MasterUser.objects.filter(Q(firstname__icontains=query) | Q(lastname__icontains=query) | Q(email__icontains=query) | Q(category__icontains=query)) webinar = MasterWebinar.objects.filter(Q(host__icontains=query) | Q(title__icontains=query)) section = ResourceSection.objects.filter(Q(resource_name__icontains=query)) item = SectionItem.objects.filter(Q(item_title__icontains=query)) all_results = list(chain(users,webinar,section,item)) print(all_results) #Objects as output are printed in console return all_results #Blank output serializers.py class GlobalSearchSerializer(serializers.Serialize): def to_native(self, obj): if isinstance(obj, MasterIndividualMembers): serializer = MasterIndividualMembersSerializer(obj) elif isinstance(obj, MasterUser): serializer = MasterUserSerializer(obj) elif isinstance(obj, MasterWebinar): serializer = MasterWebinarSerializer(obj) elif isinstance(obj, MasterResource): serializer = MasterResourceSerializer(obj) elif isinstance(obj, ResourceSection): serializer = ResourceSectionSerializer(obj) elif isinstance(obj, SectionItem): serializer = SectionItemSerializer(obj) else: raise Exception("Not found in any instance!") return serializer.data In here, while printing the output it does print objects, but doesn't return anything as output. Any cause why there is no output, where am I doing wrong? Also I tried with serializers.ModelSerializer but … -
Why Django unique constraints did not work?
I've added UniqueConstraint into the constraints array in the Meta class which is a subclass of User table. class User(AbstractBaseUser): ... class Meta: verbose_name = _("account") verbose_name_plural = _("accounts") indexes = [ models.Index(name="email_index", fields=["email"]) ] constraints = [ models.CheckConstraint(name="check_birth_date", check=Q(birth_date__lt=f"{datetime.date.today()}")), models.CheckConstraint(name="check_phone_number", check=Q(phone_number__regex=r"^09(1[0-9]|2[0-9]|3[0-9])[0-9]{3}[0-9]{4}$")), models.UniqueConstraint(name="username_email_unique", fields=["username", "email"]) ] My expectation was that prevent user to enter username and email with same value, But actually did not work and user can do it without getting the IntegrityError Moreover, I'm using Postgresql -
how to put multiple Forms in the same views.py - Django
I need to put four Form in one views.py function, but I have no idea how to do it. I need every form to show on the site on the same time. I will take any advice on how I can solve this problem. models.py # Hotel class Hotel(models.Model): customer = models.ForeignKey(Account, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) short_description = models.TextField(max_length=250) long_description = models.TextField(max_length=2000, null=True) HOTEL_STAR = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) star = models.TextField(max_length=1, default=5, choices=HOTEL_STAR, null=True) picture = models.ImageField(upload_to='images/%Y/%m/%d/',default="images/default.jpg" , blank=True) created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) # Room class Room(models.Model): hotel = models.ForeignKey(Hotel, null=True, on_delete=models.CASCADE) def __str__(self): return f'Room of {self.hotel}' # Single type for Room class Single(models.Model): room = models.ForeignKey(Room, null=True, on_delete=models.CASCADE) ROOM_NAME = ( ('Budget_single_room', 'Budget Single Room'), ('Standard_single_room', 'Standard Single Room'), ('Superior_single_room', 'Superior Single Room'), ('Deluxe_single_room', 'Deluxe Single Room'), ) name = models.TextField(max_length=30, choices=ROOM_NAME, null=True) ROOM_SMOKE = ( ('Smoking', 'Smoking'), ('Non-Smoking', 'Non-Smoking'), ) smoke = models.TextField(max_length=15, choices=ROOM_SMOKE, null=True) bed = models.IntegerField() capacity = models.IntegerField() room_size = models.IntegerField() def __str__(self): return f'{self.name}' # Double type for Room class Double(models.Model): room = models.ForeignKey(Room, null=True, on_delete=models.CASCADE) ROOM_NAME = ( ('Budget_Double_room', 'Budget Double Room'), ('Standard_Double_room', 'Standard Double Room'), ('Superior_Double_room', 'Superior … -
DRF changes name or ignores "create" route
I'm new to DRF's "viewsets", but I've inherited some problematic code, and am having trouble figuring out what's going on. I have stripped down the code below to isolate the behavior I don't understand. In my urls.py I have from my_app.api import CurrentUserViewSet, from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register("me", CurrentUserViewSet, basename="api-me") print(router.urls) Note the diagnostic print statement at the end. The CurrentUserViewSet is defined as: from rest_framework import viewsets from django.views.generic import View class CurrentUserViewSet(viewsets.ViewSetMixin, View): def create(self, request): """Update current user.""" instance = request.user ... @action(detail=False, methods=["post"]) def some_other_route(self, request): ... When I start a runserver instance that uses the above, it hits my print statement in "urls.py" and displays this: [ <URLPattern '^me/$' [name='api-me-list']>, <URLPattern '^me\.(?P<format>[a-z0-9]+)/?$' [name='api-me-list']>, <URLPattern '^me/some_other_route/$' [name='api-me-some-other-route']>, <URLPattern '^me/some_other_route\.(?P<format>[a-z0-9]+)/?$' [name='api-me-some-other-route']>... ] So it looks like the name of my create route is being changed to list. I don't know how or why this is happening. Interestingly, if I define an addtional route that is actually named "list", the "create" method still does not appear in the URLs created by the router. It seems to be totally ignored. As I mentioned, I inherited this code. I think that even though the original author named … -
Django - Firebase real time chat system
I need to make a chat system between a django app and an android app via a firebase real time database. I am using Pyrebase4 for handling the firebase, and Channels to handle the socket connection. I have a listener that listens to any changes in the chat room inside the Firebase real time database The listener is activated when the page is loaded: from accounts.firebase_repo import db def listen_to_chat(request, patient_key): doctor_id = request.user.id chat_id = f"{patient_key}_{doctor_id}" db.child("Chats").child(chat_id).stream(stream_handler) The stream_handler callback: def stream_handler(event): acc = AsyncChatConsumer() asyncio.run(acc.receive(event['data'])) The AsyncChatConsumer class: class AsyncChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, message): pass async def receive(self, text_data=None, bytes_data=None): # json_to_send = {} if text_data is not None: if 'message' not in text_data: # this is triggered on page load. Fetches all of the messages inside the room await self.send(text_data) else: # this is triggered when a new message is posted in the Firebase await self.send(text_data) the send method should trigger my javascript code. I have a chatSocket that I initialize when the DOM is loaded: window.addEventListener('DOMContentLoaded', (event) => { initializeSocket( "{{ context.key }}", "{{ context.doctor_id }}", "{% url 'send_message' %}" ); }); chatSocket = new WebSocket(wsStart + loc.host + '/ws/chat/' + … -
Django TypeError: get() got an unexpected keyword argument 'quiz_name'
I am trying to access a url from flutter webview , however, I am getting the following error. When I try to access this directly, I dont see any error. File "/home/quiz/views.py", line 629, in dispatch return super(QuizTakeAutoAuth, self).dispatch(request, *args, **kwargs) TypeError: get() got an unexpected keyword argument 'quiz_name' views.py class QuizTakeAutoAuth(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'foo': 'bar' } return Response(content) def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied if self.sitting is False: print("sitting false") if self.logged_in_user: return render(request, self.single_complete_template_name) else: redirecturl = "/login/?next=/quiz/"+self.kwargs['quiz_name']+"/take/" return redirect(redirecturl) return super(QuizTakeAutoAuth, self).dispatch(request, *args, **kwargs) urls.py url(r'^(?P<quiz_name>[\w-]+)/startquiz/$',view=QuizTakeAutoAuth.as_view(), name='quiz_question_auth'), What am I missing here? I am using the same view elsewhere without any knox Tokenauthentication and works as expected. -
Post working from build-in rest_framework UI (in browser) but not from Postman
while starting my backend project I've run into a problem and can't find a solution. I work with django and wanted to implement crud operations for one table named tutorials and these operations run great when I use the browser or build-in rest_framework UI from the browser but when I try the post request from postman (sending a json object) it gives me the 500 internal server error from postman this is my project structure , I have only one app called platforme : project structure This is the code in platforme/urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from platforme import views urlpatterns = [ path('tutorials/',views.TutorialList.as_view()), path('tutorials/<int:pk>/',views.TutorialDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) This is the code in platforme/models.py , I only have one model from django.db import models # Create your models here. class Tutorial(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) This is platforme/serializers.py from rest_framework import serializers from platforme.models import Tutorial class TutorialSerializer(serializers.ModelSerializer): class Meta: model = Tutorial fields = ('id','title','description','published') And finally this is the platforme/views.py : from rest_framework import generics from rest_framework import mixins from platforme.models import Tutorial from platforme.serializers import TutorialSerializer class TutorialList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Tutorial.objects.all() serializer_class …