Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multible dynamic URLs in django
Making a clinic website, in which the user is the clinics, who can then create "patient" objects. To navigate the page, I want the URLs to be dynamic and specific for the clinic and the given patient. Im having trouble making a selecting button on the clinics dashboard. The Dashboard has the following URL: /<str:kl_id>/ . the button should link to a patient page with the URL: /<str:kl_id>/patientside/<str:pt_id>/ The Views.py file looks like this: def klinik(request, kl_id): klinik = Klinik.objects.all() kliniknavn = Klinik.objects.get(navn=kl_id) E_patient = kliniknavn.patient_set.all() context = {'E_patient':E_patient, 'klinik':klinik} return render(request,'DentHelp/klinik.html', context ) I have tried in the template to make the following code, making a list of eksisting patients, with buttons leading to the dynamic patient page: {% for patient in E_patient %} <tr> <td>{{patient.id_nr}}</td> <td>{{patient.fornavn}}</td> <td><a href="{% url 'patientside' kl_id=klinik.navn pt_id=patient.id_nr %}" class="btn btn-primary">Vælg patient</a></td> </tr> {% endfor %} With this code do I get a NoReverseMatch error when trying the klinik page. Looking forward to getting help. -
make two fields in serializer from a same model
how are you? I used a nested serializer in another serializer and I have two models (Object and ObhectMedia)... here are the serializer class ObjectMediaSerializer(serializers.ModelSerializer): media_address = serializers.SerializerMethodField() class Meta: model = ObjectMedia fields = ["media_address", "type"] class ObjectAddEditSerializer(serializers.ModelSerializer): slug = serializers.SlugField(read_only=True) object_medias = ObjectMediaSerializer(many=True, required=True) class Meta: model = Program fields = [ "slug", "object_medias", ] I want to add object media in two fields(separated by their type) like below but I don't know how it is possible: { "slug":"my_slug", "object_media_type1": [ { "media_address ": "somewhere", "type":TYPE1 } ], "object_media_type2": [ { "media_address ": "somewhere", "type":TYPE2 }, { "media_address ": "somewhere\else", "type":TYPE2 }] } Thanks for reading -
403 CSRF verification failed. Request aborted. Django-Heroku-Cloudflare issue
I’ve made a heroku app with django and used the free ssl certificate of Cloudflare for my custom domain. The problem is that on a page I have a POST method with csrf token which shows ok in herokuapp.com but returns an error 403 in my custom domain served by Cloudflare! What should I do? -
how to setup daphne with nginx with djnago channels for websockets
I have to set up the Django server with WebSockets and HTTP requests. It works fine in my local system. and also on the server without SSL, but when we use the SSL on the server the HTTP request works fine on the https but WebSocket does not work with wss I am using Nginx for the webserver and daphne. this is my Nginx conf file server { listen 80; server_name domain.name; error_log /var/log/nginx/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /root/myprojectdir/staff_hiring/static; } location /media/ { autoindex on; alias /root/myprojectdir/staff_hiring/media; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and this is my asgi file import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import staff_admin.routing from channels.security.websocket import AllowedHostsOriginValidator import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'staff_hiring.settings') django.setup() application = ProtocolTypeRouter({ "https": get_asgi_application(), 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( staff_admin.routing.websocket_urlpatterns ) ) ) }) and routing file websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), # Using asgi # url(r'/ws/chat/', consumers.ChatConsumer.as_asgi()) ] -
csrf cookie not set on linux
I know this question is quite popular, before asking it, I researched all the previous questions and their answers, but never found a solution for myself. My problem is that I am trying to remove the csrftoken validation completely in my application. I understand the vulnerabilities that open up in this case, but this is not critical for me. During development, no errors occur on my computer due to csrftoken, I develop on windows, but when I run it on linux, this error appears, it’s hard for me to imagine the reason why this happens only on a linux server, I transfer using docker . I decided to remove csrftoken from my application for the same reason, on the windows computer on which I developed the application, no errors occurred with csrftoken enabled, but when transferred to a linux server, forms using data transfer using js files also gave an error 403. Settings MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', ] CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False I removed in js files csrf_token {# {% csrf_token %}#} I removed in js files headers // headers: {'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value}, I added in form attribute action="" <form class="js-edit-event-form" action=""> I already cleared … -
Custom Response to display the data in list of JSON using django
models.py class Project(models.Model): project_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='org_project',null=True) product = models.ManyToManyField(Product,related_name='product_project') client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client_project') project_name = models.CharField(unique=True,max_length=100) project_code = models.CharField(max_length=20) project_cost = models.IntegerField(null=True) currency_type = models.CharField(max_length=100, choices=CURRENCY_CHOICES, default='Indian Rupee') project_head = models.ForeignKey(User_Master, on_delete=models.CASCADE, related_name='project_head',null=True) project_manager = models.ForeignKey(User_Master, on_delete=models.CASCADE, related_name='project_manager',null=True) project_user = models.ManyToManyField(User_Master,related_name='project_user') description = models.TextField(max_length=500) start_date = models.DateField() end_date = models.DateField() techstack = models.ManyToManyField(Techstack,related_name='techstack_project') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.IntegerField(default=0, choices=STATUS_CHOICES) views.py from djmoney.settings import CURRENCY_CHOICES class CurrencyList(APIView): renderer_classes = (CustomRenderer,) def get(self, request, *args, **kwargs): return Response(CURRENCY_CHOICES, status=status.HTTP_200_OK) I was Trying to get the Currency code list in a response so that the data can be sent to the frontend as a dropdown list. When I Used the above django money package I am getting an response as { "status": "success", "code": 200, "data": [ [ "XUA", "ADB Unit of Account" ], [ "AFN", "Afghan Afghani" ], [ "AFA", "Afghan Afghani (1927–2002)" ], .... ], "message": null } But I need to Get the response as list of json inside the data not as the list of arrays, { "status": "success", "code": 200, "data": [ { "shortname": "XUA", "fullname": "ADB Unit of Account" }, { "shortname":"AFN", "fullname":"Afghan Afghani" … -
Error: object of type 'NoneType' has no len()object of type 'NoneType' has no len()
Tengo un sistema de productos de una tienda, el cual tiene varios usuarios y quiero hacer que uno en especifico(Proveedor) solo se le muestren los productos que el creo,pero a los demás usuarios si se les muestren todos los productos existentes en la base de datos. Si me respeta la condición sin problemas cuando inicio sesión con proveedor y solo me muestra los creados por el, pero cuando ingreso con otro perfil como de vendedor es cuando me arroja el error. Este es mi codigo: def get_queryset(self): query = super().get_queryset() if self.request.user.is_proveedor: query = query.filter(created_by_id = self.request.user) return query Pero recibo este error cuando inicio sesión con vendedor y quiero ver los productos: object of type 'NoneType' has no len() -
how do I write test cases for __str__ method for a model having two ManyToManyFields in Django Rest FrameWork?
Here are the three models where in the 3rd model we relate the above two models. #models.py class CategoryDetail(models.Model): categoryCode = models.BigAutoField( primary_key=True) categoryName = models.CharField(max_length=100) categoryDescription = models.CharField(max_length=500) def __str__(self): return self.categoryName class ProductDetail(models.Model): productCode = models.BigAutoField(primary_key=True) productName = models.CharField(max_length=100) manufacturer = models.CharField(max_length=100) def __str__(self): return self.productName class ProductCategoryMapping(models.Model): productCategoryCode= models.BigAutoField(primary_key=True) productCode= models.ManyToManyField(ProductDetail, related_name='category') categoryCode = models.ManyToManyField(CategoryDetail) def __str__(self): return '%s: %s' % (self.productCategoryCode, self.categoryCode) here is the test written which is having errors def test_CategoryMapping_str(self): product1 = ProductDetail.objects.create(productName = 'AquaTouch') category1= CategoryDetail.objects.create(categoryName = 'Trimmer & Shaver') categoryMapped = ProductCategoryMapping.objects.create(productCategoryCode= '1', productCode= product1.productCode, categoryCode= category1.categoryCode) self.assertEqual(str(categoryMapped), '1:Trimmer & Shaver ') The errorMessage says: "Direct assignment to the forward side of a many-to-many set is prohibited. Use productCode.set() instead" -
I have installed mysqlclient , but not able to run server
I am a beginner in python and Django. I would like to connect my Django project to MySQL database,I have installed mysqlclient brew install mysql pipenv install mysqlclient but after changing the settings to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'storefront', 'HOST': 'localhost', 'USER': 'root', 'PASSWORD': 'my_password', } } I get an error for running server: (NameError: name '_mysql' is not defined) source /Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/bin/activate (base) niloufar@Niloufars-MacBook-Air site-functions % source /Users/niloufar/.local/share/virtualenvs/ site-functions-HFSltvjv/bin/activate (site-functions) (base) niloufar@Niloufars-MacBook-Air site-functions % python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/niloufar/anaconda3/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Users/niloufar/anaconda3/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/niloufar/.local/share/virtualenvs/site-functions-HFSltvjv/lib/python3.9/site-packages/django/apps/config.py", line … -
Why don't the styles load?
I don't understand what I'm doing wrong this is te code -
Django ORM: get the monthly average of price for each category
Imagine this simple model: class Expense(models.Model): price = models.DecimalField(decimal_places=2, max_digits=6) description = models.CharField(max_length=300) category = models.CharField(choices=ExpenseCategory.choices, max_length=20) created_at = models.DateField() I'm trying to get the monthly average of price for each category in the current year. My general thought was to do something like: sub = ( Expense.objects.filter(created_at__year=date.today().year) .annotate(month=TruncMonth("created_at")) .values("month", "category") .annotate(total=Sum("price")) .order_by("month") ) qs = Expense.objects.values("category").annotate(avg=Avg(Subquery(sub.values("total")))) I'm basically trying to: Truncate the months of created_at Group by category and month Sum the prices Aggregate the prices for each category It works just fine if I do like: for category in categories: sub.filter(category=category).aggregate(avg=Avg("total")) -
how to fix nextToken for amazon api and python
i need some help to fix nextToken for this method : https://sp-api-docs.saleweaver.com/endpoints/inventories/ this is my code it's work but bring just 50 products and there is more then that, i try but i don't know how to fix it: product_client = Inventories(credentials=credentials) product_c = ListingsItems(credentials=credentials) res = product_client.get_inventory_summary_marketplace(**{"details": True,"marketplaceIds": ["********"]},next_token=None).payload for item in res.get("inventorySummaries"): try: _sellerSku=item.get("sellerSku") _asin =item.get("asin") resultat = product_c.get_listings_item(sellerId='********', sku=_sellerSku).payload for summaries in resultat.get("summaries"): _created_date = summaries.get("createdDate") _lastupdate_date = summaries.get("lastUpdatedDate") _mainImage = summaries.get("mainImage").get("link") _title =summaries.get("itemName") _condition =summaries.get("conditionType") inst = ProduitsAmz(asin=_asin, sellersku=_sellerSku,created_date=_created_date,lastupdate_date=_lastupdate_date,mainImage=_mainImage,title=_title,condition=_condition) inst.save() except: pass response is like this with more result : 'rate_limit': '5.0'} {'errors': None, 'headers': {'Date': 'Tue, 10 May 2022 16:12:10 GMT', 'Content-Type': 'application/json', 'Content-Length': '483', 'Connection': 'keep-alive', 'x-amzn-RequestId': 'c8eae15a-****-427c-b463-********', 'x-amzn-RateLimit-Limit': '5.0', 'x-amz-apigw-id': 'R******=', 'X-Amzn-Trace-Id': 'Root=1-627a8eda-*********'}, 'next_token': None, 'pagination': None, 'payload': {'sku': '*******', 'summaries': [{'asin': '*******', 'conditionType': 'used_good', 'createdDate': '2022-04-13T00:43:02.348Z', 'fnSku': '*******', 'itemName': 'Deadly Dose: The Untold Story of a ' "Homicide Investigator's Crusade for " 'Truth and Justice', 'lastUpdatedDate': '2022-04-13T01:46:25.755Z', 'mainImage': {'height': 500, 'link': 'https://m.media-amazon.com/images/I/******.jpg', 'width': 311}, 'marketplaceId': '*******', 'productType': 'ABIS_BOOK', 'status': ['DISCOVERABLE']}]}, I need some help to fix nexttoken and if there is any option to bring link for offer please (url in amazon), it's my seller account and i use amazon sp-api. Thank … -
problem with migrating on heroku with django windows 10
I am trying to migrate the database from django to heroku, the deploy is done correctly, but when doing heroku run python manage.py migrate, I get the following error https://www.toptal.com/developers/hastebin/kumayunigu.sql Does anyone know what is going on? here is my log https://www.toptal.com/developers/hastebin/uciyoxecuq.sql heroku error -
http status code 502, normal after refresh. uwsgi caused? nginx caused?
python + Django + uwsgi + nginx when the user visits the webpage, HTTP request returns 502 status code. And then the user immediately refreshes the page, it can be opened normally. Many users are getting this error. At this time, the concurrency is not large, no more than 20 users. I don't know what is causing the 502 error. Does anyone know how to solve it? For 502 errors, the uwsgi received a lot of error logs. like this: 9 16:07:37 2022] GET /usernames/chengyuyao@/count/ => generated 1658 bytes in 5 msecs (HTTP/1.0 404) 9 headers in 310 bytes (3 switches on core 0) uwsgi_proto_http_parser(): Bad address [proto/http.c line 463] !!! uWSGI process 115 got Segmentation Fault !!! *** backtrace of 115 *** /usr/local/bin/uwsgi(uwsgi_backtrace+0x2f) [0x55c95079ca7f] /usr/local/bin/uwsgi(uwsgi_segfault+0x23) [0x55c95079ce43] /lib/x86_64-linux-gnu/libc.so.6(+0x3bd60) [0x7f6e96acad60] /lib/x86_64-linux-gnu/libc.so.6(cfree+0x1c) [0x7f6e96b1973c] /usr/local/bin/uwsgi(uwsgi_close_request+0x13b) [0x55c9507519eb] /usr/local/bin/uwsgi(py_uwsgi_gevent_request+0x100) [0x55c9507c3e20] /usr/local/lib/libpython3.6m.so.1.0(PyCFunction_Call+0x45) [0x7f6e96d9f5f5] /usr/local/lib/python3.6/site-packages/gevent/_gevent_cgreenlet.cpython-36m-x86_64-linux-gnu.so(+0x10b6c) [0x7f6e91034b6c] /usr/local/lib/python3.6/site-packages/gevent/_gevent_cgreenlet.cpython-36m-x86_64-linux-gnu.so(+0x29182) [0x7f6e9104d182] /usr/local/lib/python3.6/site-packages/gevent/libev/corecext.cpython-36m-x86_64-linux-gnu.so(+0x23fff) [0x7f6e91e13fff] /usr/local/lib/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x8a) [0x7f6e96d7418a] /usr/local/lib/libpython3.6m.so.1.0(_PyObject_Call_Prepend+0x67) [0x7f6e96d74b07] /usr/local/lib/libpython3.6m.so.1.0(PyObject_Call+0x47) [0x7f6e96d74587] /usr/local/lib/python3.6/site-packages/greenlet/_greenlet.cpython-36m-x86_64-linux-gnu.so(+0x3819) [0x7f6e92898819] /usr/local/lib/python3.6/site-packages/greenlet/_greenlet.cpython-36m-x86_64-linux-gnu.so(+0x3a8f) [0x7f6e92898a8f] [0x7f6e8eff1588] *** end of backtrace *** uwsgi config: stdout_logfile_backups=5 enable-threads = true processes = 16 workers = 16 threads = 8 max-requests = 10000 master = true listen = 65536 #http-keepalive = true disable-logging = True nginx local.conf: client_body_buffer_size 128k; proxy_buffer_size 64k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; … -
What are the names of the endpoints provided by the Django auth app?
What are the names of the endpoints provided by the Django auth model? E.g., if I want to link to the login page, what do I put in the template? <a href={% url ???? %}>Login</a> -
Object of type Decimal is not JSON serializable
I got an error: TypeError at /cart/ Object of type Decimal is not JSON serializable Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 4.0.4 Exception Type: TypeError Exception Value: Object of type Decimal is not JSON serializable The fact is that I store my favorites and the basket in the same session, and when one of these is not filled (favorites / basket), this error appears. When the products are in both lists everything is fine. allow_nan True check_circular True cls <class 'json.encoder.JSONEncoder'> default None ensure_ascii True indent None kw {} obj {'cart': {'2': {'price': Decimal('123123.12'), 'product': <Product: test1>, 'quantity': 2, 'total_price': Decimal('246246.24'), 'update_quantity_form': <CartAddProductForm bound=False, valid=Unknown, fields=(quantity;update)>}}, 'featured': {}} separators (',', ':') skipkeys False sort_keys False How can i fix it? -
Python mixin: Why is my serialized field not coming through?
Trying to write a very simple python mixin for setting ReadOnly status'. This is what i have class ReadOnlyMixin: readonly_fields = serializers.SerializerMethodField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.get_readonly_fields(): self.fields[field].read_only = True def get_readonly_fields(self): raise NotImplementedError( "Classes subclassing ReadOnlyMixin must implement a " "`get_readonly_fields` method" ) and in my serializer class, I have class TestSerializer(mixins.ReadOnlyMixin, serializers.ModelSerializer): class Meta: model = models.Test fields = '__all__' def get_readonly_fields(self): exp = self.instance return ['status'] if exp.status != 'Pending' else [] Other fields in the serializer come thru, but readonly_fields does not. Everything is getting called as well because my self.fields['status'].read_only is getting upddated to True. Even if I just assign readonly_fields = ['status'], it still doesnt come thru. What am i doing wrong? -
Django: URLs to apps showing 404 errors
I have added three apps to my django website: application, blog, and feedback. All three have the same problem: when I click a link, or enter a URL, to any of them, I get a 404 error. I'm attaching code and other documentation below for one of the problem addons. For further context, if necessary, my full code can be found at https://github.com/kkerwin1/pensdnd. Directory structure (venv) kris@adjutant:~/venv/pensdnd$ tree -if . ./application ./application/admin.py ./application/apps.py ./application/forms.py ./application/__init__.py ./application/migrations ./application/models.py ./application/templates ./application/templates/application.html ./application/templates/application_thanks.html ./application/tests.py ./application/urls.py ./application/views.py ./blog ./blog/admin.py ./blog/apps.py ./blog/models.py ./blog/templates ./blog/templates/blog_list.html ./blog/templates/blog_post.html ./blog/tests.py ./blog/urls.py ./blog/views.py ./feedback ./feedback/admin.py ./feedback/apps.py ./feedback/forms.py ./feedback/models.py ./feedback/templates ./feedback/templates/feedback.html ./feedback/templates/feedback_thanks.html ./feedback/tests.py ./feedback/urls.py ./feedback/views.py ./manage.py ./pensdnd ./pensdnd/settings.py ./pensdnd/static ./pensdnd/static/css ./pensdnd/static/css/main.css ./pensdnd/static/html ./pensdnd/static/html/arvon_rules.html ./pensdnd/static/html/be_a_dm.html ./pensdnd/static/html/community_rules.html ./pensdnd/static/html/guild_rules.html ./pensdnd/static/html/index.html ./pensdnd/static/html/volunteer.html ./pensdnd/static/img ./pensdnd/static/img/carbon_fibre.png ./pensdnd/static/img/github_icon.png ./pensdnd/static/js ./pensdnd/static/misc ./pensdnd/static/templates ./pensdnd/static/templates/base.html ./pensdnd/static/templates/partials ./pensdnd/static/templates/partials/blogbar.html ./pensdnd/static/templates/partials/feedback.html ./pensdnd/static/templates/partials/footer.html ./pensdnd/static/templates/partials/navbar.html ./pensdnd/static/templates/partials/newsbar.html ./pensdnd/static/vid ./pensdnd/urls.py ./pensdnd/views.py ./pensdnd/wsgi.py ./requirements.txt ./pensdnd/urls.py from django.contrib import admin from django.urls import path, include from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.HomePageView.as_view()), path('admin/', admin.site.urls), path('be_a_dm', views.BeADM.as_view()), path('blog', include('blog.urls')), path('feedback', include('feedback.urls')), path('application', include('application.urls')), path('guild_rules', views.GuildRules.as_view()), path('community_rules', views.CommunityRules.as_view()), path('arvon_rules', views.ArvonRules.as_view()), path('volunteer', views.Volunteer.as_view()), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ./blog/urls.py from . import views from django.urls import path urlpatterns = [ path('blog', views.PostList.as_view()), path('blog/<slug:slug>/', views.PostDetail.as_view(), … -
Django Conditional Expressions to display different text strings based on Foreignkey value
I am trying to get a product description to automatically format based on the fields in the database record. I have looked at the Case() method but not sure if I can use it? The function is not working and only displays the value in the elif at the end, which I have given "not working" as a test. Models.py: from django.db import models from django.utils.functional import cached_property class FilmSpecs(models.Model): NO_UP = ( (1,'1 Up'), (2,'2 Up'), (4,'4 Up'), (6,'6 Up'), (8,'8 Up'), ) TINTS = ( ('NAT', 'Natural'), ('TNT', 'Tinted'), ('OPQ', 'Opaque'), ) SLIPLEVEL = ( ('STD', 'Standard'), ('LOW', 'Low Slip'), ('HIGH', 'High Slip'), ) stock_code = models.CharField(max_length=200, verbose_name="Stock Code", unique=True) desc = models.CharField(max_length=200, null=False, blank=False, verbose_name="Film Description") label_desc = models.CharField(max_length=200, verbose_name="Label Description") film_type = models.ForeignKey('settings.FilmType', on_delete=models.CASCADE, null=True, blank = False, related_name='film_type', verbose_name="Film Type") sale_type = models.ForeignKey('settings.SaleType', on_delete=models.CASCADE, null=True, blank = False, related_name='sale_type', verbose_name="Sale Type") film_width = models.IntegerField(null=True, blank=False, verbose_name="Film Width (mm)") guss_closed_width = models.IntegerField(null=True,blank=False, default=0, verbose_name="Gussetted Closed Width (mm)") micron = models.FloatField(null=False,blank=False, default=0,verbose_name="Micron") slip_level = models.CharField(max_length=30, choices=SLIPLEVEL, null=True) roll_weight = models.IntegerField(null=True, blank=True, verbose_name="Roll Weight (kg)") strip_out_size = models.IntegerField(null=True, blank=True, verbose_name="Strip Out Size (mm)") edge_trim_size = models.IntegerField(null=True, blank=True, verbose_name = "Edge Trim (mm)") tint = models.CharField(choices=TINTS, max_length=200, default="NAT", null=True, … -
Django/Python: execute code (sending email) without waiting for it to finish then immediately response to the client side
My question is basically the Python version of this question: code structure: def save(request): if request.method == 'POST': ... obj.save() # write data into database # the below sendmail step takes too long to finish # how to execute it without waiting for it to finish # then immediately run the last step: return render(request, 'success.html') sendmail(email) # return render(request, 'success.html') -
Django Python - Post not saving in Database Postgresql
I have an issue where my Django form is not posting into my Postgres database. Payload seems like all data is captured in variables. Here is my code if anyone can shine some light? Form is posted and redirect back to form etc however data isn't passed onto the database. Have tried this as an AJAX post too but still the same, capturing variables but not passing into the database for some reason. Views.py def createResidential(request): if request.method!="POST": return HttpResponseRedirect(reverse("apps:customers.create")) else: residential_firstname=request.POST.get("residential_firstname") residential_lasttname=request.POST.get("residential_lasttname") residential_contact=request.POST.get("residential_contact") residential_mobile=request.POST.get("residential_mobile") residential_email=request.POST.get("residential_email") residential_houseflatno=request.POST.get("residential_houseflatno") residential_houseflatname=request.POST.get("residential_houseflatname") residential_streetname=request.POST.get("residential_streetname") residential_city=request.POST.get("residential_city") residential_county=request.POST.get("residential_county") residential_postcode=request.POST.get("residential_postcode") try: postResidential=ResidentialCustomer( residential_firstname=residential_firstname, residential_lasttname=residential_lasttname, residential_contact=residential_contact, residential_mobile=residential_mobile, residential_email=residential_email, residential_houseflatno=residential_houseflatno, residential_houseflatname=residential_houseflatname, residential_streetname=residential_streetname, residential_city=residential_city, residential_county=residential_county, residential_postcode=residential_postcode, ) postResidential.save() messages.success(request,"Data Save Successfully") return HttpResponseRedirect(reverse('apps:customers.create')) except: messages.error(request,"Error in Saving Data") return HttpResponseRedirect(reverse('apps:customers.create')) Models.py class ResidentialCustomer(models.Model): residential_firstname = models.TextField() residential_lasttname = models.TextField() residential_contact = models.IntegerField() residential_mobile = models.IntegerField() residential_email = models.EmailField() residential_houseflatno = models.IntegerField() residential_houseflatname = models.TextField() residential_streetname = models.TextField() residential_city = models.TextField() residential_county = models.TextField() residential_postcode = models.TextField() residential_dateCreated = models.DateTimeField(default=timezone.now) agent = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return f"{self.residential_firstname} {self.residential_lasttname}" Form in html page <form action="{% url 'apps:createResidential' %}" method="POST" class="vertical-navs-step">{% csrf_token %} <div class="form-floating"> <input type="text" class="form-control" name="residential_firstname" placeholder="John"> <label for="residential_firstname">First Name</label> </div> Same for all other fields I need to capture … -
How can I move Django models to a different django app? I'm not sure the migrage --fake option can work for me since I have 2 cases to consider
In moving models from one django app to another, I used the approach recommended from this question: Moving multiple models from one django app to another class Post(models.Model): title = models.CharField(max_length=120) class Meta: db_table = 'blog_post' However, in my case, I also have some models that need to migrate, in addition to the ones that I'm moving to another app. Since I want some tables to stay intact (the ones migrating to another app), and some others to actually change, then I don't think the migrate --fake is an option I can use. What can I do? -
How to test django using test sqlite3 database instead default mysql database?
My databases in settings.py 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbname', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'mydb.com', 'TEST': { # it's not works 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } But TEST section not work. I use this code and it works but i don't like it. Maybe there are other way in databases section describe test database? if 'test' in sys.argv: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } -
Can't hit django views.py function from URL
I'm new to Django-react and having problem in hitting specific function of views.py file using URL. Here is my main project URL file urlpatterns = [ path('admin/', admin.site.urls), path('company/', include('manageCompany.urls')), ] Here it's manageCompany.urls file router = DefaultRouter() router.register('', CompanyViewSet, basename='companies') urlpatterns = [ # path('', index), path('', include(router.urls)), path('saveFile/', SaveFile) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's my views.py file class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer @csrf_exempt def SaveFile(request): if request.method == 'POST': file = request.FILES['file'] file_name = default_storage.save(file.name, file) return JsonResponse(file_name, safe=False) return JsonResponse("Hello") Now I'm trying to hit saveFile method from postman using POST method using URL http://127.0.0.1:8000/company/saveFile/ but it's showing "Method \"POST\" not allowed." Where it's going wrong? What should be my URL so that I could hit that SaveFile function? -
Not hashing password. Unexpected keyword argument 'password2'
I have three different questions. They're all related to each other. 1 - I get an error when I add password2 or confirm_password field. Got a `TypeError` when calling `CustomUser.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `CustomUser.objects.create()`. You may need to make the field read-only, or override the UserCreateSerializer.create() method to handle this correctly. TypeError: CustomUser() got an unexpected keyword argument 'confirm_password' 2 - Without any validate when I only have password field. I am not getting any errors but passwords are not hashed. 3 - When I want to create user using shell. Even if I leave all the fields blank, I can create an empty user without any errors.