Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
```AttributeError: 'Settings' object has no attribute 'FILE_CHARSET'```deployment error
AttributeError: 'Settings' object has no attribute 'FILE_CHARSET' trying to delov my project of Heroku but getting error -
django: problems refering to model primary key in templates (pk)
I am trying to pass the primary keys of a model through various templates and it seems like refering to model primary key as pk does not work. After reading the doc, it seems that the primary key of a model can always be refered as pk. Here is how I set things up: model.py class Products(models.Model): ProductName = models.CharField(max_length=100, primary_key=True) ProductUnit = models.CharField(max_length=100, default="NA") ProductCategory = models.CharField(max_length=100) ProductTagNumber = models.IntegerField(max_length=100) StockOnHand = models.FloatField(max_length=100) views.py def ProductsView(request): queryset = Products.objects.all() products_list = list(queryset) request.session['context'] = products_list return render(request, 'inventory.html', {'products_list':products_list}) def UpdateProductView(request,pk): Product = get_object_or_404(Products, pk=pk) if request.method == 'POST': form = UpdateProductForm(request.POST, instance = Product) if form.is_valid(): form.save() Name = form.cleaned_data.get('ProductName') Category = form.cleaned_data.get('ProductCategory') OH = form.cleaned_data.get('StockOnHand') update1 = Products.objects.filter(pk = pk).update(ProductName = Name) update2 = Products.objects.filter(pk = pk).update(ProductCategory = Category) update3 = Products.objects.filter(pk = pk).update(StockOnHand = OH) messages.success(request, "Changed in Product successfully recorded") return redirect('https://www.allelegroup.exostock.net/inventory.html') else: form = UpdateProductForm(initial = { 'Name' : Products.ProductName, 'Category' : Products.ProductCategory, 'OH' : Products.StockOnHand}, instance =Product) return render(request, 'update_product.html', {'form' : form}) urls.py path('inventory.html', ProductsView, name="inventory"), path('update_product/<int:pk>', UpdateProductView, name="update_product"), inventory.html <tbody style="background-color: white"> {% for Product in products_list %} <tr> <td>{{ Product.pk }}</td> <td>{{ Product.ProductCategory }}</td> <td>{{ Product.ProductTagNumber }}</td> <td>{{ Product.StockOnHand }}</td> … -
Django/Graphene seems to clean database between individual tests in a test run
I'm testing Django/Graphene to see if it can fulfill what I need, but I'm getting trouble in unit testing. I'm using the in-memory SQLite db, with the following code (tests.py): import json from graphene_django.utils.testing import GraphQLTestCase from graphene.test import Client from users.schema import UserType class APITestCase(GraphQLTestCase): def test01_query_users(self): print("Running test01_query_users") response = self.query( ''' query { users { id username email } } ''' ) print (response) content = json.loads(response.content) self.assertResponseNoErrors(response) print (content) assert content == { "data": { "users": [] } } def test02_mutation_addUser(self): print("Running test02_mutation_addUser") response = self.query( ''' mutation { createUser (username: "testuser", email: "testemail@testserver.com", password: "123456") { user { id username email } } } ''' ) print (response) content = json.loads(response.content) self.assertResponseNoErrors(response) print (content) assert content == { "data": { "createUser": { "user": { "id": "1", "username": "testuser", "email": "testemail@testserver.com" } } } } def test03_mutation_addUser(self): print("Running test03_mutation_addUser") response = self.query( ''' mutation { createUser (username: "testuser2", email: "testemail2@testserver.com", password: "123456") { user { id username email } } } ''' ) print (response) content = json.loads(response.content) self.assertResponseNoErrors(response) print (content) assert content == { "data": { "createUser": { "user": { "id": "2", "username": "testuser2", "email": "testemail2@testserver.com" } } } } def test04_query_users(self): print("Running test04_query_users") response … -
Django StaticLiveServerTestCase together with compressed hypertables
I am testing my django 2.2 application using StaticLiveServerTestCase. My database includes several compressed hypertables with foreign key relations i.e.: class Measurement(models.Model): pass class Sensor(models.Model): sensor = models.ForeignKey(Measurement, ...) class SensorResults(models.Model): results = models.ForeignKey(Sensor, ...) The timescaledb specific migration adaptation looks like migrations.RunSQL("SELECT create_hypertable('proj_sensorresults', 'time');"), migrations.RunSQL("ALTER TABLE proj_sensorresults SET (timescaledb.compress, timescaledb.compress_segmentby = 'results_id');"), migrations.RunSQL("SELECT add_compress_chunks_policy('proj_sensorresults', INTERVAL '1 days');"), When tearing down the test database the following error occures: psycopg2.errors.FeatureNotSupported: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "_compressed_hypertable_2" references "proj_sensor". HINT: Truncate table "_compressed_hypertable_2" at the same time, or use TRUNCATE ... CASCADE. I overrode sqlflush to include cascading, I manually truncated and dropped tables, I tried to decompress all hypertables before calling tear down and finally ended up disabling compression. Since my software will be used in the field with very limited bug fixing and updating possible I really do not want to run tests against a modified data base. I am pretty much out of ideas how to achieve this and really would appreciate your ideas! -
How to prevent changing slug value when updating the post if the title has not changed?
I have a purpose about learning django and rest framework. So I faced a problem when I worked on a tutorial project. The slug value changing every time when the article object updating. If the title value has not changed, I want the slug value not to change either. How can I handle this process? For example: When I update article but I haven't made any changes to the title field, the slug value also changes. before update "title" : "article 1", "slug" : "article-1", after update "title" : "article 1", "slug" : "article-1-1", models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) title = models.CharField(max_length=120) content = models.TextField() draft = models.BooleanField(default=False) # taslağa kaydetme işlemi created = models.DateTimeField(editable=False) modified = models.DateTimeField() slug = models.SlugField(unique=True, max_length=150, editable=False) image = models.ImageField( upload_to="media/post/%Y/%m/%d/", blank=True, null=True) modified_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="modified_by") def __str__(self): return self.title def get_slug(self): slug = slugify(self.title.replace("ı", "i")) unique = slug number = 1 while Post.objects.filter(slug=unique).exists(): unique = '{}-{}'.format(slug, number) number += 1 return unique def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() self.modified = timezone.now() self.slug = self.get_slug() return super(Post, self).save(*args, **kwargs) serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ["user", "title", "content", "created", "modified", … -
How can I dispatch URLs in the form sitename.com/<slug>/<slug> in django?
I am trying to create a website whose structure is something like this: A main page with various links of similar kind (like a blog). User can click on any on those and go inside any of them (link will be like site.com/slug). Then again the same thing (this time the link will be like site.com/slug/slug). individual_question.html <div id="argument_container"> {% for argument in argument%} <h6 id='{{ argument.argument_faction }}' style="display:none"><a href=" {{question.get_absolute_url}}{{argument.get_absolute_url}} " style="text-decoration: none; color: black">{{ argument.argument_text }}</a> <br><br> <button type="button" class="btn btn-outline-success btn-sm"><i class="fa fa-thumbs-o-down" style="padding-right: 3px;"></i>Agree</button> <button type="button" class="btn btn-outline-danger btn-sm"><i class="fa fa-thumbs-o-up" style="padding-right: 3px;"></i>Disagree and debate</button> </h6> {% endfor %} </div> urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', home_screen_view, name="home"), path('register/', registration_view, name="register"), path('logout/', logout_view, name="logout"), path('login/', login_view, name="login"), path('account/', account_view, name="account"), path('<slug:question>', individual_question_view, name="individual_question_view"), # for testing path('<slug:argument>', individual_argument_view, name="individual_argument_view"), models.py class Faction(models.Model): faction_id = models.BigAutoField(primary_key=True) faction_question = models.ForeignKey(Question, on_delete=models.CASCADE) faction_name = models.CharField(max_length=30) def __str__(self): return self.faction_name class FactionArgument(models.Model): argument_id = models.BigAutoField(primary_key=True) argument_faction = models.ForeignKey(Faction, on_delete=models.CASCADE) argument_question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True) argument_slug = models.SlugField(max_length=80, null=True) argument_text = models.TextField() user_id = models.ForeignKey(Account, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('individual_argument_view', args=[self.argument_slug]) # chances of error def __str__(self): return self.argument_text views.py def individual_question_view(request, question): context={} question = get_object_or_404(Question, … -
How to access a file object from a CBV that delivers it as a response
I am using Django-WeasyPrint to generate PDF files from HTML templates: from django_weasyprint import WeasyTemplateResponseMixin class MyModelView(DetailView): # vanilla Django DetailView model = MyModel template_name = 'mymodel.html' class PDFDownload(WeasyTemplateResponseMixin, MyModelView): # View that returns the PDF file as a download to the user def get_pdf_filename(self): return 'mypdf - {at}.pdf'.format( at=timezone.now().strftime('%H%M-%d%m%Y'), ) How can I access the file returned in the response as an object? E.g: my_pdf = HttpResponse(reverse( 'pdf_download', kwargs={'id': self.object.id}) -
Django ModuleNotFoundError: No module named "project_name"
when I try to run server I get this error File "/home/mori/Documents/Django/news/articles/admin.py", line 1, in <module> from news.articles.models import Article ModuleNotFoundError: No module named 'news' -
How to associate specific page id with forms to submit POST REQUEST?
Background I have created an small app that can add projects, and show it in the index page, all those projects can be access individualy to its own "profile proJect page" clicking on the project name. Inside the project's profile page, it can be seeing data as ProjectName, ResponsableName, Description and so on. Problem I'd like to add additional information to its project profile page such as financial aid amount, expected revenue,etc. So I have created the respective HTML Forms for each kind of information I need to submit, but I don't have idea how to associate the form with specific project_id. I'd be glad if you could provide me an example about it Project index Project Profile Page Financial aid form in case you click on "Agregar información" views.py def financiamiento(request): if request.method == 'POST': MontoProyecto = request.POST.get('MontoProyecto') MontoPropio = request.POST.get('MontoPropio') MontoBanca = request.POST.get('MontoBanca') MontoPublico = request.POST.get('MontoPublico') Financiamiento.objects.create(MontoProyecto=MontoProyecto, MontoPropio=MontoPropio, MontoBanca=MontoBanca, MontoPublico=MontoPublico) return redirect("/Portafolio") return render (request, "Portafolio/Financiamiento.html") -
nested_data ORM django problem in nested data
[ { "id": 10, "username": "naresh90", "notess": [ { "id": 8, "note": "hello world" }, { "id":9, "note":"hello world 2" } ] } ] how can i acces the notess data only, on screen.... in django... like, [ { "id": 8, "note": "hello world" }, { "id":9, "note":"hello world 2" } ] My views.py... @api_view(["POST","GET"]) def Note_retrive(request,username): if request.method=="POST": serializer=user_all_dataSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) elif request.method=="GET": dts=notes_user.objects.filter(username=username) serializer=user_all_dataSerializers(dts,context={'request': request} ,many=True) return Response(serializer.data) -
Django template rendering slowly
I'm rendering a template and it's taking anywhere between 2-3 seconds to do it. There are quite a few elements on the page (10k checkboxes) and I'm wondering if anyone knows any helpful tricks to cut down on load time. Is it database hits? After inspecting my django connections and profiling, I'm only making two database calls as far as I can tell. My datastructure is a dict which looks like: results_dict = { LemmaObj1 : [form11, form12, form13, ...], LemmaObj2 : [form21, form22, form33, ...], ... where the LemmaObj are Queryset objects. Generating this dict only takes 0.5 seconds. I force evaluation of the lazy queryset by putting the formij into a list comprehension. views.py lemma_qs = Lemma.objects.prefetch_related('form_set') # ... # some logic goes here # ... for lemma in lemma_qs: form_qs = lemma.form_set.all() form_list = [form.name for form in form_qs if form_filter.search(form.name)] if form_list: results_dict[lemma] = form_list context['results_dict'] = results_dict return render(request, "query.html", context) All this is to say that I'm pretty sure the slowdown isn't coming from database hits. The template in question In my query.html I have two for loops. query.html <div class="lemma-box"> <ol> <li class="lemma-title"> <div class="lemma-col-1"> lemma [{{results_dict|length}}] (group {{group}}) </div> <div class="lemma-col-2"> latin … -
Django makemigrations, 'module' object is not iterable
I'm new to Django and I was trying to use models and migrations, everithing works fine until I try to execute the command: python manage.py makemigrations where it rises the error: TypeError: 'module' object is not iterable I tried to reinstall django and create a new venv and change settings on my code editor, basically everything I could find online, yet I'm stuck with this error (full below). I would appreciate any help, thanks in advanced. Traceback (most recent call last): File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\checks\urls.py", line 23, in check_reso`enter code here`lver return check_method() File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\urls\resolvers.py", line 409, in check messages.extend(check_resolver(pattern)) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\checks\urls.py", line 23, in … -
How to get the selected row's record from a table in django?
I am new to django so I am sorry if this is a noob question. I have created a model "Students" in models.py and a view "Add_Student" for adding a new student, and another view "Display_Students" for displaying all the students. I have a table in which all the students are displaying perfectly with specific columns. But in the table, I added one more column that is "Action" and there is an eye-icon in that column. Now if someone click on that eye-icon so the complete information should be display in a new form/page. Displaying the information in a new form/page isn't the problem, but I don't know how it will work. Similarly, there will be an edit and delete icons. So here, my question comes, when I click on a eye-icon, how the django will get the desired row id from the table? from django.db import models # Create your models here. class students(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) fathername = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) state = models.CharField(max_length=50) zip = models.IntegerField(blank=True) address = models.CharField(max_length=100) contact =models.CharField(max_length=20) photo = models.FileField() Views.py from django.shortcuts import render, redirect from home.models import students # Create your views here. def … -
mysqlconnection not working in Django project M1 Mac
im trying just to do python manage.py migrate in my project. python --version Python 3.8.2 My pip list in my venv: Package Version ----------- ------- asgiref 3.3.4 Django 3.2.4 mysqlclient 2.0.3 pip 21.1.3 pytz 2021.1 setuptools 41.2.0 sqlparse 0.4.1 wheel 0.36.2 My Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'msapi', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', } } I've got an infinite error but most important: Traceback (most recent call last): File "/Users/micenor/Documents/Proyectos/MarvelStudiosAPI/project/.venv/lib/python3.8/site-packages/MySQLdb/init.py", line 18, in from . import _mysql ImportError: dlopen(/Users/micenor/Documents/Proyectos/MarvelStudiosAPI/project/.venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/micenor/Documents/Proyectos/MarvelStudiosAPI/project/.venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so Expected in: flat namespace in /Users/micenor/Documents/Proyectos/MarvelStudiosAPI/project/.venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so version_info, _mysql.version_info, _mysql.file NameError: name '_mysql' is not defined -
what is the false parameter in .delete(False)
I used an example from here which deletes unreferenced files when instance is deleted. one part of the code has this function: """ Only delete the file if no other instances of that model are using it""" def delete_file_if_unused(model,instance,field,instance_file_field): dynamic_field = {} dynamic_field[field.name] = instance_file_field.name other_refs_exist = model.objects.filter(**dynamic_field).exclude(pk=instance.pk).exists() if not other_refs_exist: instance_file_field.delete(False) What does the argument False mean in .delete(False) ? (I couldn't find a reference to it) Thanks -
Templates directory outside Django root
I have a templates directory /var/opt/backoffice/templates and inside there is a template called foo.html. The directory is outside the Django root directory, which is /opt/backoffice. I am trying to get Django to access the foo.html template in /var/opt/backoffice/templates using the get_templates('foo.html') command, but no matter what I try I get the error: django.template.exceptions.TemplateDoesNotExist: foo.html My settings.py for templates is: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'var/opt/backoffice/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', ], }, }, ] My question is , how can I configure Django so that I can access the template in /var/opt/backoffice/templates using get_templates('foo.html')? Thank you. -
Getting Youtube Channel ID using oAuth2.0 with Django/Python
Is there a way to obtain youtube channel ID or youtube userID using Google oAuth2. I am able to retrieve 'profile' and email details using oauth. Also provided scope for "youtube-readonly". I want to achieve this using Python/Django NB: General idea here is to show the Youtube Channel name and subscriber count of the logged in User. [user login through Google OAuth only.] -
WSGIServer: missing FastCGI required by WSGI
I am trying to run my project in Django from my hosting but at the moment of already trying to run it this error is shown in the terminal. WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI! WSGIServer: missing FastCGI param SERVER_NAME required by WSGI! WSGIServer: missing FastCGI param SERVER_PORT required by WSGI! WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI! Status: 400 Bad Request Content-Type: text/html To put them in context, I am following this tutorial: https://soporte-latam.hostgator.com/hc/es-419/articles/115002998391--Cómo-instalar-Django-en-entornos-compartidos-, that those of my hosting passed me for me to be able to install Django, finished all the steps already final to test if it is working that error is shown. Here my .htaccess AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_index} !-f RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] Here my index.fcgi #!/home4/quarkedi/.virtualenv/bin/python import os, sys from flup.server.fcgi import WSGIServer from django.core.wsgi import get_wsgi_application sys.path.insert(0, "/home4/quarkedi/Quark/Quark") os.environ['DJANGO_SETTINGS_MODULE'] = "settings" WSGIServer(get_wsgi_application()).run() Any ideas? Thank you! -
Heroku Django Postgres CREATE postgres schema on database. Multitenancy
the docs are not clear. Is it possible to create a schema system on postgres database in order to use postgres schemas as isolated data collection for a multi-tenant app directed by a sub-domain request. -
Page not found (404) The current path, media/15611349.jpg, didn’t match any of these
I cannot understand what my error is. I have a django project. In order to set up my media url, I followed the django doc Django doc - Managing static files and static media. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// IMAGE LINK RESULT DIR product_detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Product Image: <img src="{{products.image.url}}"> </body> </html> shop/urls.py from django.urls import path from .views import shop_home, ProductDetailView urlpatterns = [ path('', shop_home, name='shop_home'), path('products/<str:ct_model>/<str:slug>/', ProductDetailView.as_view(), name='product_detail') ] shop/views.py from django.shortcuts import render from django.views.generic import DetailView from .models import CPU, Smartphone def shop_home(request): return render(request, 'shop/index.html') class ProductDetailView(DetailView): CT_MODEL_MODEL_CLASS = { 'cpu': CPU, 'smartphone': Smartphone } def dispatch(self, request, *args, **kwargs): self.model = self.CT_MODEL_MODEL_CLASS[kwargs['ct_model']] self.queryset = self.model._base_manager.all() return super().dispatch(request, *args, **kwargs) context_object_name = 'products' template_name = 'shop/product_detail.html' slug_url_kwarg = 'slug' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('shop/', include('shop.urls')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_dev') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
Using RSA private key for decrypt data in Web Application
I am developing a web application that can help people encrypt data. The idea is to use different RSA encryption pairs for different user groups. But I want to hide both public key and private key like on password manager software. I mean, like users in a certain group will only receive encrypted pairs as *****/*******. Even users cannot see private pass strings. I read they can use USB token or PKI. But i dont know how can it connect to web app (django). Anyone have idea???? Thank -
Django Rest Framework and django rest framework simplejwt two factor authentication
I am using django version 3.2.4 in combination with Django Rest Framework. I also use https://github.com/jazzband/djangorestframework-simplejwt for JWTs. Problem: I need to enable Two Factor Authentication in the following way. User uses an endpoint that he submits his username & password. He receives back a jwt token that includes in a claim the verification code he needs to enter hashed. At the same time an email with this code goes to his email. Once the user receives the email he posts in another enpoint the verification code received and the jwt token he received in the previous step. If the code the user submitted matches the hashed code then he obtains the jwt token that it will be used in the subsequent requests. P.S. Any other ideas, that achieve something similar with the above are welcomed. -
DRF: Image page not found
I want to add ImageField to my module and follow the instruction Serializer returns http://127.0.0.1:8000/media/images/lkdj/unnamed.jpg but the link doesn't work (Page not found) How can I receive a valid link? Added MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # 'http://myhost:port/media/' models.py def name_image(instance, filename): return '/'.join(['images', str(instance.name), filename]) class Construction(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=name_image, blank=True, null=True) views.py class ConstructionView(viewsets.ModelViewSet): serializer_class = ConstructionSerializer queryset = Construction.objects.all() pagination_class = ConstructionSetPagination def get_construction_create_serializer(self, *args, **kwargs): serializer_class = ConstructionSerializer kwargs["context"] = self.get_serializer_context() return serializer_class(*args, **kwargs) def create(self, request, *args, **kwargs): serializer = self.get_construction_create_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) response = {"result": serializer.data} return Response( response, status=status.HTTP_201_CREATED, headers=headers) serializer.py class ConstructionSerializer(serializers.ModelSerializer): coordinates = PointField() deadline = serializers.DateTimeField(format=TIME_FORMAT) cameras_number = serializers.SerializerMethodField() class Meta: model = Construction fields = ( 'id', 'developer', 'name', 'image', 'address', 'coordinates', 'deadline', 'workers_number', 'machines_number', 'cameras_number', ) read_only_fields = ('workers_number', 'machines_number', 'cameras_number') def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance -
Queries related to Django Signals
To begin with, Here Profile and Seller model is created when a User model is created through Signals.What I want to do is When profile model is first created or updated,I want all the fields of Seller model to be same as all fields of Profile.Similarly when I first created Seller model,I also want all fields of Profile Model to be same as that of Seller model.But,I couldn't figure out how to do? from typing import Tuple from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.db.models.fields import DecimalField from django.dispatch import receiver from django.db.models.signals import post_save class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) #cascade is for deleting the customer first_name = models.CharField(max_length=10, null=True) second_name=models.CharField(max_length=10,null=True) email = models.EmailField(max_length=70, null=True,blank=True) @receiver(post_save, sender=User) def create_profile(sender, instance,created,**kwargs):#Signal receivers must accept keyword arguments (**kwargs). if created: Profile.objects.create(user=instance) ... @receiver(post_save, sender=Profile) def create_seller(sender, instance,created,**kwargs):#Signal receivers must accept keyword arguments (**kwargs). if created: Seller.objects.create(user=instance) class Seller(models.Model): user = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True, blank=True) #cascade is for deleting the customer first_name = models.CharField(max_length=10, null=True) second_name=models.CharField(max_length=10,null=True) email = models.EmailField(max_length=70, null=True,blank=True) ... -
How to use one Jquery function to handle multiple onchange (HTML) events
I have multiple item name drop-down fields along with price fields. When item is selected corresponding price should be updated in price field. -----HTML----- <tbody> <tr class="d-flex"> <td class="col-sm-5"> <div class="form-outline"> <select id="selectitem1" class="form-control" onchange="myFunction(event)"> <option selected disabled="True">--- select --- </option> {% for item in showdrop %} <option value="{{item.item_price}}" class="form-control" style="color:gray" font-size="20">{{item.item_name}}</option> {% endfor %} </select> </div> </td> <td class="col-sm-2"> <div class="form-group"> <input id="myText1" type="text" class="form-control price" value=" " name="price"> </div> </td> <tr class="d-flex"> <td class="col-sm-5"> <div class="form-outline"> <select id="selectitem2" class="form-control" onchange="myFunction(event)"> <option selected disabled="True">--- select --- </option> {% for item in showdrop %} <option value="{{item.item_price}}" class="form-control" style="color:gray" font-size="20">{{item.item_name}}</option> {% endfor %} </select> </div> </td> <td class="col-sm-2"> <div class="form-group"> <input id="myText2" type="text" class="form-control price" value=" " name="price"> </div> </td> </tbody> ---- function----- function myFunction(e) { document.getElementById("myText1").value = e.target.value }