Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I call a Django app from another Python app?
In the standard setup, Django applications are called by a WSGI server (like gunicorn and mod_wsgi) to answer HTTP requests, the entrypoint at user-level is the django View. Can I make a custom calling convention to call Django apps (a new entrypoint)? If so, How I properly load a Django app? -
Django, NoReverseMatch. What should I write in this code?
I have a problem: NoReverseMatch at /update-orders/12 Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update\-orders/(?P[0-9]+)$'] Request Method: GET Request URL: http://192.168.0.249:8000/update-orders/12 Django Version: 3.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update\-orders/(?P[0-9]+)$'] Exception Location: /root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 Python Executable: /root/.local/share/virtualenvs/myp4-4l8n6HJk/bin/python Python Version: 3.7.3 Python Path: ['/var/workspace/myp4/webprint', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages'] Why do I have this Error during template rendering? detail_order.html {% extends 'index.html' %} {% block content %} <p><a href="{% url 'orders' %}">Back</a></p> <h1>Заказ {{get_order.number_order}}</h1> <h2><a href="{% url 'update_order' get_order.id %}">Update</a></h2> views.py class UpdateOrderView(CustomSuccessMessageMixin, UpdateView): model = Order template_name = 'detail_order.html' form_class = OrderForm success_url = reverse_lazy('detail_order') success_msg = 'Ok' def get_context_data(self, **kwargs): kwargs['update'] = True return super().get_context_data(**kwargs) urls.py from django.contrib import admin from django.urls import path, include from .views import * from print import views urlpatterns = [ path('', views.home_page, name='index'), path('orders', views.OrderCreateView.as_view(), name='orders'), path('update-orders/<int:pk>', views.UpdateOrderView.as_view(), name='update_order'), # THIS PATH path('delete-orders/<int:pk>', views.DeleteOrderView.as_view(), name='delete_order'), path('detail-order/<int:pk>', views.DetailOrderView.as_view(), name='detail_order'), path('login', views.MyprojectLoginView.as_view(), name='login_page'), path('register', views.RegisterUserView.as_view(), name='register_page'), path('logout', views.MyprojectLogout.as_view(), name='logout_page'), ] -
Django REST framework TokenAuthentication - Unauthorized 401
I'm using axios to get data from Django server. getQuestionsPage(page) { return axios.get(`${API_URL}/questions/?page=${page}`, c.getHeaders).then(response => response.data); } getQuestionsURL(url) { return axios.get(url, c.getHeaders()).then(response => response.data); } Both URLs are the same, but when I getQuestionsPage(page) is called, the request is unauthorized. [23/Apr/2020 17:59:41] "GET /questions/?page=2 HTTP/1.1" 401 58 [23/Apr/2020 17:59:41] "GET /questions/?page=2 HTTP/1.1" 200 3489 How can I solve this problem? -
ChartJS : It's not showing in html on Django
I will plot horizontal bar chart in html but it's not showing. I send 2 variable from views.py are {{top5StockCode}} and {{top5TotalSales}}. The values of {{top5StockCode}} that views.py sent is ['23166', '21108', '85123A', '48185', '22470'] and {{top5TotalSales}} is [2671740, 227322, 171770, 158120, 143808]. This is my code in html file. <div class="top5"> <p class="topicTop5">Top 5 Selling Products</p> <canvas id="top5"></canvas> </div> <script> var top5 = document.getElementById('top5').getContext('2d'); var chart = new Chart(top5, { type: 'horizontalBar', data: { labels: {{top5StockCode}}, datasets: [{ label: 'Top 5 selling products ', backgroundColor: '#CE3B21', borderColor: 'rgb(255, 99, 132)', data: {{top5TotalSales}} }] }, options: { legend: { display: false }, responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); </script> I'm so confused why it's not showing graph. Please help me. Thank -
I'm getting django.db.utils.IntegrityError: FOREIGN KEY constraint failed in cmd
I copied a json file from online. I'm using it for django project in sublime text 3. I entered the following lines in cmd - >>> import json >>> from blog.models import Post >>> with open('posts.json') as f: ... posts_json=json.load(f) ... >>> for post in posts_json: ... post = Post(title=post['title'], content=post['content'], author_id=post[' user_id']) ... post.save() ... And the error I got was - Traceback (most recent call last): File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 3, in <module> File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 782, in save_base updated = self._save_table( File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields , raw) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 924, in _do_insert return manager._insert( File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\sql\compiler.py", line 1391, in execute_sql cursor.execute(sql, params) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang … -
CORS_ORIGIN_WHITELIST inside a environment file in django
I need to configure the whitelist for the CORS policy inside my django app. Instead of hardcode the urls inside settings.py, I'd like to put them inside a separate file, like the .env file from django-environ. This is my code: .env DEBUG=on SECRET_KEY='xxx' DATABASE_URL=psql://xxx CORS_ORIGIN_WHITELIST=http://127.0.0.1:4200 settings.py (MIDDLEWARE and INSTALLED_APPS are fine) ... environ.Env.read_env() ... CORS_ORIGIN_WHITELIST = env('CORS_ORIGIN_WHITELIST') I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/david/errepiu-project/backend/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/david/errepiu-project/backend/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/david/errepiu-project/backend/venv/lib/python3.7/site-packages/django/core/management/base.py", line 441, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E013) Origin '.' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '.' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '.' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '/' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. … -
Importing CSV file to MySQL table made in Django Models.py
I'm attempting to import a CSV file into a table in MySQL, the table being made in a Django models.py file and then migrated over. I am able to import CSV files into tables made in MySQL but when I attempt to import into the models.py made tables I get "0 records imported". Could someone help enlighten me to my mistakes? Relevant code and process screenshots below Models.py from django.db import models # Create your models here. class StudentDetails(models.Model): firstname = models.CharField(max_length=500) lastname = models.CharField(max_length=500) major = models.CharField(max_length=500) year = models.CharField(max_length=50) GPA = models.DecimalField(max_digits=3, decimal_places=3) class CourseDetails(models.Model): courseID = models.IntegerField() coursetitle = models.CharField(max_length=500, default="class") coursename = models.CharField(max_length=500) coursesectioncode = models.IntegerField(default="101") coursedept = models.CharField(max_length=500, default="college") courseinstructor = models.CharField(max_length=500, default="professor") Import process -
Django test does not add coverage with AssertRaises
There two lines that are not being executed by django tests when they are called as self.assertRaises. I am using: Python 3.6.9, Django 3, Coverage. I have this class: class AverageWeatherService: subclasses = WeatherService.__subclasses__() valid_services = { subclass.service_key: subclass for subclass in subclasses } @classmethod def _check_service(cls, one_service): if one_service not in cls.valid_services: logger.exception("Not valid service sent") raise NotValidWeatherFormException("Not valid service sent") And I have a local API that is up in my pc. Then I wrote this test: def test_integration_average_temp_services_error(self): self.assertRaises ( NotValidWeatherFormException, AverageWeatherService()._check_service, "MyFakeService", ) And although the test is successful with assert raises properly used this test is not adding coverage but If I call this method in a wrong way like this one: def test_integration_average_temp_services_error2(self): self.assertRaises ( NotValidWeatherFormException, AverageWeatherService()._check_service("MyFakeService") ) Then of course I get an error running the test because the exception is raised and not properly catched by assertRaises BUT It adds coverage. If I run this test wrongly I have my code 100% covered. If I use assertRaises as the first way these two lines are not being covered (According to coverage html). logger.exception("Not valid service sent") raise NotValidWeatherFormException("Not valid service sent") Also If I execute the method as the first way, the … -
after login through django social all_auth after redirect to webpage again webpage is refereshing when clicking on to it
i have used social django all_auth for login through gmail and it redirects to the page where i want but i am facing a problem after login through gmail it again refereshing the webpage and i want to perform two operations through textarea first it redirect me to gmail login after login when it returns back to the same page it takes input to it but whenever i click it refereshes the webpage and input not shows just bacause of that refereshing. here is myhtml code" <form id="new_user_form"> <a href="{% provider_login_url 'google'%}"> <textarea style=" width: 500px; border: 2px solid #333; padding: 15px 10px;"placeholder="Add Your Comment"></textarea></a> -
how to make edit functionality edit by using django form
I work on this project and i reached at a point where i am suppose to make edit functionality,I have two models child and *parent * models and these two models have relationship to each other and also in a template where i want to edit parent details i pass a child id, here is my child model from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) def __str__(self): return self.Firstname here is my parent model class Parent(models.Model): child = models.ForeignKey(Child_detail,on_delete=models.CASCADE) Parent_firstname = models.CharField(max_length = 100) Parent_lastname = models.CharField(max_length = 100) Current_address = models.CharField(max_length = 100) def __str__(self): return str(self.Parent_firstname) here is views.py file for editing parent details def edit_parent(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=ParentForm(request.POST) if form.is_valid(): form.instance.child=child form.save() return redirect('more_details',pk=pk) else: form=ParentForm() context={ 'form':form, 'child':child } return render(request,'functionality/parents/edit.html',context) here is form.py file class ParentForm(forms.ModelForm): class Meta: model=Parent fields=['Parent_firstname','Parent_lastname','Current_address','Phone_number','Parent_job', 'Life_status','Other_parent_name','Other_parrent_phone_number'] labels={ 'Parent_firstname':'Parent Firstname','Parent_lastname':'Parent Lastname', 'Other_parent_name':'Other Parent Name', 'Current_address':'Current Address','Phone_number':'Phone Number', 'Other_parrent_phone_number':'Other Parent Phone Number', } -
Django Variable Number of ChoiceFields
I am making a form in Django where the user reads a paragraph, then is asked a variable number of questions about the paragraph (the content of the paragraphs and the number of questions per paragraph is is stored in Django models). For each question, I need to display a ChoiceField (the same one for each question). What is the best way to display the ChoiceFields and then read the data (i.e namespacing each separate question). I have already looked into FormSet which I do not think will work for my purposes. Any help is appreciated! -
Problem getting "first_name" and "last_name" from User model
I'm creating the Client model like this: from django.db import models from django.contrib.auth.models import User from platforms.models import Platform class Client(models.Model): """Model definition for Client.""" user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.CharField(("Compañía"), max_length=50) platforms = models.ManyToManyField(Platform, verbose_name=("Plataformas")) class Meta: """Meta definition for Client.""" verbose_name = 'Cliente' verbose_name_plural = 'Clientes' def __str__(self): """Representación de cliente.""" company = "Sin empresa" if self.company: company = self.company string = "{} {} ({})".format(self.user.first_name, self.user.last_name, company) return string But in this part, when I try to get the first_name and user_name I get an error: string = "{} {} ({})".format(self.user.first_name, self.user.last_name, company) This is the error: Instance of 'OneToOneField' has no 'first_name' member Why does this happen? "User" model should have first_name and last_name right? Thank you? -
Django filter my admin list for another field
In my django project i have this model: class as_clienti(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True ) id_ag = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ag_user",null=True, blank=True ) Codice = models.IntegerField() Nome = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.Nome well i would in my django admin when i open the as_clienti link to see the list containing data filtered for logged user but on column id_ag So in my admin.py i do: class as_clientiAdmin(FilterUserAdmin): def get_queryset(self, request): qs = super(as_clientiAdmin, self).get_queryset(request) return qs.filter(id_ag_id=request.user.id) but my django admin page remain blank with 0 rows returned message. Where am i wrong in my code? So many thanks in advance -
Using nested loop in django template
Hi i have a template where i used nested loop like fetching data from two table. html file <div class="content"> <ul class="dashboard-box-list"> {% for form in user.userselecttest_set.all %} <li> <div class="invoice-list-item"> <strong>{{ form.testselected }}</strong> <ul> {% for ut in user.usertest_set.all %} <li>{{ ut.totalprice }}</li> </ul> </div> </li> {% endfor %} {% endfor %} i have two table in models name "UserSelectTest" and "UserTest". So from "UserSelectTest" i retrieve items and "UserTest" thier price i am achieving in displaying the item but in price i get all values for example: Item Price A 120,70 B 120,70 but i want: Item Price A 120 B 70 I am getting confused in nested for loop hope i am making sense i know i am making some silly mistake , Please help. -
Django ASGI Deployment on Heroku
I want clear cut explanation of how should I deploy django 3.x and channels 2.x on heroku. my asgi.py file import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainProj.settings') django.setup() application = get_default_application() -
Overriding admin template works in local not in server
I have project like this structure /-myapp-templates-admin-myapp-myModel-change_list_result.html -change_list.html -base_site.html -base.html -myapp-index.html -base.html When I edit change_list_result.html the edited admin page works on python manager.py runserver. However not on server apache. I guess somehow change_list_result.html is not over-rided on apache server. Does anyone know the reason?? -
Javascript with Crispy Forms
I am using django-crispy-forms but would like to add some super simple JS to change the value of the submit button depending on if a checkbox is checked or not. Here's the generate HTML for the checkbox <div class="form-group"> <div id="div_id_draft" class="custom-control custom-checkbox"> <input type="checkbox" name="draft" class="checkboxinput custom-control-input" id="id_draft"> <label for="id_draft" class="custom-control-label"> Draft </label> </div> </div> <input type="submit" name="submit" value="Post" class="btn btn-primary" id="submit-id-submit"> Here is the JS I am trying to use: function draftbox() { var checkBox = document.getElementById('id_draft') var button = document.getElementById('submit-id-submit') if (checkBox.checked == true){ button.value = 'Save'; } else { button.value = 'Post'; } } Currently, when I click the checkbox, I get no changes in the submit button, but I would like for the "Post" in the submit button to change to "Save" when the checkbox is checked. -
mitmproxy 5.1.1 always crashed
I encountered mitmproxy crash issue with Windows 10 64-bit build 19041.207 Following are my crash logs Mitmproxy: 5.1.1 build pypi_0 from pypi Python: 3.7.6 from conda-forge OpenSSL: 1.1.1g build he774522_0 from conda-forge pyopenssl: 19.1.0 build py_1 from conda-forge cryptography: 2.9.2 build pypi_0 from pypi ================== D:\Dev\Anaconda3\envs\WXC_prj\python.exe D:/Dev/Anaconda3/envs/WXC_prj/src/main.py 2020-04-23 22:40:16.216 | INFO | web_server::32 - Gevent server mode 2020-04-23 22:40:19.039 | INFO | web_server::32 - Gevent server mode `Proxy server listening at http://*:8080 192.168.1.17:58307: clientconnect 192.168.1.17:58309: clientconnect 192.168.1.17:58307: Traceback (most recent call last): File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\server.py", line 121, in handle root_layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\modes\http_proxy.py", line 9, in call layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 285, in call layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http1.py", line 83, in call layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http.py", line 190, in call if not self._process_flow(flow): File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http.py", line 262, in _process_flow return self.handle_regular_connect(f) File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http.py", line 208, in handle_regular_connect layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 278, in call self._establish_tls_with_client_and_server() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 358, in _establish_tls_with_client_and_server self._establish_tls_with_server() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 448, in _establish_tls_with_server **args File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\connections.py", line 292, in establish_tls self.convert_to_tls(cert=client_cert, sni=sni, **kwargs) File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\net\tcp.py", line 386, in convert_to_tls **sslctx_kwargs File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\net\tls.py", line 285, in create_client_context param = SSL._lib.SSL_CTX_get0_param(context._context) AttributeError: module 'lib' has no attribute 'SSL_CTX_get0_param' Traceback (most recent call last): File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\server.py", line 121, in handle root_layer() File … -
Django clean() function for form validation doesn't work
I created this simple form, but the function clean() doesn't work when I intentionally pass invalid data. here is the code: from django import forms SELECT_GENDER = ( ('M', 'Male'), ('F', 'Female'), ) SUBSCRIPTION = ( ('Pro', 'Professional'), ('Premium', 'Premium'), ('trial', '14 Days Trial') ) class FormsProject(forms.Form): fullname = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control mb-3', 'placeholder': 'Basir Payenda'})) django = forms.BooleanField( widget=forms.CheckboxInput(), required=False) flask = forms.BooleanField( widget=forms.CheckboxInput(), required=False) gender = forms.ChoiceField( widget=forms.RadioSelect(), choices=SELECT_GENDER) comments = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control mb-2', 'rows': 4, }), help_text='Write here your message!') subscription_plan = forms.ChoiceField( choices=SUBSCRIPTION, widget=forms.Select(attrs={ 'class': 'form-control mb-3' })) def clean(self): super(FormsProject, self).clean() fullname = self.cleaned_data.get('fullname') if len(fullname) < 5: raise forms.ValidationError("ERRRRRRRRROR") return self.cleaned_data The form is rendered in template without any issue. The only thing is that it don't show validation error. Thanks -
UnboundLocalError: local variable 'listing' referenced before assignment
I have create model of comment in models.py with ForeignKey of Listing. while creating comment i get unexpected error i have posted so useful code to find error if request.method == 'POST': message = request.POST['message'] listing_id = request.POST['listing_id'] user_username = request.user.username listing = Listing.objects.all().filter(listing_id=listing.id) if listing: comment = Comment(message=message, user_username=user_username, listing_id=listing) comment.save() return redirect('listing', listing_id)``` and get this error as in picture[![error in browser][1]][1] [1]: https://i.stack.imgur.com/pdLPl.jpg -
django rest framework , Invalid json list
i am trying to add tags to my posts it works fine but whenever i make serializer class (to return json data ) it raise this error { "tags": [ "Invalid json list. A tag list submitted in string form must be valid json." ] } i have django-taggit and django-taggit-serializer package my models.py class Post(models.Model): title= models.CharField(max_length=50) description = models.TextField() location = models.PointField(srid=4326) tags = TaggableManager() my serializers.py class PostCreateSerializer(TaggitSerializer,GeoFeatureModelSerializer): tags = TagListSerializerField() class Meta: model = Post geo_field = 'location' fields = [ 'title','description','tags' ] my views.py class PostCreateApiView(CreateAPIView): queryset = Post.objects.all() serializer_class = PostCreateSerializer message = 'you have not account' permission_classes = [IsAuthenticated] def perform_create(self,serializer): serializer.save(user=self.request.user) i have seen some duplicated questions but wont worked in my case i use geo django with postgis database -
Django: problem with data format (string instead of JSON)
I have a new Django project with specific constraints for displaying data to be edited. I am not sure it is the best way to do the job. I want user: to be able to edit data directly in the html table add new lines in database (datas displayed at screen) Considering 2 forms : index form that display data of my model. When I click on "Modify settings" button user is redirected to edit form with the last 4 records send in the context (parameters) edit form display the last 4 records of my table with editable rows. When I click on "Modify settings" button I send data from html page with ajax query In my ajax view, I want to add data received in my model (4 new lines). But data below are not at JSON format but is a string??: datas [ { "ran_st1": "1", "ran_st2": "1", "bra_00A_act": "1", "bra_00A_lib": "Polyvitamines et oligo-éléments" }, { "ran_st1": "1", "ran_st2": "0", "bra_00A_act": "1", "bra_00A_lib": "Polyvitamines et oligo-éléments" }, { "ran_st1": "0", "ran_st2": "1", "bra_00A_act": "null", "bra_00A_lib": "null" }, { "ran_st1": "0", "ran_st2": "0", "bra_00A_act": "null", "bra_00A_lib": "null" } ] I don't understand how to convert as JSON? views.py @login_required … -
Django doesn't translate this form error : " Your username and password didn't match. Please try again."
I'm triying to translate my Django app to Spanish. I already set my settings.py like this: LANGUAGE_CODE = 'es' TIME_ZONE = 'America/Santiago' USE_I18N = True When I tried to login with invalid credentials I get this error message : "Your username and password didn't match. Please try again." which is in English. I already check django/django/contrib/auth/locale/es/LC_MESSAGES/django.po and I couldn't find this message translation and also couldn't find it i the english catalog (../en/LC_MESSAGES/django.po). Translation for other messages or tags seems to works. Anyone knows how to fix this? is this a bug or I'm doing something wrong? -
ModuleNotFoundError: No module named 'router'
Hi i am getting this error please help me. i am new on this field and i am getting this error. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'first', ] my views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from .serializers import MovieSerializer,RatingSerializers from .models import Movie,Rating # Create your views here. class MovieViewSet(ModelViewSet): queryset=Movie.objects.all() serializer_class=(MovieSerializer,) class RatingViewSet(ModelViewSet): queryset=Rating.objects.all() serializer_class=(RatingSerializers,) my main urls.py is """rest_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('my_apis',include('first.urls')), ] and serializers.py from rest_framework import serializers from .models import Movie,Rating class MovieSerializer(serializers.ModelSerializer): class Meta: model= Movie fields=['title','description'] class RatingSerializers(serializers.ModelSerializer): class meta: model=Rating fields='__all__' models.py is from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator,MaxValueValidator # Create … -
How to redirect logger django_structlog.middlewares.request to another file?
I use structlog with Django but I found my flat_line.log file difficult to read because every time an action is performed in the admin section there are several new entries like these: timestamp='2020-04-23T15:17:49.196600Z' level='info' event='request_started' logger='django_structlog.middlewares.request' request_id='bf82598e-5a34-4bd0-a698-7556bf4733a4' user_id=1 ip='127.0.0.1' request=<WSGIRequest: GET '/admin/myapp/market/'> user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' timestamp='2020-04-23T15:17:49.325273Z' level='info' event='request_finished' logger='django_structlog.middlewares.request' request_id='bf82598e-5a34-4bd0-a698-7556bf4733a4' user_id=1 ip='127.0.0.1' code=200 request=<WSGIRequest: GET '/admin/myapp/market/'> timestamp='2020-04-23T15:17:49.465507Z' level='info' event='request_started' logger='django_structlog.middlewares.request' request_id='9e7558a8-2d8f-4145-8569-9c6a74b0090b' user_id=1 ip='127.0.0.1' request=<WSGIRequest: GET '/admin/jsi18n/'> user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' timestamp='2020-04-23T15:17:49.468317Z' level='info' event='request_finished' logger='django_structlog.middlewares.request' request_id='9e7558a8-2d8f-4145-8569-9c6a74b0090b' user_id=1 ip='127.0.0.1' code=200 request=<WSGIRequest: GET '/admin/jsi18n/'> How can I redirect all entries from logger django_structlog.middlewares.request to another file so they don't flood the log files with a ton of undesired informations? This is how my configuration looks like: LOGGING = { "version": 1, "disable_existing_loggers": True, "formatters": { "json_formatter": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.JSONRenderer(), }, "plain_console": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.dev.ConsoleRenderer(), }, "key_value": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.KeyValueRenderer(key_order=['timestamp', 'level', 'event', 'logger']), }, }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "plain_console", }, "json_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "json.log", "formatter": "json_formatter", }, "flat_line_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "flat_line.log", "formatter": "key_value", }, }, "loggers": { '': { "handlers": ["console", "flat_line_file", "json_file"], "level": "INFO", } } …