Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best solution to create live status/control web dashboard for running web scraper?
I have a few python web scrapers built using Selenium and Python. I'd really like to build a web-based front end for these that will show live (ie. without having to refresh the page) status updates from each of the 3 scrapers simultaneously, and allow control of them remotely (eg. starting/stopping, changing search terms/options, and exporting data as a downloadable csv). I've looked at the current python web dashboard solutions, all of which seem to fall short in some way or other - they're more aimed at data visualisation/graphing, don't update live etc. This leaves rolling my own: My current thinking is to use Django with the Channels package (to enable live updates), which feels like overkill and an overly complex solution, so I thought I'd ask here in case anyone knew of anything more suitable? If I did have to go with Django, since each of the 3 scrapers is currently a separately running Python script, how would I ultimately tie them all together so that they'd all be controlled by the web interface? Run them as separate threads within the central Django script perhaps? Many thanks for any insights you can offer! Rufus -
Customizing output file name
with open('media_cdn/account/pdf01.pdf', 'wb') as out_file: output.write(out_file) How can I format this to have a custom name for each output? For example, I have tried: author_id=str(instance.author.id) with open('media_cdn/account/{author_id}-pdf01.pdf', 'wb') as out_file: output.write(out_file) however, the file is output as "{author_id}-pdf01.pdf" -
Django-import-export always exports same file despite the changes in the resource
Hello I'm new to Django framework and got stuck with the below issue while using django-import-export in django admin panel. I have a relationship between two models via a Foreign Key and I would like to export an attribute instead of the "id" of the related item. I have tried the ForeignKeyWidget did not work. I have also tried to get the deserved attribute via defining fields and using underscore like "custodian__name" and no luck. Then I discover actually I cannot alter anything in the exported file(not even selecting which fields to export etc.) I have always saved my work and even tried to restart the server after each change, still no luck. No errors, I just keep exporting the same exact file which is the export of all the fields in the database. I cannot find what I'm doing wrong. Hope someone can help # admin.py from django.contrib import admin from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from import_export.admin import ImportExportModelAdmin from .models import Custodian, Asset class AssetResource(resources.ModelResource): custodian = fields.Field(column_name = 'custodian', attribute = 'custodian', widget = ForeignKeyWidget(Custodian, 'name')) class Meta: model = Asset fields =['tag_number', 'description', 'custodian',] class AssetAdmin(ImportExportModelAdmin, ExportMixin): resources_class = AssetResource admin.site.register(Asset, AssetAdmin) … -
How to organise unit-test for the javascript files in a django project so they can be run from CLI and be integrated to Gitlab-CI script?
I have made my project alone and as a hobby and looking for the professionnal methodology to do it: I have got my django project oganised in a standard way: Myproject +-- App1 │ +-- migrations │ +-- static │ │ \-- js │ +-- apps.py │ +-- __init__.py │ +-- migrations │ +-- static │ │ \-- js │ │ +-- App1.js # <-- javascipt for my first app │ +-- templates │ │ +-- App1.html │ +-- tests # <-- contains python tests for my first app │ │ \-- test_views_App1.py │ +-- tests.py │ +-- urls.py │ \-- views.py +-- App2 ... │ │ \-- js │ │ +-- App2.js # <-- javascipt for my second app ... │ +-- tests # <-- contains python tests for my second app │ │ \-- test_views_App2.py │ +-- urls.py │ \-- views.py +-- App3 ... +-- pytest.ini +-- manage.py For each of my app, I often have Javasript scipt for my frontend. I have used JQuery to build them so naturaly, I am thinking of using Qunit for my unit-test. The django documentation is quite succint about that subject. So I wonder what is the best practise for organising … -
Can we upload google sheets api credentials on github?
I have made a web application that uses Google Sheets as a database. I want to upload my project on github. But since it uses google sheets API for fetching data, I was wondering if is it safe to upload because I will also have to upload API credentials as well? I have seen a lot of questions like this on Stack Overflow but none of them addressed this question clearly. Also, my application/database is nothing confidential or anything like that. My only concern is if uploading API credentials can cause any harm to my google account? -
Django Rest Framework: In App purchase for Apple App store and Google Playstore
We're developing a mobile app. Users will be able to subscribe to our monthly services. We're using flutter and django. We had configured our payments to use stripe. But we've just learned that stripe is not compatible with the online stores for in app purchases. I am the django developer but I've never had to deal with integrating mobile apps. Is there a documentation/ package / integration method for django to use in app purchases? -
Cannot run migrate
I am referring to my privious question, which was not answered. Cannot run migrate while using an existing database I tried by myself all the methods I could find but all of them didnot work. Please take a look to my question. Thanks for the help. -
Django display error messages for default login backend
I am using Django's default authentication backend, and I cannot get the messages framework to work with it to show error messages (such as incorrect username, invalid password etc). Everything that I have searched through here to suggest to make a custom authentication backend, but is there any easier way to do it? I already have a form which is subclassing the AuthenticationForm to use form_valid method, is there anything I could do there? Any help would be really appreciated. -
ModuleNotFoundError at /api/social/convert-token No module named 'path.to'
Hi Im trying to Authenticate Users on an foodtasker project using POSTMAN, but I have an error, could anyone help me please. Error is the following: ModuleNotFoundError at /api/social/convert-token No module named 'path.to' Traceback: File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/braces/views/_forms.py" in dispatch 30. return super(CsrfExemptMixin, self).dispatch(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework/views.py" in dispatch 505. response = self.handle_exception(exc) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception 465. self.raise_uncaught_exception(exc) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework/views.py" in raise_uncaught_exception 476. raise exc File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework/views.py" in dispatch 502. response = handler(request, *args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework_social_oauth2/views.py" in post 70. url, headers, body, status = self.create_token_response(request._request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/oauth2_provider/views/mixins.py" in create_token_response 124. return core.create_token_response(request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/oauth2_provider/oauth2_backends.py" in create_token_response 149. headers, extra_credentials) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/base.py" in wrapper 116. return f(endpoint, uri, *args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework_social_oauth2/oauth2_endpoints.py" in create_token_response 60. request, self.default_token_type) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py" in create_token_response 60. self.validate_token_request(request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework_social_oauth2/oauth2_grants.py" in validate_token_request 91. user = backend.do_auth(access_token=request.token) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/social_core/backends/facebook.py" in do_auth 153. return self.strategy.authenticate(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/social_django/strategy.py" … -
mock.patch() Not patching function in module call, but is in test function
So I am trying to mock a function and it is not being mocked in the module where it is being called, but it when called directly in the test function. I am unsure what I'm doing wrong. I use patch all the time without any problems. So in the test I have below from unittest.mock import patch from django.test import TestCase from web.utils.registration import test_render_mock class TestRenderMock(TestCase): @patch("django.shortcuts.render") def test_render_mock(self, render_mock): request = self.make_request() # Calls render in same way in function below test_render_mock(request) from django.shortcuts import render r = render(request, 'c') print(type(r)) which is calling the function in the file web/utils/registration.py from django.shortcuts import render def test_render_mock(request): r = render(request, 'registration/signup_link_error.html') print(type(r)) And it isn't mocking the render call in the function test_render_mock but it is in the test function test_render_mock(). The console output is below. <class 'django.http.response.HttpResponse'> <class 'unittest.mock.MagicMock'> I have no idea what I'm doing wrong. Any help would be appreciated. Using python version 3.8.2 and Django 3.0.5 -
Test a Django model that uses request.user in save_model
I have a Django model that overrides save_model in order to automatically save the current authenticated user into a field on save. The question is, how in a unit test can I test the creation of this model, without having to go through a view? The model: class SomeClass(models.Model): def save_model(self, request, obj, form, change): self.prevent_update() if not obj.pk: # Only set added_by during the first save. obj.created = request.user super().save_model(request, obj, form, change) The test just wants to set up SomeClass before doing some other stuff. class SomeClassTestCase(TestCase): def setUp(self): self.assertTrue(request.user) SomeClass.objects.create(name="abc") I know that there is a request getting set up automatically, since request.user doesn't fail with request being None; instead, the query constraint fails because the user is null. How do I set a user on the request that appears to have been passed into save_model Alternatively, I know I can setup a request using RequestFactory and generate a user. In that case, how do I get that into the test so that the SomeClass.objects.create actually sees it. -
Python/Django creating several classes from variable through looping
I'm working with Python Django and I'm trying to create a forum with several subpages - each subpage concerns another topic and should look the same but store different posts. I want to create several classes (not instances!) with a similar name and same attributes. Each class should have another template name and render other posts. Something like this: my_variable = 'part_of_class_name' for class_number in range(2, 5): class_name = my_variable + str(class_number) + '(SameParentClass)' class class_name: template_name = 'template' + str(class_number) + '.html' Of course, the code above doesn't work, is it a possibility to pass a variable to a class name? I want the following: part_of_class_name2(SameParentClass), part_of_class_name3(SameParentClass), part_of_class_name4(SameParentClass). How can I do it by looping? I want to avoid making three classes. -
Show model parent fields in Django's admin model details
I let most of my models inherit from: class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True get_latest_by = 'updated_at' Like this: class Sale(TimeStampedModel): ip_address = models.GenericIPAddressField(null=True) # ... However, if I visit /admin/myapp/sale/123/change/ I only see the ip_address field. How can I also get to see the created_at and updated_at fields? Possibly, without having to specify every single field of Sale in a list. -
need to understand the ur to path converter in Django
i am learn to Django . i have stuking the below URL . i use path but i went to convert it to my path URL pattern . This is my actual Path patrn path('', views.home,name='home'), path('topics/<int:id>/', views.board_topic, name='topics'), path('topics/<int:id>/new/', views.new_topic,name='new_topic'), path('signup/', accounts_views.signup, name='signup'), i went to convert below this comented url to the below path path('topics/<int:id>/topic_id', views.topic_posts, name='topic_posts'), # url(r'^boards/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/$', views.topic_posts, name='topic_posts'), This is Good Formate ? if not then which is best url to path formate ? Thank You -
How do I display search results on my URL on django. ex www.123.com/Search=THIS+IS+SEARCH+RESULTS
So i'm building a website scraper and so far I can scrape search results fine, the problem is my URL is always the same which is 127.0.0.1:8000/search_results I'd love to be able to make it look like 127.0.0.1:8000/search_results=Hello if I search for "Hello" in my search box. Thank you all -
How to solve "from _sqlite3 import * ImportError: DLL load failed: The specified module could not be found." error
I'm beginner in Django . I use pycharm but when I want to run server with "python manage.py runserver" in pycharm terminal It says "from _sqlite3 import * ImportError: DLL load failed: The specified module could not be found. ". -
how to 'ignore the data and leave the instance as it is' in a ModelSerializer update
I have a field in my models that is an ImageField and every time I try to update a data using the browsable API. The API returns an error for my ImageField which is The submitted data was not a file. Check the encoding type on the form. when it's empty but in the instance it is not. How can I ignore the data and leave the instance as it is when updating? But when I upload an image in the imagefield, no error returns. Model class Report(models.Model): # other fields image = models.ImageField(upload_to="reports/image-report/", max_length=1000, null=True, blank=True) Serializer class ReportSerializer(serializers.ModelSerializer): # other fields image = serializers.ImageField(max_length=None, allow_empty_file=True, use_url=True) class Meta: model = Report fields = "__all__" def update(self, instance, validated_data): # other fields instance.image = validated_data.get('image', instance.image) instance.save() return instance Viewset class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer permission_classes = [IsAuthenticated] parser_classes = (MultiPartParser, FormParser) # for uploading attachments pagination_class = LimitOffsetPagination -
How to pass current logged user in a form class in django
I am trying to create a form where one field is a ModelChoicefield. Im trying to populate that field with objects from a different model. I have ran into a problem as i need to get the current logged user within the form to filter the queryset. Here are the 2 models class UserExercises(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) Muscle = models.ForeignKey(Muscle, on_delete=models.CASCADE) class Exercise(models.Model): exercise = models.ForeignKey(UserExercises, on_delete=models.CASCADE) weight = models.DecimalField(max_digits=6, decimal_places=3) reps = models.PositiveIntegerField(validators=[MaxValueValidator(100)]) difficulty = models.CharField(max_length=30) date = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) And here is my form class AddExerciseForm(forms.Form): exercise = forms.ModelChoiceField(queryset=UserExercises.objects.filter(user=1)) class Meta: model = Exercise fields = ['exercise', 'weight', 'reps', 'difficulty'] As you can see i am currently hard coding a filter in the ModelChoiceField, but want to replace that with the current users Id. Is there anyway of Going about this. Im new to django so any help would be Appreciated. -
ModuleNotFoundError: No module named 'django.contrib.admin' in p
hi i know this is repetitive question but i checked everywhere and i checkd my urls and import stuffs but it does not fix i don't know which file path is incorrect i clone my project from github and my project in localhost works all right but in pythonanywhere.com i have this error here is my wsgi.py code: import os import sys path = '/home/gazegan/blood-donor/bblood/' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'bblood.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() and this is the full error: Error running WSGI app ModuleNotFoundError: No module named 'bblood' File "/var/www/gazegan_pythonanywhere_com_wsgi.py", line 57, in <module> application = get_wsgi_application() File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in django.setup(set_prefix=False) File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) please help me :( -
Form unable to center and max width
I have a form that I would like to center in a div, but also apply a max-width Here is what I have: HTML: <div class="site-section mb-5"> <div class="container"> <div class="form-register"> <form method="POST"> {% csrf_token %} <legend>Join Today</legend> {{ form|crispy }} <button class="btn btn-outline-info" type="submit">Sign Up</button> </form> </div> <p class="p-center">Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a> </p> </div> </div> CSS: .form-register { display: inline; margin: 0 auto; } form { width: 80%; max-width: 300px; display: inline; margin: 0 auto; } However if I switch the width and max-width between the two CSS classes, I get either of the following results: or -
Visual Studio Code Django project Error 404 Not Found
My project is named Travello, following this here: https://www.youtube.com/watch?v=Tt3mgy2ECug&list=PLsyeobzWxl7r2ukVgTqIQcl-1T0C2mzau&index=12) , When I runserver I get this error. Anybody have any clue how to fix this error: [16/Apr/2020 20:27:21] "GET / HTTP/1.1" 200 22122 [16/Apr/2020 20:27:21] "GET /static/styles/bootstrap4/bootstrap.min.css HTTP/1.1" 404 1731 [16/Apr/2020 20:27:21] "GET /static/images/destination_2.jpg HTTP/1.1" 404 1698 [16/Apr/2020 20:27:21] "GET /static/images/destination_5.jpg HTTP/1.1" 404 1698 Not Found: /images/intro.png Not Found: /images/travello.jpg [16/Apr/2020 20:27:21] "GET /images/intro.png HTTP/1.1" 404 2149 [16/Apr/2020 20:27:21] "GET /images/travello.jpg HTTP/1.1" 404 2158 [16/Apr/2020 20:27:21] "GET /static/styles/bootstrap4/bootstrap.min.js.map HTTP/1.1" 404 1740 [16/Apr/2020 20:27:21] "GET /static/styles/bootstrap4/popper.js.map HTTP/1.1" 404 1719 Not Found: /images/testimonials.jpg [16/Apr/2020 20:27:21] "GET /static/images/footer_1.jpg HTTP/1.1" 404 1683 [16/Apr/2020 20:27:21] "GET /images/testimonials.jpg HTTP/1.1" 404 2170 Not Found: /images/home_slider.jpg [16/Apr/2020 20:27:21] "GET /images/home_slider.jpg HTTP/1.1" 404 2167 My settings.py file looks like this: Django settings for telusko project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = … -
Django Error when calling to other project url to get data
I have gone into a bit of trouble. I have to call the url of Project 1 from Project 2 views to get the JSON data but when I am trying to call the url using requests it gives me "Max retries exceeded with url" error. Both the projects are using Django 3 Project 1 is running on port 8001 and the other is on port 8000 Please help me out i thought it was a simple task as everything is working fine when doing the same in terminal or python file. # Project 1 views.py def send_master_data(request): return JsonResponse(provide_master_data()) urls.py path('masterdata/', views.send_master_data, name='send_master_data'), # Project 2 views.py @decorators.login_required def export_master_excel(request): with requests.Session() as session: res = session.get("http://127.0.0.1:8001/masterdata/") data = res.json() response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = f'attachment; filename="{data["metadata"]["filename"]}"' wb = Workbook() -
how to pass form object to html and use each item in the object in django
I have a class called user form (UserMyProfilePersonalForm) class UserMyProfilePersonalForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput, max_length=50) first_name = forms.CharField(widget=forms.TextInput, max_length=100) last_name = forms.CharField(widget=forms.TextInput, max_length=100) email = forms.CharField(widget=forms.EmailInput, disabled=True) dob = forms.CharField(widget=forms.DateInput, required=True) profile_pic = forms.CharField(widget=forms.TextInput) def __str__(self): return f"{self.username},{self.first_name}, {self.last_name},{self.email},{self.dob}, self.profile_pic}" class Meta(): model = UserMyProfilePersonal fields = ("email", ) then in my view file, I created an object of this class newUserMyProfilePersonalForm = UserMyProfilePersonalForm.from_json(user_detail) print(newUserMyProfilePersonalForm.email) context_data = {"newUserMyProfilePersonalForm": newUserMyProfilePersonalForm} return render(request, "home.html", context_data) Now I don't know how to fetch the data in the HTML. I tried multiple things 1. below code prints all the value as dummyusername,fname, lname,email@gmail.com,10/05/1990... this output looks the same as str function {{newUserMyProfilePersonalForm}} I tried {{newUserMyProfilePersonalForm.as_p}} but this prints all the items as a form with textbox and label but without any value in the textbox. I want to have a textbox with values as user data e.g. email, username because I want to create "EDIT PRofile" section. -
Django form prefix returns an empty form on GET method
I'm trying to show multiple forms prefilled with data from model instances. Then I would like to use Django "prefix" kwarg for Forms. However as soon as I use that "prefix" argument in a form and send data to display with it it returns empty with no form error showing. I wrote a very simple example hereunder with 2 forms : the first has no prefix and works properly, the 2nd has a prefix and does not. I would love some help ! Many thanks ! models.py class Production_Plan_Data(models.Model): production_plan = models.ForeignKey( Production_Plan, on_delete=models.CASCADE, related_name="production_plan_data", verbose_name="production plan data" ) week_number = models.PositiveSmallIntegerField(verbose_name="Week Number") product = models.ForeignKey( Product, on_delete=models.PROTECT, related_name="production_plan_product", verbose_name="production plan product" ) value = models.PositiveIntegerField(verbose_name="Week Value") creation_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Production Plan Data" ordering = ["production_plan", "product", "week_number"] def __str__(self): return self.production_plan forms.py class Production_Plan_Data_Form(forms.ModelForm): class Meta: model = Production_Plan_Data fields = ["product", "week_number", "value"] view.py class Tests_View(TemplateView): template_name = "load_mgmt/tests.html" def get(self, request, **kwargs): current_item = Production_Plan_Data.objects.get(pk=105) current_item_data = { 'product': current_item.product, 'week_number': current_item.week_number, 'value': current_item.value } form_prefix = "form" + str(current_item.pk) form1 = Production_Plan_Data_Form(instance=current_item) # form1 = Production_Plan_Data_Form(current_item_data, prefix="tt") current_item2 = Production_Plan_Data.objects.get(pk=106) current_item_data2 = { 'product': current_item2.product, 'week_number': current_item2.week_number, 'value': current_item2.value … -
Populate a DataBase from an API in Django
I am building a Django project with a postgresql in it. This databasa has to be populated from an API. This database doesn't have to be updated. As I understood, the tables inside my database have to be created in my Django models. But where should I populate it? In a script outside Django or inside my app views?