Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't import image in Django
Here is my project structure I'm trying to display the image from the static folder but it can't be displayed. I also tried to mention the static folder in the settings.py file as below: Here is how I'm calling the image from the base.html file. I'm not sure what is wrong, I tried to search but the google sources can't help. -
How to add a horizontal rule in bootstrap?
I'm trying to add a horizontal rule in-between my divs. Here is my code. Div("Name", css_class='col-sm-12'), Div("Address", css_class='col-sm-6'), Div("Favorite_Movie", css_class='col-sm-6'), <hr> <-- Horizontal rule would go here. -
Key encyption, front-end back-end question
I have a front end which has some api credentials which are needed to receive information for the front-end. I also want to store these credentials in a database so that the user does not need to enter these api credentials with every log in, rather the api credentials are 'there'. How should these api keys be stored in the back end and then de-crypted in the front-end? -
Django: On button/link click, send an API request, fetch data, save it in a variable, and put variable in textarea/textbox without refreshing page
I've been breaking my head attempting to come up with a simple solution to something I had in mind. What I'd like to have is: User clicks on a button or a link disguised as a button to reveal information. The server will then send an API request to https://randomuser.me/api, which is outside of the domain. The first name of the random user in the API will be stored in a variable. The variable storing the first name will then be put in the textarea. The button's text will change to "hello" as a greeting instead of just "button" and will not be clickable from now on. OR TO BE FANCY: It can have a timer counting down from 20 minutes. The div that was hidden previously will now show up with the updated button and the textarea filled in with the first name of the random person, ready for the user to copy. I know I can use Python to get requests results from the server. I just don't know how to implement that with Django with the features I want above, especially without Django reloading/refreshing the page. The HTML page: <div> <a href="#" class="button" onclick="showButtonDetails()">button</a> <div id="showDIV" style="display: … -
Custom Django User not saving
So I'm trying to create a user with many fields. I followed a tutorial on how to create a custom user model by inheriting from the base user class and then creating a user manager. I had one of my past professors take a look at it and he couldn't find anything that would keep it from saving, kind of at a loss here. class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser Full_Name = models.CharField(max_length=200) industry_type = models.CharField(max_length=200) presenter = … -
Deployment Error Heroku [Remote rejected] master -> master (pre-receive hook declined)
I am trying to deploy my app in Django/Heroku but I am having this issue while doing git push Heroku master. This is the error I am getting after this command. Enumerating objects: 654, done. Counting objects: 100% (654/654), done. Delta compression using up to 8 threads Compressing objects: 100% (637/637), done. Writing objects: 100% (654/654), 10.77 MiB | 525.00 KiB/s, done. Total 654 (delta 138), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Requested runtime (python-3.6.8) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to warm-taiga-11044. remote: To https://git.heroku.com/warm-taiga-11044.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/warm-taiga-11044.git'``` -
Djanto Singnals is not triggering through admin panel
I have a library that syncs some models with the s3 bucket, so, when someone deletes some row, it should receive the signal and activate the function. Here is the function: @receiver(post_delete) def on_object_deletion(sender, instance, **kwargs): """Upload deleted object to cloud if it is part of synced model""" deletion_time = datetime.datetime.now() # Retrieve the metadata (app and model name) for the model contenttype = ContentType.objects.get_for_model(model=instance) # Skip unnecessary database lookup (never syncs its own models) if contenttype.app_label == "lakehouse_sync": return syncmodel = SyncModel.try_retrieve_model(contenttype.app_label, contenttype.model) if not syncmodel: return # Raise exception if the instance is not BaseSyncModel. # Should be caught during clean() though. if not isinstance(instance, BaseSyncModel): raise Exception("Cannot sync a model that does not inherit BaseSyncModel") # Manually update the timestamp so the lakehouse can merge data instance.updated_at = deletion_time # Write the serialized object to the cloud blacklist = syncmodel.get_blacklist() serialized = Serializer.serialize_object(instance, blacklist) CloudActions.write_delete_file( contenttype.app_label, contenttype.model, serialized.getvalue() ) I didn't set the sender because I'll use this function for any model that inherits from the SyncModel. I'd like to ask for some help to figure out how to activate the signal when I made some deletions through the admin panel. I didn't understand the reason why … -
Maintaining history by soft deleting the row of table
Initially, I was hard deleting SQL rows. Now, I want to soft delete the row by adding a new column in table 'is_active'. if is_active=False, this means the row is deleted, and it is now part of history. But the concern is with the other tables where this table is referenced via a foreign key. earlier, when deleting this row, automatically deletes the record from other tables(model.cascade). Example; Table 1{ id uuid, is_active bool, . . } Table2{ id uuid, fk foreignKey(Table1, on_delete=models.cascade) } Table3{ id uuid, fk foreignKey(Table1, on_delete=models.cascade) } Now, if I will soft delete the table1(making is_active=False), then I have the following option, Add is_active columns to all other tables also which is referencing table1. and follow the same procedure to these tables as for table1. ISSUE: it will be a very hectic task, as some other tables might be pointing to table2, which in result may be referenced by some other tables. and we have manually set is_active=False for table2 and table3. QS. Is there any better approach for soft_deleting the table? like something like that, Table2{ id uuid, fk foreignKey(Table1, on_is_active_is_False=set.is_active=False), is_active bool } -
Django elasticsearch DSL with custom model fields (hashid field)
I have a model that uses django hashid fields for the id. class Artwork(Model): id = HashidAutoField(primary_key=True, min_length=8, alphabet="0123456789abcdefghijklmnopqrstuvwxyz") title = .... This is the related item of another model class ArtworkFeedItem(FeedItem): artwork = models.OneToOneField('artwork.Artwork', related_name='artwork_feeditem', on_delete=models.CASCADE) Now I'm trying to setup [django elasticsearch dsl] (https://github.com/django-es/django-elasticsearch-dsl) and to that end have the Document @registry.register_document class ArtworkFeedItemDocument(Document): class Index: name = 'feed' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } artwork = fields.ObjectField( properties={ 'id': fields.TextField(), 'title': fields.TextField( attr='title', fields={ 'suggest': fields.Completion(), } ) } ) class Django: model = ArtworkFeedItem fields = [] related_models = [Artwork] However, when I try to rebuild indices with python manage.py search_index --rebuild I get the following exception elasticsearch.exceptions.SerializationError: ({'index': {'_id': Hashid(135): l2vylzm9, '_index': 'feed'}}, TypeError("Unable to serialize Hashid(135): l2vylzm9 (type: <class 'hashid_field.hashid.Hashid'>)",)) Django elasticsearch dsl clearly does not know what to do with such a hashid field. I thought maybe I could just make my own HashIdField like from elasticsearch_dsl import Field class HashIdField(Field): """ Custom DSL field to support HashIds """ name = "hashid" def _serialize(self, data): return data.hashid then use it in 'id': HashIdField, but this gave me yet another exception elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'No handler for type [hashid] declared on field … -
Change sorting order for foreign key entity on Django
I would like to rearrange this dropdown to were profiles are sorted based on A-Z order based on the name. I would like to leave the string formatted in the same format it is now just have them sorted from A-Z. -
Nginx-ajax-django: 504 timeout error on page, error-log: upstream timed out (110: Connection timed out) , TTFB>1
I have a django application running on an nginx server which uses ajax to do asynchronous rendering of an html page. I have got the 504 gateway timeout tried almost every solution mentioned in stack overflow nothing worked out. In my application, I upload an excel sheet from which data is parsed, processed, pushed into database and then status of processing is displayed on an html page. I realized that first two to three rows of data are being processed normally and result is also being displayed correctly.For the remaining rows the backend process is happening correctly but ajax is not receiving the status message from django view. It is showing 504 error message. The error logs are showing upstream timed out error. I even included timeout:333333 in my ajax code. If I make async:false in ajax , process is slowing down and I am getting page unresponsive error message. By closely observing I realized that for processes which are incomplete TTFB is becoming more than 1. So can someone explain what to do? nginx.conf events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush off; tcp_nodelay on; keepalive_timeout 605; types_hash_max_size 2048; … -
Image url in django template doesnt work in production
I'm trying to show images in a one-to-many relationship with a Post model. The Post model is in a one-to-many relationship with a Category model. My code works with debug: True but fails in production. Can anyone see why? settings.py: import os BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEBUG = False models.py: class BlogImage(models.Model): b_img = models.ImageField("Blog Image", null=True, blank=True, upload_to="img/b", default='imagedefault.jpg') postimg = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True) class Post(models.Model): ... category = models.ForeignKey('PortfolioCategory', on_delete=models.SET_NULL, blank=True, null=True) class PortfolioCategory(models.Model): category_name = models.CharField(max_length=100, unique=True) urls.py: from django.conf.urls.static import static ... urlpatterns = [...]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html: {% for category in categories %} {% for post in category.post_set.all %} {% for img in post.blogimage_set.all %} <img src="{{ img.b_img.url }}" alt=""> {% endfor %} {% endfor %} {% endfor %} This code returns ValueError: The 'b_img' attribute has no file associated with it. I'm losing my marbles trying to make this work. Thanks in advance for anyone who can help ! -
Django's change password form (views.py)
I have an issue... I really dont know how to remove the help_text,label or wathever it is in the change_password form views.py . Please help me. Look the picture I linked for more information about ... enter image description here this is the picture , between the inputs you can see the text with markers, how can i remove it ? -
After adding an URL link, the text type and size changes automatically. How can I sort out this issue?
I have the following in django-ckeditor settings CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } and I have a simple model class Faq(models.Model): question = RichTextUploadingField() answer = RichTextUploadingField() Output screenshot below The font type and size change automatically to a smaller one after adding a link. You can see this in the above screenshot. It seems to me it automatically changes to the default setting. How can I access the default text setting? Can you please help me to troubleshoot this issue? I am using the django-ckeditor 6.1.0 version and Python 3.7. Thanks -
What are the current ways to get_absolute_url for django-mptt?
I read other questions, but I didn't find anything useful for Django 3, they just don't work. The link type is needed like this: post/categories/subcategories/**etc I think an adequate answer will be useful for everyone. Tell me how to do it for DetailView class Category(MPTTModel): title = models.CharField(max_length=255, verbose_name=_('Заголовок')) slug = models.SlugField(max_length=255, verbose_name=_('URL'), blank=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) class MPTTMeta: order_insertion_by = ['title'] class Meta: unique_together = ['parent', 'slug'] verbose_name = _('Категория') verbose_name_plural = _('Категории') urls.py urlpatterns = [ path('category/<slug:slug>/', CategoryListView.as_view(), name='category_detail'), ] views.py class CategoryListView(ListView): model = Category template_name = 'modules/post/category_detail.html' context_object_name = 'category' queryset = Category.objects.all() def get_queryset(self): queryset = self.queryset.filter(slug=self.kwargs['slug']) return queryset -
template_view error - [Errno 13] Permission denied
PermissionError at /blog/template_view/ [Errno 13] Permission denied: 'C:\DJango\denv\lib\site-packages\django\contrib\admin\templates' Request Method: GET Request URL: http://127.0.0.1:8000/blog/template_view/ Django Version: 3.2.6 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'C:\DJango\denv\lib\site-packages\django\contrib\admin\templates' Exception Location: C:\DJango\denv\lib\site-packages\django\template\loaders\filesystem.py, line 23, in get_contents Python Executable: C:\DJango\denv\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\DJango\myproject', 'C:\Program Files\Python39\python39.zip', 'C:\Program Files\Python39\DLLs', 'C:\Program Files\Python39\lib', 'C:\Program Files\Python39', 'C:\DJango\denv', 'C:\DJango\denv\lib\site-packages'] Server time: Wed, 18 Aug 2021 02:29:57 +0000 Traceback Switch to copy-and-paste view I am getting this error. please someone help me out -
TemplateDoesNotExist at / template path
I want to create the backend of a portfolio and I'm trying to use a template but it says it doesn't exist but shows the correct file path in the error message. This is my views.py: from django.shortcuts import render from django.http import HttpResponse from django.template import loader def home(request): template = loader.get_template('home.html') return HttpResponse(template.render(request)) And this is my templates setting: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ .... ], }, }, ] The directory structure is: my project my project -init.py -settings.py -urls.py -manage.py -my app templates static -
models.E005 The field 'xxx' from parent model 'x.x' clashes with the field 'xxx' from parent model
Django inheritance error: (models.E005) Do you have a solution to get around this problem, is there a way to add a prefix or idk because I must have several User with the same heritage? Django dont like this: class Dispositif(Infos, ChefGO, ADJChefGO): bcs ChefGO and ADJChefGO depend on the same class Member, but i realy need two member class Members(models.Model): phone_regex = RegexValidator(regex=r'^[0-9]{10}$', message="Error: Format 0611223344") indicative = models.CharField(max_length=16, default="Default indicative") phone = models.CharField(max_length=10, validators=[phone_regex]) class Meta: abstract = True class ChefGO(Members): pass class ADJChefGO(Members): pass class Dispositif(Infos, ChefGO, ADJChefGO): name = models.CharField(max_length=32, default="Name") place = models.CharField(max_length=64) start_date = models.DateTimeField(default=datetime.datetime.now) end_date = models.DateTimeField(default=datetime.datetime.now) Thanks -
Is there a way to set a different pickle version for Django cache when using the DatabaseCache?
Due to legacy code I'm uploading database cache from my local machine to production. However as I'm using python 3.9 and production is running python 3.7, I'm running into "unsupported pickle protocol" errors when the cache is used (ValueError: unsupported pickle protocol: 5). Is there any way to set the pickle version on my local to match the version? or any method to transform it? ...or am I stuck installing and using python 3.7 for this project? -
Django ModelChoicefield not saving
in the following project i managed to add form fields and save the changes made to them. But then i added ModelChoicefield, that takes the list of fields from a model as a list of possible answers. Example: Defect_Area = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Defect_Area_dv',flat=True).distinct(),widget=forms.Select) The only problem is that as soon as I added these ModelChoicefield, the data wont save, but it will just return to blank. When i now click submit, the changes will stay but if i refresh the page it goes back to how it was: Forms.py: class auditForm(ModelForm): class Meta: model = auditsModel fields = '__all__' #RADIO BUTTONS CHOICES = [('Defect', 'yes'), ('No Defect', 'no')] CHOICES_Action_correctly_captured = [('yes', 'yes'), ('no', 'no')] Audit_outcome = forms.ChoiceField(choices=CHOICES, widget=RadioSelect()) Action_correctly_captured = forms.ChoiceField(choices=CHOICES_Action_correctly_captured, widget=RadioSelect()) Defect_Area = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Defect_Area_dv',flat=True).distinct(),widget=forms.Select) Key_Driver = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Key_Driver_dv',flat=True).distinct(),widget=forms.Select) Sub_Key_Driver = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Sub_Key_Driver_dv',flat=True).distinct(),widget=forms.Select) Metric_name = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Metric_name_dv',flat=True).distinct(),widget=forms.Select) Correct_Associate_Action = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Correct_Associate_Action_dv',flat=True).distinct(),widget=forms.Select) Correct_investigator_Action = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Correct_investigator_Action_dv',flat=True).distinct(),widget=forms.Select) Action_Correctly_Captured = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Action_Correctly_Captured_dv',flat=True).distinct(),widget=forms.Select) Audit_Outcome = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Audit_Outcome_dv',flat=True).distinct(),widget=forms.Select) Type_of_Audit = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Type_of_Audit_dv',flat=True).distinct(),widget=forms.Select) If_Correctly_Captured_No = forms.ModelChoiceField(queryset=dv_model.objects.values_list('If_Correctly_Captured_No_dv',flat=True).distinct(),widget=forms.Select) #Status = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Status_dv',flat=True).distinct(),widget=forms.Select) #Defect_Area_Investigator = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Defect_Area_Investigator_dv',flat=True).distinct(),widget=forms.Select) def __init__(self, *args, **kwargs): super(auditForm, self).__init__(*args, **kwargs) # Makes the field un-editable #FIELDS----------- # IPV COMMENT BOX self.fields['QA_Comments_on_Associate_Action'].widget = forms.Textarea( attrs={'class': 'form-control', 'style': 'height: 100px'}) # Sets the size of the widget # SIV COMMENT BOX self.fields['QA_Comments_on_investigator_Action'].widget = forms.Textarea( attrs={'class': 'form-control', 'style': 'height: 100px'}) … -
Django custom permission class is not working
I am using Django REST for my API. Here is my custom permission class: permissions.py: from rest_framework.permissions import BasePermission from rest_framework.response import Response class ItemsPermissions(BasePermission): def has_permission(self, request, view): try: request_data = request.data print(request_data) auth_token = request_data['returnedDataFromAuthAPI'] if("accessToken" in auth_token): auth_token = auth_token['accessToken'] Response({"Permission Granted - AccessToken": auth_token}) return True #else Response({"message": "No Auth Token Provided! You Need To Login!"}) return False except Exception as ex: return Response({"message": ex}) in views.py: class ListItems(generics.ListAPIView): permission_classes = [ShippingPermissions] queryset = myModel.objects.all() serializer_class = mySerializer in urls.py: url_patterns = [ path("/items/list/", ListItems.as_view()), ] I have an authentication microservice that I get the JWT Token from, for the user to have access to the views. In the ItemsPermissions class I am checking the token. My Question: I want to grant the user access to the ListItems class, after the token is provided, but if token is not provided then the user should not have access. However, for some reason, I am able to access the /items/list/ endpoint, and it does not ask me for a token at all. What is the problem ? -
cannot cast type date to time without time zone LINE 1: ...COLUMN "creation_date" TYPE time USING "creation_date"::time (DJANGO - Heroku)
I am trying to upload my Django-project to Heroku. I run the following command like i have always done: git add . git commit -am "" git push heroku master heroku run bash $- python manage.py migrate //this for apply all the migrations Once i ran them i got the cannot cast type date to time without time zone. I have already found some answers but none of them works for me. I have already set the TIME_ZONE in settings.py This is the migration that gives me the error: # Generated by Django 3.1.7 on 2021-08-16 16:29 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('website', '0009_order_creation_date'), ] operations = [ migrations.AlterField( model_name='order', name='creation_date', field=models.TimeField(default=django.utils.timezone.now, verbose_name='Data Ordine'), ), ] -
Gunicorn [CRITICAL] WORKER TIMEOUT, When redirection
I'm newbi in development. I would appreciate it if you could help me solve this problem. I'm making a social login system in Nginx + gunicorn + Dango by DRF. An error occurs when I request GET {api-path}/kakao/login from my server. My server has to serves to give user's token and to redirect user. The new/old user login is completed successfully, But ** user's page doesn't switch and doesn't get the token.** when I run python manage.py runserver 0.0.0.0:8000, No error occurs and a normal token value is returned. But If I use gunicorn or uwsgi, the error occurs. How can I solve this problem? I have summarized my attempts and my code below. 1. I tried https://www.datadoghq.com/blog/nginx-502-bad-gateway-errors-gunicorn/ check "Gunicorn is not running" other requst like {api-path}/admin works normally. check "NGINX can’t communicate with Gunicorn" other requst like {api-path}/admin works normally. check "Gunicorn is timing out" When I runed python manage.py runserver 0.0.0.0:8000 and tried the problematic request, It took only 2 ~ 3 seconds to response. Because gunicorn's default time limit is 30 seconds, I think reason of my error has nothing to do with Nginx's timing out & Gunicorn's timing out. I tried uwsgi, uwsgi's socket too, but … -
Filter + Paginator not working as expected
I have a filter with a dependent dropdown as well as a paginator. The paginator and filter are working as expected except if the category has a page 2 it no longer filters the results and just displays everything in the db(paginated). How do I go about carrying the filter request into the paginator. view model = Post myFilter = carFilter(request.GET, queryset=Post.objects.all()) posts = myFilter.qs page = request.GET.get('page', 1) paginator = Paginator(posts, 2) page_obj = paginator.get_page(page) page_range = paginator.get_elided_page_range(number=page) context = { 'posts':posts, 'myFilter':myFilter, 'page_range': page_range, 'page': page, 'paginator': paginator, 'page_obj': page_obj } template {% for post in page_obj %} <article> <a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.year }}</a> <a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.manufacture }}</a> </article> {% endfor %} <nav aria-label="Page navigation example " class="paginator"> <ul class="pagination justify-content-center"> <li class="page-item"> {% if page_obj.has_previous %} <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> {% else %} </li> <li class="page-item disabled"> <a class="page-link" href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %} <li class="page-item active" aria-current="page"> <a class="page-link" href="#">{{ i }}</a> </li> {% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %} <li class="page-item"><a class="page-link" … -
fetch is returning html rather than JSON response
I am working on the cs50 web development project Network. Basically building a twitter copycat. It is still in process but so far I have two fetch requests for a JSON response. Once works perfectly but the other, which is a very similar request, returns html instead of JSON, causing an error. Can't figure out why this one doesn't work. Code snippets below: Here is the one that is returning html for my profile.html file for some reason. The commented out parts are the actual fetch JSON request but I temporarily changed it to show me in the console what is was returning. profile.js: function load_posts_profile() { console.log("load_posts_profile running"); document.querySelector('#prof-posts').style.display = 'block'; fetch(`/profile_posts`) //.then(response => response.json()) .then(response => response.text()) .then(text => console.log(text)) //.then(posts => { // Print posts //console.log(posts); //posts.forEach(post => show_posts_profile(post)); //}); } profile.html: {% extends "network/layout.html" %} {% load static %} {% block body %} {% if user.is_authenticated %} <!--insert profle name below in h3--> <h2 id="profile-name"></h2> <br> <h4 id="followers"></h4> <br> <h4 id="following"></h4> <!--add js to load user's posts only--> <div id="prof-posts"> </div> {% else %} <strong> Login To See Profile</strong> {% endif %} {% endblock %} {% block script %} <script src="{% static 'network/profile.js' %}"></script> {% endblock …