Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to reverse url with pk post django
hi i am creating a django blog in which i am adding a comment section,all stuff worked fine. but after adding comments i want to redirect to that perticular post in which i wanted to add comment views.py class add_comment(CreateView): model = comments fields = ['comment'] template_name = 'forum_app/add_comment.html' success_url = reverse_lazy('post_detail',) def form_valid(self, form): form.instance.author = self.request.user form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) urls.py from . import views from .views import post_detail,add_comment urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name="home"), path('<int:pk>/',post_detail.as_view(),name='post_detail'), path('add_comment/<int:pk>/',add_comment.as_view(), name='add_comment') ] all i want to do is once i click submit it should reverse to the same post which i wanted to add comments simple post_detail asking for pk but not able to integrate pk in this... help is appreciated -
How to warmup cache view as login user in Django?
I want to warmup cached View from scheduled management command. I have to be logined when doing request to View. What is the best practice to login as user and do get request to View? I am thinking about two ways: Use requests: request = requests.session() response = request.get(login_url) token = response.cookies['csrftoken'] data={'username':'username@username.ru', 'password': 'pass','csrfmiddlewaretoken':token} response = request.post(login_url, data=data) response = request.get(target_url) Use test.Client() and login option. What is better? Or maybe the best option exists? -
Update Django model based on the row number of rows produced by a subquery on the same model
I have a PostgreSQL query which updates the global_ranking field of each row, based on the row number of that row as computed by a subquery which takes that same table and sorts it according to another column called rating. Additionally, the update is partitioned, so that the ranking of each updated row is relative to only those rows which belong to the same language. In short, I'm updating the ranking of each player in a word game (why player statistics have a language field), based on their current rating. The working PostgreSQL query looks like this: UPDATE stats_userstats SET global_ranking = sub.row_number FROM ( SELECT id, row_number() OVER ( PARTITION BY language ORDER BY rating DESC ) AS row_number FROM stats_userstats ) sub WHERE stats_userstats.id = sub.id; I'm using Django, and it'd be fun to learn how to express this query using the Django ORM, if possible, before resorting to running a raw query. It seems like Django has all the parts that are necessary to express the query, including the ability to use PostgreSQL's row_number() windowing function, but my current attempt updates all rows ranking with 1: from django.db.models import F, OuterRef, Subquery from django.db.models.expressions import Window from … -
Why there is a lag between Django and Gunicorn?
I have my production server (RHEL 7) setup with the following Nginx -> Gunicorn -> Django. Below are the logs from django (removed log messages and modules info for safety reasons). { "log_level": "INFO", "_time": "2021-02-03 06:02:49,711" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:49,711" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:50,371" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:50,611" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:50,852" <removed for safety reasons> } It is clear that the time taken to process a request and respond is Approx 1-2 sec Below is the access log entry in gunicorn - - [03/Feb/2021:06:02:54 +0000] "GET /all_uploads/ HTTP/1.0" 200 18496 "<domain name removed for safety reasons>" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36" and Below is the entry log in Nginx <ip removed for safety reasons> - - [03/Feb/2021:06:02:54 +0000] "GET /all_uploads/ HTTP/1.1" 200 18496 "<domain name removed for safety reasons>>" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36" "-" "-" I assumed that the template rendering is taking time, however this template is a simpler one and shouldn't take more … -
Django: celery showing different status for the same task
I've a django app with two celery tasks, say task1 and task2. task1 gets triggered on a POST request from the frontend and the request has to sent back the task id so the frontend can poll its status later. task2 is supposed to run after task1 succeeds, asynchronously. Here're my task definitions: @shared_task(ignore_result=False) def task1(pk: int): # retrieve object matching pk return task1_func(obj) @shared_task(ignore_result=False) def task2(task_id: int): task = AsyncResult(task_id) while not task.ready(): logger.info("status {}".format(task.status)) time.sleep(1) return task2_func() Here's how I'm triggering them inside my views.py: class MyView(viewsets.ModelViewSet): def create(self, request): # create object task = task1.delay(obj.pk) task2.delay(task.id) #breakpoint return Response(task.id, status=status.HTTP_200_OK) Now when I try checking the status at the breakpoint, it shows success: In [1]: task.id Out[1]: '97f8d150-de04-4848-a400-3882988c833c' In [2]: task.status Out[2]: 'SUCCESS' In [3]: AsyncResult(task.id).status Out[3]: 'SUCCESS' But the code inside the task2 never gets executed because the status of task1 inside task2, never changes from PENDING. What am I doing wrong? Clearly my results are being stored and accessible but for some reason I cannot see the change in status from within another task. I cannot chain the tasks because I've to send the first task's id to the frontend. -
How exactly should JWT-based authentication be implemented in Django (drf and simplejwt)?
I am struggling to understand exactly how JWT-based authentication should be implemented in Django (I am using simplejwt). I am just a beginner, so please brace yourselves for some silly questions. The rest-framework-simplejwt documentation is very minimal and does not provide enough detail for a newbie like me. path('token/obtain', jwt_views.TokenObtainPairView.as_view(), name='token_create'), path('token/refresh', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), So, I've created the paths in my urls.py as suggested by the official documentation. Where do I go from here? I guess my confusion comes from the fact that I am not sure where exactly in the code I have to issue my tokens. Let's say, I am logging in the user. So, in order to obtain the token, do I have to send a request to the 'token_create' endpoint from inside my view? Or do I have to somehow indicate it in one of my serializers? What about the 'refresh_token' endpoint? Is there a specific method that I need to use? Then, what do I do with the token once it has been issued? Clearly, I shouldn't save it in the database since it defeats the entire purpose of using JWTs in the first place. From my understanding, I should attach it to the headers … -
How to display single/particular data record from database -django
I want to display a particular data record from the database of a person who is logged in to the website. I have a default primary key in the migration. Other than that I don't have any of the primary or foreign keys. Below is the models.py and template codes. models.py class Ticket(models.Model): Email = models.CharField(max_length=40) to = models.CharField(max_length=40) cc = models.CharField(max_length=50) subject = models.CharField(max_length=25) class Meta: db_table = 'ticket' def __str__(self): return self.Email Following is the views which I had used before, that display's the whole data from the database. Views.py def ticket(request): ticket = Ticket.objects.all() return render(request, 'web/ticket.html', {'ticket':ticket}) But I want to display data of the respective mail id ticket.html {% for ticket in ticket %} <fieldset id="first"> <label for="From"><b>From</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="From" name="From" style="width:100%" value="{{ ticket.Email }}" required> <br> <br> <label for="To"><b>To</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="To" name="To" style="width:100%" value="{{ ticket.to }}" required><br> <br> <label for="Cc"><b>Cc</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="Cc" name="Cc" style="width:100%" value="{{ ticket.cc }}" required><br> <br> <label for="Subject"><b>Subject</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="Subject" name="Subject" style="width:100%" value="{{ ticket.subject }}" required><br> <br> </fieldset> … -
Scraping jobs from PDF in india
I am facing an issue with PDF. I have to scrape the jobs from pdf file. Different pdfs are in different formats. I can scrape the data from pdf but, I need to identify which is a job title, job description..e.t.c.I am unable to do that.Can you guys suggest any solution to this issue? I need a solution in python. -
(1170, "BLOB/TEXT column 'BS_ID' used in key specification without a key length") Error while shifting my Django Database from Sqlite3 to mySQL
I have recently being try to change my Django database from sqlite3 to MySQL and while running the migrations I'm getting this error for the text field which is a primary key, its necessary to have it as a primary key because I have to use it for foreign key. Please share what changes do I need to make in my models to make this migration to MySQL successful. BS_ID = models.TextField(max_length=20,unique=True)- this field is the cause of the error. -
Pass the value of dropdown to sql query and fetch data and display in form of checkbox using Django Python
So i have a code which should get the value of dropdown selected value and pass it to a sql query fetch the result and pass it to another class , Since am new to django and am not really able to find what is the problem with the code . Can anyone kindly help me Posting the code <form enctype="multipart/form-data" action="{% url 'files' %}" method="POST"> {% csrf_token %} {{SnippetForm|materializecss}} <br> <table class="table form-table table-bordered table-sm"> <tbody> {% for form_data in formset %} <tr class="item"> <td> {{ form_data.server|materializecss }} </td> </tr> {% endfor %} </tbody> </table> {{ formset.management_form }} <br> <button type="reset" class="waves-effect waves light btn-large">Reset</button> <button type="submit" class="waves-effect waves light btn-large">Submit</button> </form> Here is the Index.html and the SnippetForm contains textbox Model.py # Create your models here. class Snippet(models.Model): customer = models.CharField(max_length=100, choices=customer_list) environment = models.CharField(max_length=100, choices=environment_list) def __str__(self): return self.customer class Meta: db_table = "snippet" Value = Snippet() cursor.execute("select distinct(VMName) from Inventory where customer='"+str(Value)+"' and status='Active'") records2 = cursor.fetchall() for i in range(len(records2)): server_choices[records2[i][0]] = records2[i][0] server_list = tuple([(str(k), v) for k, v in server_choices.items()]) class Files(models.Model): files_to_upload = models.FileField(upload_to='uploaded_files/', default=None, validators=[validate_file]) path = models.CharField(max_length=100) server = MultiSelectField(choices=server_list) snippet = models.ForeignKey(Snippet, related_name="files", on_delete=models.CASCADE) def __str__(self): return str(self.snippet) class … -
OrderForm' object has no attribute 'get' via request.post
I've created an orderform and was trying to extract information from the form. However, each time when i called for forms.get("firstname") or anything, i will face the error that the object has no attribute 'get" even though it is a form. more specifically, the error is "AttributeError: 'OrderForm' object has no attribute 'get'" Here is the relevant code: in models.py: class BaseModel(models.Model): eid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date_created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: abstract = True @classmethod def get_or_none(cls, **kwargs): try: return cls.objects.get(**kwargs) except cls.DoesNotExist: return None class Order(BaseModel): itemname = models.CharField(max_length =100, default="") firstname = models.CharField(max_length = 20) lastname = models.CharField(max_length = 20) email = models.EmailField() phone = PhoneNumberField(null=False, blank=False) comments = models.TextField() delivery = models.BooleanField(default=False) def __str__(self): return str(self.eid) in forms.py: class OrderForm(forms.ModelForm): itemname = forms.ModelMultipleChoiceField(queryset=Post.objects.filter(title__contains="Bae"), required=True) class Meta: model = Order fields = ('itemname', 'firstname', 'lastname', 'email', 'phone','delivery', 'comments') labels = {'itemname': 'Order Item', 'firstname': 'First Name', 'lastname':"Last Name", 'email':"Email", 'phone':"Phone Number", 'delivery':'Deliver?', 'comments':'Comments'} in views.py. This is where the error occurs: def order(request): if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): order = form.save(commit=False) item_selected = form.get('itemname') order.itemname = item_selected order.save() return render(request, 'Reddit_app/order_thankyou.html') else: form = OrderForm() return render(request, 'Reddit_app/order_from_post.html', {"form": form}) finally, the … -
Pycharm Django remote execution trying to use local path
I created a Django project in Pycharm, and configured for remote execution. Pycharm happily uploads the local project to the remote VM. However, when I try to debug/execute manage.py, or another "hello world" kind of Python script, it appears that the remote python is being handed the path to manage.py, etc. on my local machine, not the path to manage.py, etc. on the remote machine. I've successfully create and remotely executed multiple "Pure Python" Pycharm projects. I am reasonably familiar with Pycharm, but not so much with Django, and particularly not experienced running Django under Python. Any suggestions as to what I might be doing wrong are appreciated Config: Pycharm 2019.3.4 Professional MacOS Catalina. The Pycharm console output follows. ssh://xxx@xxx:22/usr/local/bin/python3.9 -u /home/xxx/.pycharm_helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 0.0.0.0 --port 43395 --file /Users/xxx/PycharmProjects/etlworkflow/manage.py bash: line 0: cd: /Users/xxx/PycharmProjects/etlworkflow: No such file or directory pydev debugger: process 6418 is connecting Connected to pydev debugger (build 193.6911.25) Traceback (most recent call last): File "/home/xxx/.pycharm_helpers/pydev/pydevd.py", line 1434, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "/home/xxx/.pycharm_helpers/pydev/_pydev_imps/_pydev_execfile.py", line 11, in execfile stream = tokenize.open(file) # @UndefinedVariable File "/usr/local/lib/python3.9/tokenize.py", line 392, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: '/Users/xxx/PycharmProjects/etlworkflow/manage.py' -
Django: AttributeError: 'User' object has no attribute 'get'
I'm getting AttributeError: 'User' object has no attribute 'get' in Django, I am trying to get the favorite movie genres of the user. My form looks like this: class GenresForm(forms.ModelForm): firstGenre = forms.CharField(label="What is your favorite genre?", widget=forms.Select(choices=GENRE_CHOICES)) secondGenre = forms.CharField(label="What is your second favorite genre?", widget=forms.Select(choices=GENRE_CHOICES)) thirdGenre = forms.CharField(label="What is your third favorite genre?", widget=forms.Select(choices=GENRE_CHOICES)) class Meta: model = Favorites fields = ["firstGenre", "secondGenre", "thirdGenre"] My view: def genres(request): user = request.user if request.method == "POST": form = GenresForm(request.POST) if form.is_valid(): genres = form.save(commit=False) genres.user = request.user genres.save() return redirect("/home") else: form = GenresForm(request.user) return render(request, 'core/genres.html', {"form":form}) and my Model class Favorites(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) firstGenre = models.CharField(max_length=50) secondGenre = models.CharField(max_length=50) thirdGenre = models.CharField(max_length=50) -
count of likes is not showing in python django .... I don't know why .. Can someone help me
registration and login page is working properly but mine count of likes is not showing in django... I don't know why... Can somebody help me to find this error... It will be the great help... Thank You!! 1.Views.py from django.shortcuts import render, get_object_or_404, redirect from datasecurity.models import Post from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required # Create your views here. @login_required def likes(request, pk): post=get_object_or_404(Post, pk=pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:datasecurity')) def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} def __init__(self, *args, **kwargs): stuff = get_object_or_404(Post, id = self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes'] = total_likes return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() context={"post":post} return render(request, "datasecurity/blogHome.html", context) 2.Urls.py from django.conf.urls import url from . import views app_name = 'datasecurity' urlpatterns = [ url(r'^$', views.datasecurity, name="datasecurity"), url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'), url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"), ] 3.models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) img = models.ImageField(blank=True, null=True, upload_to="dataimage/") likes = models.ManyToManyField(User) @property def total_likes(self): return self.likes.count() def __str__(self): return self.title + " by " + self.author 4.data.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, … -
How can I implement AJAX live search in my Django Application?
I am looking to create a recipe app with a live search feature where you will type into the search bar located at the top of the home page, and it should filter down the list of recipes that are displayed underneath (located in the partial_home.html file). What I am expecting to see is that when I input any character or string of characters, the search icon should start blinking, and then after a short delay (about 700 miliseconds), the recipes should fade out and the fade in with a filtered list. Currently I am able to have the search icon blink when inputting text into the search bar, indicating that the js file is being read, however no changes are made to the recipes and nothing is fading in/out. If I add in the following tail ".../?q="chicken" for example, I am able to load the page with filtered recipes for all recipes with "chicken" in the title, however it is not occurring asynchronously. Would anyone know what the issue is in my code? I am currently using Django 3.1.2 main.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" … -
CSRF cookie not set: POST from Javascript to separate Django project
I'm developing two separate django (version 3.1) projects. I keep getting a "403: CSRF cookie not set" error and have no idea what the problem is. Project 1 is running on an Apache server & takes POST requests containing JSON data & sends back a JSON response. Project 2, running on localhost, sends the POST via Javascript XMLHttpRequest() function to Project 1. This question seems to be having the same problem as me, but I'm trying to send info between different URL's (more specifically, POST from localhost:8000, eventually url.com, to engine.url.com) and I don't think that user's solution will work for me. I've tried using the @csrf_exempt decorator on Project 1 views.py, and it works just fine. However, personally identifying information might be sent between the two, so I want to make sure things are secure. A csrf cookie is best practice if I'm not mistaken, so I have the decorator @ensure_csrf_cookie before my view. I've tried everything I could find online to fix the problem. In Project 1 settings.py, I've included 'corsheaders' in my INSTALLED_APPS, 'django.middleware.csrf.CsrfViewMiddleware' in MIDDLEWARE and have the following code at the end of the file: CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False CORS_ALLOWED_ORIGINS … -
Postgresql - password authentication failed for user
Well, I've been working on a project on Django, but a friend of mine was facing a problem so he sent me his project (The entire folder). Anyway, I tried to run the server but it didn't work. I tried to change the password and the username from the settings file, and when I tried to access the user, the username was changed (as the sql shell recognized it, I think ¯_(ツ)_/¯), but whenever I try to login with the password I wrote in the settings file it produces the following error: django.db.utils.OperationalError: FATAL: password authentication failed for user "Youssef" Here's the DATABASE part in the settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Boards_django', 'USER': 'Youssef', 'PASSWORD': '000000', 'HOST': 'localhost', 'PORT': '5432', } } BTW, the database is recognized by the PgAdmin4: Any idea what should I do??? Side note: I can't access the user, hence I'm not able to use any of the commands of postgresql -
Django admin form, thows error while set ArrayReference field, Djongo
I'm newbie in Django, I got an error when trying to set ReferenceField to Record This is models: from djongo import models class Record(models.Model): _id = models.ObjectIdField(primary_key=True) text = models.TextField() attatched_file = models.FileField() file_type = models.TextField() class Diary(models.Model): _id = models.ObjectIdField(primary_key=True) title = models.TextField() records = models.ArrayReferenceField(to="api.Record", on_delete=models.CASCADE) Can someone tell whats am I doing wrong? -
django: Issue with the url paths
I need little help with how to redirect the link to the right url. I have one object that has 2 categories rents and sales. When the form is submitted I can successfully redirect the user to the right place but that is from the views --- return redirect(category +'/'+ listing_id) --- Any trick how can I do the same from the HTML? Any help is appreciated! urls. path('rents/',rents, name = 'rents'), path('rents/<int:pk>',RentView.as_view(), name = 'rent'), path('sales/',sales, name = 'sales'), path('sales/<int:pk>',SaleView.as_view(), name = 'sale'), html: First one has url localhost/dashboard/sales/1 . It should be localhost/sales/1, but I'm not sure how to remove that dashboard. Since the current page is dashboard. <td class="column3"><a href = "{{contact.category}}/{{ contact.listing_id}}" ><button class='btn-view'>View</button></a></td> Second case: I have two categories: sales and rents. It seems to work if I leave it like this, but if there is a query from rents it will redirect the URL to sales. <td class="column3"><a href = "{% url 'sale' contact.listing_id %}" ><button class='btn-view'>View</button></a></td> -
How To Get A Free Customized And Full Betting Html, Css, python or Django Templates For My Design
I developed a betting application with django and python and the template am working on is very displeasing and bad (it look too static and nothing dynamic about it). i need help with a free html template- am just a little Woman and a simple Lady that have given everything to python django and begin to learn web and app development. i need a free templates for a betting website and i will be glad if there is anyone that can help. i have to to get this templates from online but it seems not possibe am been ask to buy the few i saw online and i dont have cash for that seriously. -
Django Model Forms - Adding widget that assigns css class causes browse file button to disapear for FileField
for some reason if I try to assign a css class to a model form filefield the search button disappears forms.py class CsvForm(forms.ModelForm): class Meta: model = Csv exclude = ('user',) labels = {'file_name' : 'Browse'} widgets = { 'file_name': forms.TextInput(attrs={'class': 'form-control'}), } models.py class Csv(models.Model): file_name = models.FileField(upload_to='csvs', max_length = 100) public = models.BooleanField(default = False) user = models.ForeignKey(User, on_delete = models.CASCADE, null = True) def __str__(self): return "File id: {}".format(self.id) If I delete the widget, the button reappears and I can search for files again. Why does this happen? -
How to use Flutter's Streambuilder with Django Rest Framework?
I am very new to coding. I want to know how to use Flutter's Streambuilder with a Django Rest Framework as backend? I know to use Streambuilder, but how do I code for the same with Django? -
Why do django migrations temporarily take disk space?
Setup: Django (2.2.18) and Postgres (9.5) in one server, same disk. Migrations are altering 1 table (adding and removing fields). I'm not sure if my question is correct but I ran into a problem with my setup above while applying migrations. Error is from psycopg2: DiskFull: could not extend file "base/167296/1842042": wrote only 4096 of 8192 bytes at block 161 HINT: Check free disk space. Current disk usage is 14G out of 20G. We resolved the issue by deleting a few files and running the migrations again. We observed that the disk usage temporarily increased to about 96% of 20G then went back to 14G. Now we need to do something so the issue doesn't happen again. My question is: if we move the database to something like RDS, will it be enough? I ask because I'm not sure if it's the database size that temporarily inflates or if it's django that creates temporary files on disk. In the second case, it would mean that moving the database will not actually solve the issue. I'd appreciate references as I couldn't find anything on this on the django docs (or I'm blind). -
Download a file that is uploaded on Django admin page on the user's view
I looked everywhere for a solution, I am creating a Capture The Flag game using Django, I have everything ready, but the download part. I want to let the people who are playing can be able to download the files I upload from my side on the Django Admin page. models.py class Questions(models.Model): Qid = models.IntegerField(default='0') Qtitle = models.CharField(max_length=70) Qdes = models.CharField(max_length=1000) Hint = models.CharField(max_length=500, default="") file = models.FileField(blank=True) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('404', views.error, name='error'), path('register', views.signup, name='signup'), path('about', views.about, name='about'), path('login', views.login1, name='login1'), path('profile', views.profile, name='profile'), path('QUEST', views.Quest, name='Quest') quests.html <a target="_blank" href="_Blank" class="btn btn-outline-secondary btn-shadow"><span class="fa fa-download mr-2"></span>Download</a> <a href="#hint" data-toggle="modal" data-target="#hint" class="btn btn-outline-secondary btn-shadow" onclick="getHint({{question.Qid}})"><span class="far fa-lightbulb mr-2"></span>Hint</a>``` -
Why does django rest framework app works locally, but can only do GET requests when deployed to heroku?
I cannot do methods other than GET when accessing the API on heroku. Else, I get a 500 internal server error. I suspected that it had to do with permissions: REST_FRAMEWORK = { 'TEST_REQUEST_DEFAULT_FORMAT': 'json', # Authentication Scheme 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), # Permission Policies 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } However, when I tried commenting out the DEFAULT_AUTHENTICATION_CLASSES, I still couldn't log in. I am using django-rest-auth if that helps (https://django-rest-auth.readthedocs.io/en/latest/installation.html) Again, it works on my local server (I haven't tried heroku local though). What else am I missing?