Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How I can compare the entered input value with the value of API in Django
Nowadays, I am trying to make a Post-Office Assistant web-site using Django. The things I have to do are: Creating homepage with a search input and submit button Getting the entered input value (namely, order ID) and compare it with the values (order IDs) in my API. If the value (order ID) is the same with any value (order ID) show the details of value (order ID) in my API. Otherwise show "There is no any profile with this order ID". Can anyone help me to create this website? Can anyone create and share source code as zip format with me? Thanks in advance. -
How could I add a helper function in Django to match a topic with its user and show Http404 if not the case?
thank you beforehand. This is my first post, I´ll try to be brief. I´m going through exercise 19-3 Refactoring in Python Crash Course. However I'm a bit stuck in it. I should make a function to check the owner of a topic, and if not the case raise a Http404 error. I tried to create a "utils" folder and house my function there, but had a Name Error, so I deleted it. Then tried to store the function in the same file, but I raised a Http404 error even when the user was the owner of the topic. I left it as before trying this exercise with the function in place commented out: from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) # check_topic_owner(request) if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def edit_entry(request, entry_id): """Edit an existing entry""" entry = Entry.objects.get(id=entry_id) topic = entry.topic # check_topic_owner(request) if topic.owner != request.user: raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) #The function to … -
Django Displaying images uploaded by ImageField properly
I'm building my own porfolio using Django, and I just had a question regarding uploading images using the ImageField. I uploaded an image through the admin page using ImageField, and after a long search session, finally got my page to display the image successfully. urls.py from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('pages.urls')), # main landing page path('admin/', admin.site.urls), path('project/',include("projects.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) projects.html <img src="{{project.image.url}}"> However, the official django docs say that this is not a good way to deploy a django site. Why is that, and what is the best/proper way to display images? -
Blocked by CORS policy : No 'Access-Control-Allow-Origin' header is present on the requested resource
Hi I am using django rest framework as API service and React as frontend.I can call the api from react when developing and when i deploy to iis.I got this error No 'Access-Control-Allow-Origin' header is present on the requested resource. I already do like this say=>CORS Error but I still got this error. My Django runs on localhost:81 My react app run on : 192.168.1.32:81 I can run this on local server which both installed but when I try on another computer I got this error. I used the fiddler 4 for override the port in the hostname. -
How to set initial value of primary key in django
I made this django model: class Car(models.Model): car_id = models.AutoField(primary_key=True) engine_size = models.FloatField() fuel_consumption = models.FloatField() def __str__(self): return(str(self.car_id)) The automatic field generator in django always starts from 1. How do I make it generate id from initial value=100. For example, 100,101,102... -
Django template ajax call to api - invalid literal for int() with base 10: '[object Object]'
Hi i'm trying to call to my django api from with an ajax call from my django template The API receive a POST request with the value of an id in the url My api view: @api_view(['POST']) def add_favorite(request, property_id): if request.method == 'POST': try: favorite_property = Property.objects.get(pk=property_id) if request.user.is_authenticated: login_user = request.user if not login_user.properties.filter(pk=property_id).exists(): login_user.properties.add(favorite_property) return JsonResponse({'code':'200','data': favorite_property.id}, status=200) else: return JsonResponse({'code':'404','errors': "Property already exists in favorite"}, status=404) except Property.DoesNotExist: return JsonResponse({'code':'404','errors': "Property not found"}, status=404) My html with the anchor link to ajax call: <a id="mylink" href="javascript:onclickFunction('{{ property.id }}')"> <i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i> </a> And this is how i call to API in my django view to try and get response: <script> $(document).ready(function () { $('#mylink').on('click', function (property_id) { property_id.preventDefault(); $.ajax({ type: "POST", url: "http://localhost:9999/api/add_favorite/" + property_id.toString() + "/", beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}'); }, success: function (data) { var obj = jQuery.parseJSON(data); alert(obj); } }); return false; }); }); </script> When i try to press the link it return the following error: ValueError: invalid literal for int() with base 10: '[object Object]' web_1 | [24/Sep/2019 03:13:14] "POST /api/add_favorite/[object%20Object]/ HTTP/1.1" 500 17473 I tried to turn the property_id … -
How do I get the specific ID of my survey question in question set filtered by department in URL Template Django
How do I get the specific ID of my survey question in question set filtered by department in URL Template Django? def survey_select(request, id): try: department = Department.objects.get(id=id) except Department.DoesNotExist: raise Http404("No MyModel matches the given query.") department = Department.objects.get(id=id) questionset_list = QuestionSet.objects.filter(department=department) context = {'questionset_list': questionset_list} return render(request, 'question_set.html', context) def test_survey(request, id): try: department = Department.objects.get(id=id) except Department.DoesNotExist: raise Http404("No MyModel matches the given query.") department = Department.objects.get(id=id) question_set_items = QuestionSet.objects.filter(department=department) question_set = (c.name for c in question_set_items) print("Question for this department") print(question_set_items) if request.method == 'POST': form = ResponseForm(request.POST, department=department) if form.is_valid(): response = form.save() form = ResponseForm(department=department) # return HttpResponseRedirect("/survey/%s" % response.customer_uuid) messages.success(request, 'Thank you!', extra_tags='alert') else: form = ResponseForm(department=department) print(form) # TODO sort by question_set return render(request, 'survey.html', {'response_form': form, 'department': department, 'question_set': question_set}) -
How can I update a field in two tables in django with a query?
I'm trying to update two fields in two tables using Django's orm. model like this: class User(models.Model): name = models.CharField(...) age = models.CharField(...) class Blog(models.Model): user = models.ForeignKey(User, ...) user_name = models.CharField(...) text = models.TextField(...) How to implement MySQL statement: update user a, blog b set a.name = 'new name', b.user_name = 'new name' where a.id = b.user_id and a.id = 1; -
Need help accounting for latency in simple multiplayer game
At the moment, to account for latency, in my game (it is essentially tron lightcycles, but to move, one must solve a math problem), I send out the game state to both players every time one of the players turns. On the frontend, I have a function that draws and a function that undraws (to account for when there is latency). Currently, the setup is not performing the desired behavior: the players are not in sync with each other (neither movements nor positions at which users turn are the same for both players). Can someone help me out? This is my first time making a game. Here is the backend code: def send_answer(answer, game_object, player_type, current_position, current_direction): creator_directions = ['p1up', 'p1right', 'p1down', 'p1left'] opponent_directions = ['p2up', 'p2right', 'p2down', 'p2left'] with transaction.atomic(): # d for direction if player_type == 'creator': for d in creator_directions: if is_correct_answer(getattr(game_object, d), int(answer)): context['move_direction'] = d print(context) new_problem = generate_problem_game( game_object.level, game_object.operation, game_object, player_type) setattr(game_object, d, new_problem) game_object.save() context['new_problem'] = [d, new_problem] # calculate draw and undraw positions p1_last_pos = game_object.p1lastposupdate p1_lp_timestamp = game_object.p1lpuTimestamp time_inbetween = timezone.now() - p1_lp_timestamp ti_milliseconds = time_inbetween.seconds * 1000 p1_lp_split = p1_last_pos.split(',') p1_lp_x = int(p1_lp_split[0]) p1_lp_y = int(p1_lp_split[1]) draw_positions = [] … -
Saving a JSON Array list of values to MySQL
I have been stuck with this code in the Python views. What I'm doing is, I'm trying to get the JSON array list that came from the local storage, and individually transfer it, using self.request.POST[]. Also the values came from modal. I'm still new to Python, so I still don't know how some functions work. I've tried the for range(len()), and it works in accessing the values of each array list. the problem is I can't save this using the POST method. is there a way I can store this to the database. itemdata = self.request.POST['itemdata'] jobject = json.loads(itemdata) for i in range(len(jobject)): print(jobject[i]['invitem_id']) invitem_id = jobject[i]['invitem_id'] invitem = Inventoryitem.objects.get(pk=self.request.POST['invitem']) self.object.invitem = invitem.id[invitem_id] Here are the array list values, I want to be stored. [{"invitem_id":"85","invitem_code":"01086","invitem_desc":"1/2 PROGRAMMING FOR PONGRASS PONENTRY","charging_type":"P","unitofmeasure_id":"2","unitofmeasure_code":"BX","quantity":"123","discountamount":"123","discountrate":"%","unitcost":"123","grossamount":"123","netamount":"123","vatable":"123","vatexempt":"123","vatzerorated":"123","vatamount":"123","branch_id":"5","branch_code":"HO","department":"24","department_code":"AM","employee_id":"784","employee_code":"012068506","employee_name":"RAMONA ABAD","remarks":"123124"}] The output gives an error invalid literal for int() with base 10: '' -
django 2.2.5 product not displaying in shopping cart
I am creating a e-commerce site using django 2.2.5. I've been following a tutorial on udemy where the instructor is moving at a rapid pace and he's using an older version of django i am continuously trying to pause just to ensure my code is correctly (it's AWFUL). I am now creating a shopping cart. The price is updating correctly but the product(s) price and description are not displaying. I've back tracked checked all the videos leading up to this part of the project but i can't seem to find what i've done incorrectly, so i've decided to come here for a second / third set of eyes that maybe able to see why the product(s) price and description are not displaying. cart (cart.html): I have a forloop.counter that is looping through the products and is suppose to display the price and description of products added to the cart. {% extends 'base.html' %} {% block content %} {% load staticfiles %} <div class="pb-5"> <div class="container"> <div class="row"> <div class="col-lg-12 p-5 bg-white rounded shadow-sm mb-5"> <!-- Shopping cart table --> <div class="table-responsive"> {% if cart.product.exists %} <table class="table"> <thead> <tr> <th scope="col" class="border-0 bg-light"> <div class="p-2 px-3 text-uppercase">Product</div> </th> <th scope="col" … -
Django app keeps crashing after an exception until it is restarted
I am using Django + uWSGI + nginx to serve an application. All requests from the front end are post requests. The Behaviour: In the code snippet below, the function, convert_data, connects to a database and converts request into resp. class ConvertDataView(View): def post(self, *args, **kwargs): request = json.loads(args[0].body.decode()) resp = api_utils.convert_data(request) if resp: return JsonResponse(resp, safe=False) return JsonResponse({}, status=404) When ever the inputs contains invalid characters such as \, ', " etc, convert_data raises an exception. This varies from database to database but it is form of "Query is invalid.". The Problem: All subsequent queries to this core/thread continue to fail, even if the input is correct and does NOT contain any invalid characters. This behavior causes the app to be unstable and serve the information when the request goes to another core/thread but fail when it comes to this "corrupted core/thread". This error will continue to persist until the uwsgi server is restarted. After the uwsgi server is restarted, the app acts normal again. Things that seem to work: If I perform exception handling in ConvertDataView, this issue seems to remain. However, it seems that if I perform my exception handling in convert_data and always send back a … -
How to display custom form in django-allauth's social account sign up flow
I am trying to achieve all these together: A. New users can sign up with or without using facebook. B. They will all be presented with a form to fill out additional user information as part of the sign up flow. C. New accounts will by default be inactive. Admins will need the additional user information when they manually activate (or delete) accounts. I achieved A using django-allauth social accounts. I achieved C by adding a listener to django.db.models.signals.pre_save and setting user.active = False I partly achieved B by defining a custom ACCOUNT_SIGNUP_FORM_CLASS in settings.py. However this only works for local "non-social" accounts as far as I can tell, since social logins seem to skip this form. My problem is that when someone signs up with an allauth social account they don't have the chance to provide additional information since their account will be created without first displaying my custom sign up form. Furthermore since all new accounts are automatically saved as inactive and that additional information is needed in order for admins to activate them I can't simply add that form to a "first time login flow" (note: it's not possible to log in to inactive accounts). One way … -
How to access Detail page in Dango Rest Framework
I am new to Django Rest Framework and I have ONE question: What is the equivalent to use get_absolute_urland get_object_or_404(model, id=id) to access a DETAIL page from a LIST page with django rest framework??? While reading the official documentation, I have the sense that HyperlinkedModelSerializer could help me achieve it but when I try to access the url : http://127.0.0.1:8000/ it crashes the app with the message below: Could not resolve URL for hyperlinked relationship using view name "post-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. (It crashes because I use URL in Serializer fields, when I use just id it works fine but unable to achieve 1/) I have the built the endpoint below: models class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title Serializers class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Post fields = ('url', 'author', 'title', 'body', 'company') URLS from django.urls import path, include from .views import ( PostList, PostDetail, UserList ) from . import views app_name = 'blog' urlpatterns = [ path('', PostList.as_view()), path('<int:pk>/', PostDetail.as_view()), ] VIEWS class PostList(generics.ListCreateAPIView): permission_classes … -
Django: I have an object A with FK on B. How can I display the columns from B in a dropdown in the form of A?
I am getting the error "Unknown field(s) (topic, subject) specified for Session". I am trying to build a drop down for subject and topic in my sessionForm. My model is below: class Subject(models.Model): name = models.CharField(max_length = 30, primary_key = True) def __str__(self): return self.name class Meta: db_table = 'subjects' class Module(models.Model): topic = models.CharField(max_length = 200) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) def __str__(self): return self.topic + ' in ' + self.subject.name class Meta: db_table = 'modules' class Session(models.Model): grade_level = models.CharField(max_length = 30) num_students = models.IntegerField(default=0) session_dt = models.DateTimeField() module = models.ForeignKey(Module, on_delete=models.CASCADE) @property def subject(self): return self.module.subject def topic(self): return self.module.topic def __str__(self): return self.module.topic + ' on ' + self.session_dt class Meta: db_table = 'sessions' My forms.py is class SessionForm(forms.ModelForm): class Meta: model = Session fields = ['subject', 'topic', 'session_dt', 'grade_level', 'num_students'] I am new to Django and Python. I already looked at Vitor Freitas article on Dropdown list. -
I want to get the value in td with jquery No output as a result of the alert Can you see where the wrong part is?
When the button is clicked <button type="button" class="plus_btn_for_user btn btn-outline-success" data-user_pk="{{u.pk}}" data-user_id="{{request.user}}"> <img src="{% static 'icon/plus.png' %}" alt=""> </button> I wanted to get the count number in td <td id="skill_note_point"> {{ u.recommandationuseraboutskillnote_set.count }} </td> I did this with jQuery const point = $(this).parent().find("#skill_note_point").text(); alert(point) There is no output alert(point) Is the jquery syntax wrong? text, val, html all did not work Is the selector wrong? I can't find the wrong part text, val, html all did not work Is the selector wrong? I can't find the wrong part Thanks for telling me what's wrong ^^; total code {% if user_list.exists %} {% for u in user_list %} <tr> <td>{{forloop.counter}}</td> <td id=user_name_{{u.id}}>{{u.username}}</td> <td> <input type="text" class="shortcut_subject_input_{{u.id}} form-control" value="{{u.profile.subject_of_memo}}"> {% if u.username == request.user.username %} <a href="" class="btn btn-outline-warning btn-sm update_memo_subject_btn" data-id={{u.id}}>수정</a> {% else %} {% endif %} </td> <td> <a href="" class="btn btn-outline-info move_to_user_btn btn-sm" id={{u.id}}>이동</a> </td> <td> <a href="" class="btn btn-outline-info btn-sm copy_to_me_from_user_id_btn" id={{u.username}}>copy_to_me</a> </td> <td> <button type="button" class="plus_btn_for_user btn btn-outline-success" data-user_pk="{{u.pk}}" data-user_id="{{request.user}}"> <img src="{% static 'icon/plus.png' %}" alt=""> </button> </td> <td id="skill_note_point"> {{ u.recommandationuseraboutskillnote_set.count }} </td> </tr> {% endfor %} {% else %} -
Saving GET parameter with User Profile in Django AllAuth
Users come to my site through a referral at example.com/accounts/signup/?ref=123. I use Django AllAuth to sign up users. I would like to save the referral code with their profile. It appears my options for this are: Edit the allauth signup view directly to allow this referral field to be saved Pass the ?ref=123 parameter to the next view after signup so that I can save it to the user profile in that view Create a session variable that gets remembered to the next view after signup so that I can save it to the user profile in that view How can I save the GET parameter to my user profile? Is there something that I can do to subclass the SignupView to save the data (option 3)? from allauth.account.views import SignupView class MySignupView(SignupView): ref = request.GET.get('ref') request.session['ref'] = ref Or is there a way that I can pass it in the form submit? (option 2) <form id="signup_form" method="post" action="{% url 'account_signup' %}?ref={{ request.GET.ref }}"> The page seems to be redirecting in more ways than I understand, so I am not able to retain the get parameters. -
Django how to detect/determine form FileField in template
I am trying to render customized base template for form view on my custom CBV approach Here i am looping through form visible fields, I am able to detect form choicefield/multiplechoicefied type as {% if field.field.widget.input_type == 'select' %} >my html stuffs {% endif %} In similar manner i need to detect form field FileField or ImageField In addition to this also I need to detect and differentiate form Fields ChoiceField and MultipleChoiceFild standalone to finalize my base form-view base template Thank you in advance -
Remove default select box option without JavaScript
I have 'country' CharField with choices on my custom User model, like this: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): address = models.CharField(max_length=200) address_number = models.CharField(max_length=20) phone = models.CharField(max_length=20) COUNTRY_CHOICES = [ ('US', 'United States'), ('UK', 'United Kingdom'), ('CA', 'Canada'), ('AUS', 'Australia'), ] country = models.CharField(max_length=30, choices=COUNTRY_CHOICES) ...and I'm using UserCreationForm, like this: from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): class Meta: model = get_user_model() fields = ( 'username', 'email', 'first_name', 'last_name', 'address', 'address_number', 'phone', 'country' ) I'm manually rendering form fields in my template, however the country field is rendered as a select box with one extra option: <option value="" selected="">---------</option> How can I remove that option and have my first option (in this case US) be selected as default? I'm trying to do it proper Django way without JavaScript. -
Conditionally prevent Django join with chained serializers
I have a serializer, requirementsSerializer, that fetches two chained tables, comments and relatedfiles. In my views.py, I know how to conditionally filter for the related tables if the user is logged in. What I am confused about, is how to exclude/prevent the chaining/joining if a user is NOT logged in. Right now, it returns the entire set of relatedfiles, for all users, if the user is not logged in, which is obviously a security issue. I know I could make a second serializer that doesn't join the other tables, but that does not seem efficient or clean. // serializers.py class RequirementsSerializer(serializers.ModelSerializer): relatedfiles_set = RelatedFileSerializer(many=True, read_only=True) comments_set = CommentsSerializer(many=True, read_only=True) class Meta: model = Controls fields = ('id', 'sorting_id', 'relatedfiles_set', 'comments_set', 'requirement', 'requirement_section', 'requirement_subsection', 'requirement_version') // views.py if request.user.is_authenticated(): queryset = Controls.objects.filter(requirement_version=requirement).filter(relatedfiles__team=request.user.team_id) else: queryset = Controls.objects.filter(requirement_version=requirement) -
Django; TemplateDoesNotExist error - blog app
Im trying to create a blog application following an oline tutorial but an struggling with loading some templates. It seems as if the templates in blog/templates/blog/... cannot be found. The page http://127.0.0.1:8000/blog/ loads fine. Included below is the current code from the settings.py, views.py and urls.py file. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party installs go here. 'products', 'pages', 'blog', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views.py from django.shortcuts import render, get_object_or_404 from django.http import Http404 # Create your views here. from .models import BlogPost def blog_post_list_view(request): qs = BlogPost.objects.all() # queryset -> list of python objects template_name = 'blog/blog_post_list.html' context = {"object_list": qs} return render(request, template_name, context) def blog_post_create_view(request): # create objects #template_name = 'blog/blog_post_create.html' context = {"form": None} return render(request, "blog/blog_post_create.html", context) def blog_post_detail_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) template_name = 'blog_post_detail.html' context = {"object": obj} return render(request, template_name, context) def blog_post_update_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) template_name = 'blog_post_update.html' context = {"object": obj, 'form': None} return render(request, template_name, context) def blog_post_delete_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) template_name = … -
Django: When a user uploads media to my site, it is owned by the server's root user. How do I change this?
I am unsure of what code you guys would want me to upload, but please ask away if you need any and I will upload it! When a user uploads media/files to my website, the root user becomes the owner of the file. This prevents the user from being able to open and view the media they uploaded, because it is not owned by the proper user on my server. I have a user that runs my Django application instead of the root user. The person who uploaded the media can access it once I manually go into the server and change the ownership to that media file that was uploaded, to the server user which runs my Django application. How can I get this to, by default, upload the file to the ownership of the server user running Django?? I was thinking of setting up a cron job to run every-so-often (this would be terrible for scaling) so I can change the ownership of the media without having to physically going in the server and do it myself. -
How safely reuse database records in MySql from Django (in Apache)
Long story short: In Django web application on Apache2 (linux) and MySql (ISAM) we need safely reuse some records marked as deleted, instead of creating new ones. Even if more users may request such action at the same time, each of them should obtain different record for reusing. The background: We have web application, where many users can do things at the same time. there are tables, that grows to infinity, but only few records are active (sometimes like from 100.000 long records is active 1.000 and no chance for reactivating any "deleted") sometimes are tranferred (to other places) just changes, so we mark "deleted" records as such and transfer them to delete records on the other side sometimes is needed to transfer the tables (to partial place) as whole and it takes too long the data integrity during the transfer is managed by other part of the project and should not do real problems Wanted: reuse some old and long time "deleted" records for new data it is not problem, to have reuse_me field in tables (default False, set to True after long time deleted, by some script). It can be safely assumed, that such records are nowhere referenced … -
DRF error: Could not resolve URL for hyperlinked relationship using view name on nested serializer
I am getting the following error on DRF: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "quotationitemfile-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. I did a Google search on this and it seems an error related to the HyperlinkedModelSerializer, but the thing is that I am not using it, I am using regular serializers: class QuotationItemFileSerializer(serializers.ModelSerializer): class Meta: model = QuotationItemFile class QuotationItemSerializer(serializers.ModelSerializer): files = QuotationItemFileSerializer(many=True) class Meta: model = QuotationItem class QuotationSerializer(serializers.ModelSerializer): items = QuotationItemSerializer(many=True) class Meta: model = Quotation And this error happens when a send a request to a ViewSet using the QuotationSerializer. I also noticed that the error disappears if I comment out the QuotationItemFileSerializer so I guess this is something related to DRF falling back to hyperlinks automatically. But I can't seem to get this to work propertly -
Django running a JS script that requires a JSON returning Not Found (static collected)
Disclaimer: I know very little Javascript I'm trying to run a TensorflowJS in a Django instance, I can successfully load the JS to call the tf.loadLayersModel function, however this function requires a json file (and another .bin file later) to run and the function isnt able to find it. Both the files (json and bin) are in the expected static directory (the same that loaded the JS file in the first place), but everytime I load the page Django returns Not Found: /myapp/test_model/model.json and the browser returns (through Inspect Element) Error: Request to model.json failed with status code 404. Please verify this URL points to the model JSON of the model to load. I'm using in settings.py: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Directory: myproject/ ++ static/ #(created by django) ++ __init__.py ++ settings.py ++ ... myapp/ static/ #(where I'm putting the files) ++ myapp/ ++++ test_model/ ++++++ model.json ++++++ otherfile.bin manage.py So the files are put in the static/myapp/test_model/ and after that i run python manage.py collectstatic the files get reconized, and copy to myproject/static/myapp/test_model/ The .html loaded at the view: (localhost/myapp/test_model/) <html> <head> {% load static %} ... <script src = "{% static "myapp/test_model/main.js" %}" > </script> </head> …