Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a query joining two independent tables, with one Foreign Key in common
I have two Models, one for Intakes of Goods in the warehouse, the other for Output of goods. My available inventory per item is the sum of the intakes minus the sum of the outputs for each item. How can I do that in a query in Django? I have tried using the Django ORM but apparently its only for joining models with dependencies among each other. THIS IS THE MODEL FOR THE OUTPUT OF GOODS. ITS LOCATED IN THE APP, LETS SAY "1" OF MY PROJECT. class OutputPosition(models.Model): created_at = models.DateTimeField(auto_now=True, null=False) output = models.ForeignKey(Output, related_name='outputs', on_delete=models.CASCADE) item = models.ForeignKey(Item, related_name='output_items', help_text='Nombre del artículo', on_delete=models.SET_DEFAULT, default=999999999) quantity = models.SmallIntegerField(null=False, help_text='Ingrese el número de artículos') comments = models.CharField(max_length=256, null=True, help_text='Comentarios') def get_item_name(self): return self.item.name def __str__(self): return str(self.pk)+' '+self.item.name THIS ONE BELOW IS THE MODEL FOR THE INTAKE OF GOODS. IS LOCATED IN ANOTHER APP. class Positions(models.Model): created_at = models.DateTimeField(auto_now=True, null=False) intake = models.ForeignKey(Intake, related_name='intakes', on_delete=models.CASCADE) item = models.ForeignKey(Item, related_name='intake_items', help_text='Nombre del artículo', on_delete=models.SET_DEFAULT, default=999999999) quantity = models.SmallIntegerField(null=False, help_text='Ingrese el número de artículos') comments = models.CharField(max_length=256, null=True, help_text='Comentarios') def get_item_name(self): return self.item.name def __str__(self): return str(self.pk)+' '+self.item.name class Meta: verbose_name_plural = "Positions" I have one view which I want to … -
In Django Web Project, my app is not recognized
I'm new in Python & Django.. Creating a new app using Python 3.6 Django 2.2.7 and for some reason, the url.py which hold the urlpatterns of the project, is not recognizing the urls.py of my new app (ManageMissingBusinesses). Please see below the relevant urls.py (on the project level). urls.py (project level) from django.urls import path, include from app import forms from datetime import datetime import app.forms import app.views urlpatterns = [ path ('ManageMissingBusinesses/',include('ManageMissingBusinesses.urls')) ] The urls.py on the project level is located on level above the ManageMissingBusinesses module/directory. While starting the server, I'm receiving an error on the urlpattern line: path ('ManageMissingBusinesses/',include('ManageMissingBusinesses.urls')) "ModuleNotFoundError:No module named 'ManageMissingBusinesses' Can you explain me what is the issue? -
module 'django.db.models' has no attribute 'OnetoOneField'
I was following a Django tutorial which used models.OnetoOneFiled() in its models.py file. when I tried implementing the same I get his error: AttributeError: module 'django.db.models' has no attribute 'OnetoOneField' I have added this line as some of the previous answers suggested but with no luck. from django.contrib.auth.models import User from django.db import models # Create your models here. class UserProfileInfo(models.Model): user = models.OnetoOneField(User,on_delete=models.CASCADE, primary_key=True,) # additional portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username if successful, I should be able to migrate -
VSCode pylint is unable to import anything
This was never an issue until today, I've no idea what I have done to do this. So all the import errors are for django implying it is not installed but it is and runs fine, it's just the linting is throwing too many errors to be any use and I don't think just disabling linting is a way forward. Here is an example of one of the errors: { "resource": "/Users/rki23/Documents/Python/pcc_django/project_portal/views.py", "owner": "python", "code": "import-error", "severity": 8, "message": "Unable to import 'django.contrib.auth'", "source": "pylint", "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 1 } All other imports are fine, for example datetime imports fine. As I mentioned my site still runs fine, it's just pylint is not working. All should be running from anaconda virtual environment, but I'm not sure how to show that bit. Here also is my workspace settings.json { "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.linting.pycodestyleEnabled": false, "python.pythonPath": "/Users/rki23/anaconda3/envs/django_env/bin/python", "sqltools.connections": [ { "database": "******", "dialect": "PostgreSQL", "name": "Development", "password": "**********", "port": 5432, "server": "localhost", "username": "********" } ] } and here is the launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", … -
hi am trying to deploy django poll web app on heroku but i cant get passed this errors i dont know what to do
2019-11-05T11:32:44+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/f43bc705-ff02-49d0-98ca-06da4760a3f8/activity/builds/3b99bc09-b4d0-401d-a62a-9a23fe8b6ec8 please this is the errors -
nginx reverse proxy multiple locations
I am trying the below configuration and nginx is not routing my web request to the right url. I tried multiple suggestions in online, but still getting error. rewrite proxy ~^ End slashes server { listen 80 default_server; listen [::]:80 default_server; server_name $ipaddress; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location /flask { proxy_pass http://0.0.0.0:8000/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { proxy_pass http://0.0.0.0:8001/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } -
Validate ModelForm without checking duplicate
I'm trying to write a view in django which checks if a client exists then it does nothing. If it doesn't exist then I create. This is what the ModelForm looks like: class FacebookLoginForm(ModelForm): class Meta: model = Client fields = ['facebook_id', 'first_name', 'last_name', 'email'] And here is my code: def facebook_login(request): data = json.loads(request.body) form = FacebookLoginForm(data) if form.is_valid(): # do something pass However for some reason when I call is_valid on the form it checks that the passed data doesn't exist in the database (where the model fields are unique). How can I set the ModelForm to just validate the data without checking if it already exists? My ultimate goal is to validate the input of the form and then update/create the database. -
Make default Django orm calls be more sufficient
I have Django 1.6 and simple view class: class CategoryDetailsView(DetailView): model = Category template_name = '/details.html' queryset = Category.objects.available_categories() def dispatch(self, *args, **kwargs): return super(CategoryDetailsView, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(CategoryDetailsView, self).get_context_data(**kwargs) context.update({ 'items': ItemCategory.ITEM_CHOICES, 'items_categories': ItemCategory.objects.items_categories(), 'items_actions_count': ItemAction.objects.something_more(), }) return context I would like to enhance performance of the service and I see that get_context_data method call results in plenty of SELECT statements to the same table. Please, suggest me correct entry point for stating tuning django orm in order to minimize queries quantity. -
Django query timestamp seems to behave differently
I would like to query som data from a postgres database where we store some values. However it seems that when I do this in Django with a python script that is called from views.py the data is shifted one hour. Example: Query from script file: sensorData = SensorDataAvgFirstTwoMonths.objects.filter(timestamp__gte='2019-11-06 07:50:00', timestamp__lte='2019-11-06 08:00:00', machine_id=4, type_id=25).order_by('timestamp'); print(sensorData) for d in sensorData: print(d.timestamp) print(d.value) This result in the following print: 1 Now, if I query data directly from the terminal then I have to shift one hour to get the same result (except for the fact that the quires are slightly different). 2 The time in the database is in UTC time. I would expect that I do not need to shift time one hour in the Django qury to get the same result. But I guess that the query in Django take some timezone into account but how can I get the same result when setting the date and time exactly the same in both cases? -
Django TestCase: can't see record updated in test db
I'm testing a function in my project. The function modifies some records in my test db. I'm interested to see if a specific record was updated. I call my method inside my test_function and after that looking for the record. It seems the record wasn't updated, but the function (with some logs) tells me it was! I created my TestCase class using both TestCase and TransactionTestCase, but none of them worked. I'm usign Django 2.2 class HostTestCase(TransactionTestCase): def setUp(self): task = Task.objects.create(name='do_backup', description="") for i in range(1, 17): if i in [4, 7, 9, 11, 12, 14, 15]: host = Host.objects.create( name="test_sbb{}".format(i), mac_address="asgsb{}".format(i), remote_address="mock-server{}:4010".format(i) ) if i in [11, 14, 15]: host.last_seen_at = timezone.now() host.save() if i in [9, 12, 15]: task_assigned = Host_Task.objects.create(host=host, task=task, status="IDLE") elif i in [4, 7, 11, 14]: task_assigned = Host_Task.objects.create(host=host, task=task, status="WORKING_CREATION") else: if i != 16: host = Host.objects.create( name="test_sbb{}".format(i), mac_address="asgsb{}".format(i), remote_address="mock-server{}:4010".format(i), get_backup=False ) if i in [8, 10, 13]: host.last_seen_at = timezone.now() host.save() if i in [3, 6, 10, 13]: task_assigned = Host_Task.objects.create(host=host, task=task, status="WORKING_CREATION") else: host = Host.objects.create( name="test_sbb{}".format(i), mac_address="asgsb{}".format(i), remote_address="mock-server:4010" ) host.last_seen_at = timezone.now() host.save() influx = InfluxDB(host) # create new db influx.create_database() write_mock_data(influx, i) def tearDown(self): for i in … -
ModuleNotFoundError: No module named 'Pillow'
i installed pillow from cmd : pip install pillow and after that i went to import it : from PIL import Image but i found an error : ModuleNotFoundError: No module named 'Pillow' please help !! -
Append FormActions Div by default to custom FormHelper
To keep my ModelForms DRY I have created a custom ModelForm with a FormHelper so I can append a Div with a Submit and a Cancel button to the layout. It also offers the possibility to add a custom layout. This works perfectly fine when I don't specify a custom layout, but when I do, every time I refresh the page it appends the buttons Div (this doesn't happen when there's no custom layout) This is the custom ModelForm: class ModelFormWithHelper(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) kwargs = self.get_helper_kwargs() helper_class = FormHelper(self) if 'custom_layout' in kwargs: self.helper.layout = kwargs['custom_layout'] self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-12' self.helper.field_class = 'col-md-12' self.helper.layout.append( Div( HTML('<br>'), FormActions( Submit('submit', 'Save'), HTML('<a class="btn btn-secondary" href="{{ request.META.HTTP_REFERRER }}">Cancel</a>') ), css_class='row justify-content-center', ), ) def get_helper_kwargs(self): kwargs = {} for attr, value in self.Meta.__dict__.items(): if attr.startswith('helper_'): new_attr = attr.split('_', 1)[1] kwargs[new_attr] = value return kwargs And this is the ModelForm: class CargoForm(ModelFormWithHelper): class Meta: model = Cargo exclude = [] helper_custom_layout = Layout( Div( 'name', 'order', css_class='col-6 offset-3', ), ) This is the form with no custom_layout after I refresh the page 3 times: And this is the form with a custom_layout after I refresh the page 3 … -
How to loop in template over serializer used as form
I need a CRUD-table and don't want to write out the field names (too many). I want use the serializer to make the forms in the first row and the already entered data in the rows below. Displaying the data works fine, even with choices and FK. The problem is that i cannot loop over the form-fields. In "template1.html" I checked "render_form" and the serializer. Ok, so far. PROBLEM: In "template2.hmtl" I try to loop and position each form (rendered REST serializer) in a column and get errors. How to loop correctly? ...rest of table is omitted... <tr> <form method="POST"> {% csrf_token %} <th> {% render_form serializer template_pack='rest_framework/inline'%} <input type="submit" value="Save"> </th> </form> </tr> ...rest of table is omitted... <tr> <form method="POST"> {% csrf_token %} {% for s in serializer %} <th> {% render_form s template_pack='rest_framework/inline'%} </th> {% endfor %} <th> <input type="submit" value="Save"> </th> </form> </tr> -
How to get the second to last most recent timestamped record in Django/Python?
I have a form from a model that keeps track of enter/leave times. I am trying to add constraints to make the data more accurate. Currently, when someone "Enters", it creates a record, saves the time in the "time_in" DateTimeField and then redirects. If the person then tries to enter again, it creates a new record with a new timestamp. What I'm trying to add now is that, if the person has a previous entry without an exit timestamp (time_out) then that record (which would be the second to last most recent entry), would be flagged by updating the time_exceptions field to 'N'. Currently, it changes all the fields to 'N', regardless of whether there's an exit or not, as shown below. NOTE I reduced the amount of code in form_valid, hence the leave area part is not there. It was just a lot of filtering based on other fields and it didn't seem too relevant. views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num)).count() > 1: … -
How to create a formset from form-instance in Python Django
I am trying to get a Django - Formset out of an instance of a form class. In my form class i add some fields in the init method because the form has to offer some flexibility. Therefore i can't pass the class as parameter to the formset_factory function. --forms.py class ConfigForm(forms.Form): def __init__(self, fields, fields_choices, *args, **kwargs): super(ConfigForm, self).__init__(*args, **kwargs) for field in fields: # instanciate Field from field data exec( f'self.fields["{field.name}"] =' f'forms.{field.field_type.field_type}(' f'required = {field.required},' f'disabled = {field.disabled},' f'label = "{field.label}",' f'initial = "{field.value}",' f'widget = {field.widget},' f'help_text = "{field.description}"' f')' ) # if field is a ChoiceField add choices to the field instance if 'ChoiceField' in field.field_type.field_type: self.fields[field.name].choices = [fields_choices[field.name]] --views.py ... form = forms.ConfigForm(active_fields, field_choices) formset = formset_factory(form, extra=1) ... But if i try to call formset_factory with an instance of ConfigForm, the following error occurs: Internal Server Error: /machines/testconfig/mw0-sap-001/ Traceback (most recent call last): File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) … -
Column 'post_id' cannot be null
Column 'post_id' cannot be null I don't know why I can't bring post_id. If you try to add a comment, you might not be able to bring post_id. I can't solve it. Please help me. models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) serializers.py class CommentSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) post = PostSerializer(read_only=True) class Meta: model = Comment fields = ( 'user', 'post', 'id', 'content', ) read_only_fields = ('created_at',) views.py # api/views.py class CommentView(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): serializer.save(user=self.request.user) -
Altering the username of the User model to use PhoneNumberField instead of CharField causes errors
I work on a project started from the cookiecutter-django, and I altered the username of the User model to use PhoneNumberField from django-phonenumber-field package instead of the ordinary models.CharField, and I got this error when I tried to issue manage.py makemigrations: Traceback (most recent call last): File "./manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ahsh/Projects/xpay_stuff/communites_dj_backend/community_backend/users/admin.py", line 10, in <module> from community_backend.users.forms import UserChangeForm, UserCreationForm File "/home/ahsh/Projects/xpay_stuff/communites_dj_backend/community_backend/users/forms.py", line 8, in <module> class UserChangeForm(forms.UserChangeForm): File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/forms/models.py", line 256, in __new__ apply_limit_choices_to=False, File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/forms/models.py", line 172, in fields_for_model formfield = f.formfield(**kwargs) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/phonenumber_field/modelfields.py", line 106, in formfield return … -
List from Django to table in JavaScript
I have a list in Django and I would like transfer it to JavaScript table My template print latest_question_list in loop properly: {% if latest_question_list %} <ul> {% for row in latest_question_list %} <li>{{ row.mounth }}, {{ row.number1 }}, {{ row.number2 }}, {{ row.number3 }}, {{ row.number4 }}</li> {% endfor %} </ul> {% else %} <p>These list is empty.</p> {% endif %} But I would see it in JavaScript (in the same file) in this form: <script> var data_table = [600, 194, 345, 512, 200, 320, 328, 498, 267, 349, 287, 276]; [...] </script> -
How to use new "autocomplete_fields" option in Django <2.0 with overrided form?
I have form, which overrides the standard admin form and i want to use "autocomplete_fields" for brigadier field, which if ForeignKey -
ASGI Framework Lifespan error, continuing without Lifespan support
After creating a project with django, and auditing the code via chrome audit, it shows Does not use HTTP/2 for all of its resources 2 requests not served via HTTP/2 to fix this error I followed this tutorial https://medium.com/python-pandemonium/how-to-serve-http-2-using-python-5e5bbd1e7ff1 and when using the code specified for quart import ssl from quart import make_response, Quart, render_template, url_for app = Quart(__name__) @app.route('/') async def index(): result = await render_template('index.html') response = await make_response(result) response.push_promises.update([ url_for('static', filename='css/bootstrap.min.css'), url_for('static', filename='js/bootstrap.min.js'), url_for('static', filename='js/jquery.min.js'), ]) return response if __name__ == '__main__': ssl_context = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH, ) ssl_context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 ssl_context.set_ciphers('ECDHE+AESGCM') ssl_context.load_cert_chain( certfile='cert.pem', keyfile='key.pem', ) ssl_context.set_alpn_protocols(['h2', 'http/1.1']) app.run(host='localhost', port=5000, ssl=ssl_context) I get /home/avin/Documents/projects/portfolio/portfolio_env/lib/python3.6/site-packages/quart/app.py:1320: UserWarning: Additional arguments, ssl, are not yet supported "Additional arguments, {}, are not yet supported".format(','.join(kwargs.keys())), Running on https://localhost:5000 (CTRL + C to quit) [2019-11-06 18:30:18,586] ASGI Framework Lifespan error, continuing without Lifespan support and also I cant load the webpage via https://localhost:5000 -
Which frame work is easier django or flask
Which python web development framework should I go for (django or flask) considering i am a beginner level python developer and also new to web development -
api call from one server to another django
I'm pretty new with Django framework, I have two webservers that run in the same docker-compose the first on port 8008 and the second on 8000. I'm trying to make API's call from one to another. (they both runs Django). for some reason, after he pass the first call and try to make the second one to the second server. he trying to find the path on the first one. urls.py urlpatterns = [ . . . url(r'^badges/issuers/$', views.create_issuer, name='create issuer'), ] views.py def create_issuer(request): r = requests.get('http://127.0.0.1:8000/v2/users/romOowjnTkuoBXcb8dn_bQ', headers={"Authorization": "Token " + badgr_token}) #r = requests.get('http://api.ipstack.com/132.72.238.3?access_key=c3dcdadd83efb69cd9970cb811b2ad3f&format=1') return HttpResponse(r.content) I'm getting 404 : Using the URLconf defined in Lassi.urls, Django tried these URL patterns, in this order: . . . "The current URL, v2/users/romOowjnTkuoBXcb8dn_bQ, didn't match any of these." the logs from docker terminal : ins_1 | [06/Nov/2019 12:26:27] "GET /v2/users/romOowjnTkuoBXcb8dn_bQ HTTP/1.1" 404 5443 ins_1 | [06/Nov/2019 12:26:27] "GET /badges/issuers/ HTTP/1.1" 200 5443 and nothing from the second's log. I don't know why but he tries to get the path from the first server instead of doing regular get requests to second. I tried to make the call to the second with Postman and it's worked. Tnx!! -
Geeting value after submit and redirecting to certain page
Hi I am new in Django but know some stuff and still need your help. I want when a user submit a button after putting info in search area to redirect to another page and accept data for future use. What i did so far: in models.py from django.db import models from django.contrib import auth class Child(models.Model): name = models.CharField(max_length=150, blank=True) in forms.py from django import forms from .models import Child class ChildlForm(forms.ModelForm): class Meta: model = Child fields = ('name',) in views.py def garden(request): return render(request,'garden.html') def names(request): form = ChildForm() if request.method == "POST": form = ChildForm(request.POST) if form.is_valid(): form.save(commit=True) return garden(request) else: return 'test.html' return render(request,'garden.html',{'form':form}) 'test.html' is where the form is required to be filled by user. I want after the inform submitted the data is saved and then redirected to garden.html file. the test.html file <form action="." class="ticker_area"method="POST"> {{ form }} {% csrf_token %} <input class="form-control mr-sm-2" type="text"> <button class="ticker_button" type="submit">OK</button> </form> the form is search ready template posted by bootstrap. Could you please help to link successfully the files and get the data (name) to further use in garden.html ? So far when i put name i search area and submit the page goes … -
How to return data from django to nodeJs server?
I'm trying to send data from nodeJs server to django server for some processing, then return some json data. But when I make a request using this line of code, http.get("http://127.0.0.1:8000/test/", (message) => { console.log(message) }) then printing the message, a lot of data printed! How I can retrieve my data? this is the django code! from django.http import HttpResponse from django.core import serializers import json def prints(request): some_data_to_dump = { 'some_var_1': 'foo', 'some_var_2': 'bar', } data = json.dumps(some_data_to_dump) print("foidjfdi") return HttpResponse(data, content_type="application/json") -
How to use request_id while logging in asynchronous functions?
In asynchronous functions, every logger statement is getting their own request_id. import logging log = logging.getLogger('test_logger') def sync_fun(): log.info("test 1") log.info("test 2") log.info("test 3") @after_response.enable def async_fun(): log.info("test 1") log.info("test 2") log.info("test 3") output of sync_fun: [06/Nov/2019 10:42:00.234] [None] [130C6C47F1E24164AAC0440C719630] [INFO] Test 1 [06/Nov/2019 10:42:00.234] [None] [130C6C47F1E24164AAC0440C719630] [INFO] Test 2 [06/Nov/2019 10:42:00.234] [None] [130C6C47F1E24164AAC0440C719630] [INFO] Test 3 130C6C47F1E24164AAC0440C719630 is a request_id and its common for all logger statements. output of async_fun: [06/Nov/2019 10:42:00.234] [None] [AB352B8F2DF9459ABDD2FBF51EB05F] [INFO] Test 1 [06/Nov/2019 10:42:00.234] [None] [V9E9B6DF5F9C442195EA7C1379FBFA] [INFO] Test 2 [06/Nov/2019 10:42:00.234] [None] [DCA311A92724443C9AD7E951288917] [INFO] Test 3 async_fun is an asynchronous function and request ids are different for all logger statements. How do i get the same request_id for each logger statements in asynchronous function.