Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to preserve newlines when importing json via loaddata
I have an object that uses \r\n line breaks in a CharField. When I export using dumpdata it provides valid json: { "mykey": "example\r\nsentence\r\nhere" } However when I import again using loaddata the CharField is stripped of newlines. How do I preserve them? -
Static files only served when debug = True and does not when it is False in production for nginx ubuntu 22.04
I have followed the setup procedures here https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04 and my Django app is running but whenever I turn debug = False it will not load my static files. Below is my nginx configuration: server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and my settings.py: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'my_site/static')] I have tried my best, researched a lot online, and followed many links but still fruitless. -
Complex queryset annotation
I am struggling with a pretty complex annotation of a QuerySet and I would really appreciate some help. Here are my models:- class Player(models.Model): group = models.ForeignKey(Group) class Transaction(models.Model): created = models.DateTimeField() amount = models.DecimalField(decimal_places=2, max_digits=10) player = models.ForeignKey(Player) Given a particular Group, I can get all the transactions for that Group using:- Transaction.objects.filter(player__group=group) But what I need is for each of those transactions to be annotated with the overall balance of the group at the time the transaction was created. So for each transaction, I need to sum all the transactions of the group whose created time was earlier than the transaction's created date. To do this, without ending up with tons of database calls, (I think) requires a complex queryset using things like Subquery and OuterRef but I can't quite figure out the exact logic. I tried something like this:- balance = queryset.annotate( balance=Sum( Case( When( date__lte=F("date"), then=F("amount"), ), default=0, output_field=DecimalField(), ) ) ).filter(pk=OuterRef("pk")) queryset.annotate( group_balance=Subquery(balance.values("balance"), output_field=DecimalField()) ) but I know that's not quite right. I feel like I'm close but it's driving me mad. -
{% providers_media_js %} causes: Error during template rendering, Site matching query does not exist
I'm trying to add facebook auth through django-allauth and everything is working fine when I run on localhost (except that I can't actually login because I have no SSL cert on localhost) when I push to Heroku, everything is fine except for my login page, where I get this error Error during template rendering In template /app/templates/main.html, error at line 2 Site matching query does not exist. my main.html: {% load socialaccount %} {% providers_media_js %} // error here <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Hello</h1> <a href="{% provider_login_url 'facebook' method='js_sdk' %}">Login with Facebook</a> </body> </html> my settings.py info: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'dj_rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', 'allauth.socialaccount.providers.facebook', 'django_extensions', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", "corsheaders.middleware.CorsMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ) SOCIALACCOUNT_PROVIDERS = \ {'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'kr_KR', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'}} #facebook SOCIAL_AUTH_FACEBOOK_KEY = '' # App ID here SOCIAL_AUTH_FACEBOOK_SECRET ='' #app … -
Django - Cannot run "python manage.py runserver" [closed]
Django==2.2 sentry-sdk==1.5.8 python=3.10 Error: Traceback (most recent call last): File "{path}/venv/lib/python3.10/site-packages/sentry_sdk/utils.py", line 188, in init self.project_id = text_type(int(path.pop())) ValueError: invalid literal for int() with base 10: 'None' -
django upload view fails
This is my Product model class Product(models.Model): name = models.CharField(max_length=255, blank=False) category = models.ManyToManyField(ProductCategory) thumbnail_image = models.ImageField(null=True, blank=True) description = models.TextField(null=False, blank=False) price = models.DecimalField(max_digits=20, decimal_places=2, null=False, blank=False) stock = models.IntegerField(default=0) tag = models.CharField(max_length=255, null=True, blank=True) date = models.DateTimeField(auto_now=True) enable = models.BooleanField(default=True) as you can see category is many to many. so I declared 'product.category.add(product_category)' in ProductUpload view @api_view(['POST']) def ProductUpload(request): img = request.FILES.get('thumbnamil_image') data = request.data product_category = request.POST.getlist('category') product = Product(name = data['name'], thumbnail_image = img, description = data['description'], price = data['price'], stock = data['stock'], tag = data['tag'], enable = data['enable'] ) product.save() product.category.add(product_category) return Response('success') I thought this is it to implement upload function. However, it does not work.. if I declare POST method view in ProductList view, it works though.. if I erase the POST part of the ProductList, it is not working.. How I can integrate two seperated upload logics in ProductUpload view? @api_view(['GET','POST']) def ProductList(request): if request.method == 'GET': products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ProductSerializer(data=request.data, many=False) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) -
how to activate some methods
enter image description hereHow can i activate "objects and create" method in Django? -
Django logges out from admin panel
I have a Django 4.1.1 app in production with Redis 7.0.4 cache backend, here is my settings.py: import os from pathlib import Path from datetime import timedelta from dotenv import dotenv_values config = dotenv_values(".env") BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'some-secret' DEBUG = True ALLOWED_HOSTS = ['production.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'core', 'staticpages', 'rest', 'user', 'rest_framework', 'rest_framework.authtoken', 'django_celery_results', 'django_extensions', "allauth", # allauth "allauth.account", # allauth "allauth.socialaccount", # allauth "allauth.socialaccount.providers.google", # allauth ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'django.middleware.locale.LocaleMiddleware' ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'allauth')], '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', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config['SQLDB'], 'USER': config['SQLDBUSER'], 'PASSWORD': config['SQKDBPASS'], 'HOST': config['SQLDBHOST'], 'PORT': '5432', # 'OPTIONS': {'sslmode': 'require'}, } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': config['REDISHOST'], } } LANGUAGE_CODE = 'fa' TIME_ZONE = 'Asia/Tehran' USE_I18N = … -
Api connections from react(axios) to nginx(docker/django) doesn't work. ERR_CONNECTION_REFUSED
I have a problem with connecting my fronted(react/axios) to backend(django) data hosted on VPS using nginx and docker. Problem is weird because I can connect to api by Postman. The issue appears when I try to get data from my frontend(localhost:3000) or from netlify app. There is nginx code: upstream 127.0.0.1 { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://127.0.0.1; } location /ws { proxy_pass http://127.0.0.1; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /static/ { alias /static/; } location /media/ { alias /code/media/; } } -
How to present Pandas Contingency Table in Django Template? How to iterate to get rows?
how can I get Pandas Contingency Table to Django Template? First I created function which returns contingency table with data from model: def monthly_quantity_table(table): mtable = pd.pivot_table(table, index="name", columns="link", values="quantity", aggfunc=np.sum, margins=True, fill_value=0, margins_name="TOTAL") return mtable Second I created necessary View to be able to get context to template: class StatsCategoryView(LoginRequiredMixin, FilterView): template_name = "stats/stats_category.html" model = SalesData filterset_class = StatsCategoryFilter ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) entry_data = self.object_list.values().order_by("date") ... try: mtable = utils.monthly_quantity_table(table) except: mtable = [0, 0, 0, 0] context["c1_m_table"] = mtable return context And finally I tried to present data from contingency table in template: First I checked that there is data and it is working. And it is OK, I can see data in template, function and view is working, but there is no formatting to rows or columns: <div class="row"> <div class="col"> {{ c1_m_table }} </div> </div> But then I tried iterate by rows from table, but it is not working and I am getting no data: <div class="row"> <div class="col"> {% for index, row in c1_m_table.iterrow %} {{ row }}<br> {% endfor %} </div> </div> I would like to iterrate through contingency table to get particular rows and to format them to … -
replace the base editor in django-wiki app
I use django-wiki app : https://django-wiki.readthedocs.io/en/main/ I try to replace the base editor. The default param are : wiki.conf.settings.EDITOR = 'wiki.editors.markitup.MarkItUp' I installed Martor (Markdown Editor plugin for Django) : https://github.com/agusmakmun/django-markdown-editor I don't know how properly load it. I tried import martor wiki.conf.settings.EDITOR = 'martor' and catch this error : django.core.exceptions.ViewDoesNotExist: '<module 'martor' from '/home/gabriel/Dev/Web/Projets/wp_ahimawiki/venv/lib/python3.10/site-packages/martor/init.py'>' is not a callable or a dot-notation path I tried also many things and catch differents errors. How properly change the django-wiki editors config ? Thanks for reading. ps: I use the last version of all packages (in a virtualenv) Linux Mint 21 Python 3.10.4 django 4.0.7 Markdown==3.3.7 martor==1.6.14 wiki==0.9 -
Unable to load min.js and min.css files in Django when debug=False
I am trying to deploy my website to Heroku for that I made some changes in the setting file. After that, I'm unable to runserver in debug=False. I got some issues with .min.js and .min.css file. I am getting the following error after running the server in debug=False (Djangoenv) PS E:\Engineering\Programming\Django\projects\Portfolio\New Instance 18-9\CRRathod> python manage.py runserver Performing system checks... System check identified no issues (0 silenced). September 18, 2022 - 16:32:16 Django version 4.0.6, using settings 'crrathod.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Traceback (most recent call last): File "c:\users\lonar\appdata\local\programs\python\python38\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\wsgi.py", line 132, in __call__ response = self.get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\base.py", line 140, in get_response response = self._middleware_chain(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner response = response_for_exception(request, exc) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 139, in response_for_exception response = handle_uncaught_exception( File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\whitenoise\middleware.py", line 60, in __call__ response = self.get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner response = response_for_exception(request, exc) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 139, in response_for_exception response = handle_uncaught_exception( File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\utils\deprecation.py", line 134, in __call__ response = response or self.get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 57, … -
Django PermissionRequiredMixin not working
When I place the PermissionRequiredMixin as the most left paramenter, my requests get forwarded to the login URL even though the request is coming from an already authenticated user. class ExampleViewSet(PermissionRequiredMixin, viewsets.ModelViewSet): permission_required = ('example.example_view',) When I place the PermissionRequiredMixin after the ModelViewSet the authenticated user is detected, however, the permission_required is ignored, and every user without the permission is allowed as well. And this answer suggested, that this is caused by the placement of the parameter, which leads to the first problem. class ExampleViewSet(viewsets.ModelViewSet, PermissionRequiredMixin): permission_required = ('example.example_view',) How do I solve this problem? -
name 'message' is not defined in django python
@login_required(login_url='login_user') def hrmanager(request): template = 'Job_portal/job_listing.html' if request.method == 'POST': form = job_posting_form(request.POST, request.FILES) if form.is_valid(): form.save() message.success(request, 'Job Posted Successfully') return redirect('hrmanager') job_posting = Job_posting_hr.objects.all() user = "hrmanager" job_add_form = job_posting_form() context = { 'edit_form': job_add_form, 'user': user, 'job_posting': job_posting } return render(request, template, context) -
Django - django.core.exceptions.FieldDoesNotExist - has no field named
On our production server we got the following error when restarting django or try to run 'python manage.py makemigrations' django.core.exceptions.FieldDoesNotExist: pricing.pricing has no field named 'price_per_hour' What is strange is that the field price_per_hour was renamed long time ago to price and the migration when well. But now I got this error every time and it is preventing to make any other model modification (in any app) and migrations. What I checked : If I run 'python manage.py showmigrations' every migration is flagged with an X, which if I'm right, means all the migration were done price_per_hour is no longer find/used in any of the django app / class class Pricing(models.Model): price = models.DecimalField(default=5,max_digits=10, decimal_places=2) class Meta: ordering = ['-price',] def __str__(self): return "{}".format(self.price) I also exported the matching./current database in sql and we well see that it contains price column and not price_per_hour. And no reference anywhere to price_per_hour CREATE TABLE public.pricing_pricing ( id integer NOT NULL, price numeric(10,2) NOT NULL, ); I also tried to rename the filed price to price_per_hour just in case but it didn't help For me it seems the error comes from Django rather than the postgrsql database but I'm no sure. I don't … -
pg_restore: error: input file is too short (read 0, expected 5)
I have a backup of PostgreSQL database(taken from Heroku) now I want to restore this backup to my local database but it's not working. tried from CMD and pgadmin, but no luck! what wrong I am doing? pg_restore --verbose --clean --no-acl --no-owner -h localhost -U nafuser -d naf latest.dump pgadmin issue -
Slant on divs from css border?
Here is my html: <div style="margin: 0 auto; margin-top: 25px; text-align: center; padding: 0px;"> {% for name in client_name %} <div class="appointment_data_div">{{ name }}<div> {% endfor %} </div> css: .appointment_data_div { margin: 0 auto; margin-top: 50px; width: 600px; height: 50px; box-shadow: 0px 5px 5px 0 #cccccc; border-radius: 15px; padding-top: 10px; border: 2px solid black; } For some reason, as you can see below, the divs are slanted?? I'm using django as my framework. -
Django deployment with apache server error
I have a django application deployed on apache server. following is os and apache details: Server Version: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f mod_wsgi/4.6.8 Python/3.8 when restarting apache and trying to access website i have this error: /var/www/backend/venv2/lib/python3.8/site-packages/pandas/__init__.py:11: UserWarning: NumPy was imported from a Python sub-interpreter but NumPy does not properly support sub-interpreters. This will likely work for most users but might cause hard to track down issues or subtle bugs. A common user of the rare sub-interpreter feature is wsgi which also allows single-interpreter mode. [wsgi:error] Improvements in the case of bugs are welcome, but is not on the NumPy roadmap, and full support may require significant effort to achieve. .... [wsgi:error] raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") [wsgi:error] django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. as you can see first it gives me a warning about numpy and after it, it gives me error about SECRET_KEY which supposed to read it from environment variables. SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') for this issue i read couple of texts and other stackoverflow questions and i even tried following directive inside my apache config file. WSGIApplicationGroup %{GLOBAL} but still nothing. -
Customize model manager in django
I am working on a django blog project. this is my models.py code: from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class PublishManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Post.Status.PUBLISHED) class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="blog_posts") title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2,choices=Status.choices,default=Status.DRAFT) objects = models.Manager() published = PublishManager() class Meta: ordering = ['-publish'] indexes = [ models.Index(fields=['-publish']) ] def __str__(self): return self.title when i put “published = PublishManager()“ on top of “objects = models.Manager()” like this: published = PublishManager() objects = models.Manager() i found that my admin site didnt show the entry with draft status. if i create a Post object with status equal Published,then it will be show in my admin site.if i create an object with status Draft,it won't show in admin site. i don't know why,could anyone can help me? -
Django Cart Total
I am making an e-commerce site with django. I set it to pay with paypal. But my problem is that I can't set the cart total when you pay. Here is the html code: ... createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value:'{{value}}' } }] }); }, ... Here is the models.py class Product(models.Model): name = models.CharField(max_length=200) image = models.ImageField(upload_to='images/') value = models.IntegerField(null=True) def __str__(self): return self.name class Order(models.Model): username = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200) value = models.IntegerField(null=True) image = models.ImageField(upload_to='images1/',null=True) def __str__(self): return self.name Here is the views.py: #Make an order if request.method == 'POST': name = request.POST['name'] product = Product.objects.filter(name=name).first() value = int(product.value) order = Order(name=name,username=cookie,value=value,image=product.image) order.save() #Buy def buy(request): cookie = request.COOKIES.get('name') if not cookie: return redirect('/') orders = Order.objects.filter(username=cookie).all() for i in orders: global value value = int(i.value) value = value + value return render(request,'cart.html',{'orders':orders,'value':value}) But I don't get the right value. How can I count the total value? Thanks. -
Django channels - why can't I receive data from js in websocket_disconnect method?
I have a chat application and I want to implement a feature that makes all messages read when a certain user disconnects from an active chat. I can get the user with self.scope['user'] but I don't know how to get the active chat from chatroom.js. My code: consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) ... async def websocket_receive(self, event): print('receive', event) ... async def websocket_disconnect(self, event): print('disconnect', event) received_data = json.loads(event['text']) user = self.scope['user'] chat_id = received_data.get('chat_id') chat_obj = await self.get_thread(chat_id) await self.disconnect_update_read_status(chat_obj, user) chatroom.js let loc = window.location let wsStart = 'ws://' if(loc.protocol === 'https') { wsStart = 'wss://' } let endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) socket.onopen = async function(e){ console.log('open', e) ... } socket.onmessage = async function(e){ console.log('message', e) ... } socket.onerror = async function(e){ console.log('error', e) } socket.onclose = async function(e){ console.log('close', e) let thread_id = get_active_thread_id() let data = { 'chat_id': thread_id } data = JSON.stringify(data) socket.send(data) } I tried this solution but I had an error, when disconnecting websocket didn't receive data: disconnect {'type': 'websocket.disconnect', 'code': 1001} WebSocket DISCONNECT /chat/ [172.20.0.1:54750] Exception inside application: 'text' Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ … -
Django Product price calculation
Here I am having a product detail. ```class product(models.Model): Product_name = models.CharField(max_length=50, null=True) product_description = models.TextField(max_length=170, null=True) product_price = models.SmallIntegerField(null=True) def __str__(self): return self.Product_name``` Depending on the product selection the value "30" has to change dynamically pending on the product. So that It will calculate price automatically. Please help me. user = form.save(commit=False) products = form.cleaned_data['Product'] Quantity = form.cleaned_data['Quantity'] shoping_product = product.objects.filter(Product_name= products) sub_total = 30 * Quantity user.Gst = 30 * (1 + 0.18) user.Price = sub_total + user.Gst user.save() messages.success(request, 'Registration successful.') return redirect('home')``` -
Django Error : ValueError at / Field 'ticket_id' expected a number but got 'NS000001'
While Inserting data, I got this error. May be this could be due to change of default primary key. I do not want to enter ticket_id field as I have set default value for that field (default='NS000001') models.py class Ticket(models.Model): ticket_id = models.AutoField(primary_key=True, default='NS000001', editable=False) server_details = models.CharField(max_length=100) send_date = models.DateTimeField(default=timezone.now) license_no = models.CharField(max_length=25) file = models.FileField(upload_to='documents/%Y/%m/%d/') def __str__(self): return self.ticket_id views.py def Index(request): if request.method == "POST": form = SaveTicket(request.POST,request.FILES or None) if form.is_valid(): form.save() print(form) return redirect('index') else: form = SaveTicket() return render(request, 'index.html') forms.py class SaveTicket(forms.ModelForm): class Meta: model = Ticket fields = ['server_details','send_date','license_no','file'] -
How can I send csrf_token?
Good afternoon! Please help me send csrf_token to the POST function for an authorized user. The error is, when I do user registration, the Forbidden (CSRF token missing.) error comes out: /data/task. The link to the library is below (there is also a demo project for this link). https://docs.dhtmlx.com/gantt/desktop__howtostart_python.html -
Not able to perform update and delete operation using custom html input fields
I am a beginner to Django. I am now doing a small project and I am encounter an issue while doing the update and delete operation. I am using forms.py but using custom input fields in html file. I have tried many ways but it returns errors. When I try to update it creates a new entry instead of update. When I perform delete nothing happens. Please go through the below code and help me out to resolve this. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('contacts', views.contacts, name='contacts'), path('update/', views.update, name='update'), path('delete/', views.delete, name='delete'), ] views.py def update(request, contact_id): details = Contact.objects.filter(id=contact_id) if request.method == 'POST': form = ContactForm(request.POST or None, instance=details) if form.is_valid(): form.save() return redirect('contacts') else: return render(request, 'update.html', {'details':details}) def delete(request, contact_id): contact = Contact.objects.all() if request.method == 'POST': details = Contact.objects.get(id=contact_id) details.delete() return redirect('contacts') return render(request, 'contacts.html', {'contact':contact}) contacts.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row mt-5"> <div class="col-sm-8"> <a href="{% url 'home' %}" class="btn btn-primary mb-3">Home ></a> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> …