Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django ModelForm - initial form values
I want to create an object instance where I set the (not unique) uid myself. I want to suggest the next "free" uid because that's the most used use case. class TestForm: last_uid = Process.objects.order_by("-uid").first().uid If I use the form the first time the value in last_uid is correct (let's say it's 42), but if I create a second instance, the last_uid is still the same value (again 42, but I would expect it to be 43). Do I have to hand the last_uid to the form and extract it in __init__() in order to make sure it is generated correctly on every new call of the form? -
Redis and Django - Working with localhost redis, Broken pipe when using redis on another host
I am running a local dev environment for Django and have separated out services like DB (MariaDB), RabbitMQ and Redis onto another host instance. Everything is working as expected Except for Redis, Django throws...: python3.11/site-packages/redis/connection.py", line 446, in send_packed_command raise ConnectionError(f"Error {errno} while writing to socket. {errmsg}.") redis.exceptions.ConnectionError: Error 32 while writing to socket. Broken pipe. ERROR:django.request: Internal Server Error: / (2023-11-09 07:29:04; log.py:224) However if I configure Django to use a localhost redis-server instance it works ok. The redis instance on the other host is accessible to the django server, i.e. I can connect to it using redis-cli -h devservices.orb.local from the django server (I'm using OrbStack to provide the server hosts, if that's relevant.) -
When accessing the database in the django websocket, incorrect data is returned
I am writing a websocket for a card browser game on django and channels. When the round ends, the results are counted, the calculation itself works correctly and even saves the calculations in the database. But at the end of the next round, when accessing the database, it returns the data that was before the previous round. That is, if at the beginning of the first round everyone has 0 points, at the end someone has 3 points, at the end of the next round 0 points are returned when calculating the result from the database. Although at the beginning of the same round, all players were sent data received from the database that someone had 3 points. I can't understand why this is happening, I didn't connect any caching. Here you can see the code of the entire project. Below is the code of the websocket method for calculating the results. The problem is in the data returned to players: async def calculate_results(self, event): game = await database_sync_to_async(Game.objects.get)( id=self.game_id ) players = await database_sync_to_async( lambda: list(Player.objects.filter(game=game)) )() self.round_num = await get_round_num(game) for player in players: round = await database_sync_to_async(Round.objects.get)( game=game, round_num=self.round_num ) association = await database_sync_to_async(Association.objects.get)( round=round, player=player ) … -
Reverse for ' sign-in' not found. ' sign-in' is not a valid view function or pattern name [closed]
I have urls.py in project. 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("core.urls")), path("user/", include("userauths.urls")) > ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Then, I create an app named "userauths". In my app I have userauths/urls.py: from django.urls import path from userauths import views as auth_views app_name = "userauths" urlpatterns = [ path("sign-up/", auth_views.register_view, name="sign-up"), path("sign-in/", auth_views.login_view, name="sign-in"), path("sign-out/", auth_views.logout_view, name="sign-out"), ] In index.html file. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Index Page</title> </head> <body> <a href="{% url 'userauths: sign-in' %}">Sign-in</a> </body> </html> But when runserver django, it display errors. I don't know this url Sign-in how to wrong? Reverse for ' sign-in' not found. ' sign-in' is not a valid view function or pattern name. -
Error in string representation of django models [closed]
I have these two models in orm django. Here is the code for two models in django. class Course(models.Model): course_id = models.CharField(primary_key=True, max_length=8) title = models.CharField(max_length=50, blank=True, null=True) dept_name = models.ForeignKey('Department', models.SET_NULL, db_column='dept_name', blank=True, null=True, related_name='course_dept_name') credits = models.DecimalField(max_digits=2, decimal_places=0, blank=True, null=True) def __repr__(self): return f"Course_id: {self.course_id}, Title: {self.title}" def _str__(self): return f"Course_id: {self.course_id}, Title: {self.title}, Department: {self.dept_name}" class Meta: managed = False db_table = 'course' class Department(models.Model): dept_name = models.CharField(primary_key=True, max_length=20) building = models.CharField(max_length=15, blank=True, null=True) budget = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) def __repr__(self): return f"Department Name: {self.dept_name}, Building: {self.building}, Budget: {self.budget}" def __str__(self): return f"Department Name: {self.dept_name}, Building: {self.building}, Budget: {self.budget}" class Meta: managed = False db_table = 'department' When i write for dept in Department.objects.all()[:5]: ...: print(dept) I got dept objects well printed Department Name: Accounting, Building: Saucon, Budget: 441840.92 Department Name: Astronomy, Building: Taylor, Budget: 617253.94 Department Name: Athletics, Building: Bronfman, Budget: 734550.70 Department Name: Biology, Building: Candlestick, Budget: 647610.55 Department Name: Civil Eng., Building: Chandler, Budget: 255041.46 The same with class Course does not print correctly course objects. for course in Course.objects.all()[:5]: ...: print (course) Course object (101) Course object (105) Course object (123) Course object (127) Course object (130) Can not find the error … -
Django HTML E-mail template can't load imported css?
Now I'm creating an email template using CSS defined in other files, which I imported into the template. I formatted the template using render_to_string("my_email.html") before sending it via email. The email was sent, however the template email could not load my imported CSS. I have tried but it didn't load imported css. Then my email content didn't have css. -
Creating a dropdown menu in django form based on user model
Hello i have the following model and form models.py class Project(models.Model): name = models.CharField(max_length=255, null=False) user = models.CharField(max_length=255, null=True) notes = models.TextField(null=True) forms.py class ProjectForm(ModelForm): class Meta: model = Project fields = ["name", "user", "notes"] How can i create a dropdown menu based on the builtin users in django, so that in my project form for user, i would have a drop down menu for the users instead of a textbox? -
sending csrftoken using fetch api from react to django
I am trying to send the csrf token i genenrated here is the csrftoken generation const [cr , setCR] = useState('') const getcsrf = async () => { await fetch('http://localhost:8000/auth/gettoken') .then( async res => await res.json()).then(data =>{ setCR( data.crsftoken) console.log(cr) }) } useEffect( () => { getcsrf() },[] ) after i have obtained the token i try to send it using fetch const handlelogin = async () => { if(cr !== ''){ console.log(cr) await fetch('http://localhost:8000/auth/login', {method : "POST", credentials: "include" , headers: { "Content-Type": "application/json", "X-CSRFToken" : cr }, body : { "username" : username, "password" : password } } ).catch(err => console.log(err))}else{console.log('cr is null')} } the csrf token is generated i can see it when i console.logged it but the fetch brings back a 403 forbidden error Forbidden (CSRF token from the 'X-Csrftoken' HTTP header incorrect.): /auth/login [09/Nov/2023 05:49:59] "POST /auth/login HTTP/1.1" 403 2553 i am expecting it to post to the url i gave it. what is wrong with it? -
Add user to group to specific database does not work
I am struggling to make the following code works for me. user = User.objects.using(data[‘db_name’]).get(pk=1) group = Group.objects.using(data[‘db_name’]).get(pk=2) user.groups.add(group) I can see that Django creates one record to auth_user_groups in the default database but not in the data[‘db_name’]) database. Interestingly, user and group objects are coming from data[‘db_name’] database. Can anyone advise me how to add new record to data[‘db_name’] database successfully? -
Detach Python Selenium from Gunicorn
I'm fairly new to gunicorn, Is there any possible way that allow me to run selenium browser outside of gunicorn enviroment? For example, I would like to update my Django application without interfering with a running selenium driver in the background. from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options def selenium(request): options = Options() options.add_argument("--headless=new") options.add_experimental_option("detach", True) chrome_path = "chrome/driver/chromedriver" driver = webdriver.Chrome(service=Service(executable_path=chrome_path) ,options=options) driver.get('https://example.com/') return HttpResponse(status=200) Selenium driver will stay active until, I restart gunicorn to update my code. Is there any other way to do so without driver shutting down? I've tried to detach selenium. and I've though that will be enough to allow driver to be detached from gunicorn. But that didn't work out. I'm updating my code through git and using "systemctl restart gunicorn" to allow it to update. -
When deploying django app, manage.py cant find views.py
I am trying to deploy a simple Django app that makes a user login and then serves a "hello world" on success. I use white noise for static. The web service builds correctly, but when deploying, I am getting the error module views.py can not be found. I can not understand why though as all paths seem to be correct. I use two different settings files; one for local development utilizing pip, and one for production using Gunicorn and a build.sh script (as per Render.com documentation). These are my server logs for deployment: Nov 8 11:05:22 PM Traceback (most recent call last): Nov 8 11:05:22 PM File "manage.py", line 23, in <module> Nov 8 11:05:22 PM main() Nov 8 11:05:22 PM File "manage.py", line 19, in main Nov 8 11:05:22 PM execute_from_command_line(sys.argv) Nov 8 11:05:22 PM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line Nov 8 11:05:22 PM utility.execute() Nov 8 11:05:22 PM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute Nov 8 11:05:22 PM self.fetch_command(subcommand).run_from_argv(self.argv) Nov 8 11:05:22 PM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv Nov 8 11:05:22 PM self.execute(*args, **cmd_options) Nov 8 11:05:22 PM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute Nov 8 11:05:22 PM output = self.handle(*args, **options) Nov 8 11:05:22 PM … -
Many to Many relation between two databases Django
I am building a separate Django project to handle a chat system, I already have a different Django project for everything else (user login info and serves API that does not relate to chat). In this chat project, it has a model class ChatRoom(models.Model): rmid = models.BigAutoField(primary_key=True) name = models.CharField(max_length=256) people = models.ManyToManyField(to=User, blank=True) timestamp = models.DateTimeField(auto_now_add=True) And a database router: class UserAuthRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'auth': return 'database_with_django_auth_models' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'auth': return 'database_with_django_auth_models' return None This allows me to use the same user login info from the main project since I have connected the database in settings. When I try to access ChatRoom model, I believe because the many-to-many field is relating to User model in the Auth lib/module, it causes this error as it is routed to use the other database: Django.db.utils.ProgrammingError: (1146, "Table 'database_with_django_auth_models.apps_chat_chatroom_people' doesn't exist") But the apps_chat_chatroom_people datatable is in the database that contains the ChatRoom schema, (i.e. the second database that is going to be used for the chat system) What is the proper way to handle this? I want to be able to use the same login credentials. -
how to create a multiple ForeignKey fields in a view create and save to database
First of all, I appreciate your help and time I would like to save all the 'equipamento' fields in the database instead of just one! When I save the form, it doesn't give any errors, but looking in the django admin, it is only saving one equipment field and not 2 or 3, because when I click on the green button (success) in the create view it generates 2 new fields to choose from. Moldel admin from django.contrib import admin from .models import Saida # Register your models here. admin.site.register(Saida) Moldel SAIDA # flake8: noqa from django.db import models from funcionario.models import Funcionario from estoque.models import Estoque class Saida(models.Model): funcionario = models.ForeignKey(Funcionario, verbose_name='Funcionário', on_delete=models.SET_NULL,null=True) data = models.DateTimeField(auto_now_add=True) observacao = models.CharField(max_length=500, blank=True, null=True, verbose_name='Observações') equipamento = models.ForeignKey(Estoque, verbose_name='Equipamento', on_delete=models.SET_NULL,null=True) quantidade_saida = models.PositiveIntegerField() def __str__(self): return f'Retirada N. {self.pk}' class Meta: verbose_name = 'Saida estoque' verbose_name_plural = 'Saida estoque' SAIDA VIEW CREATE def create(request): form_action = reverse('saida:create') if request.method == 'POST': form = saidaForm(request.POST, request.FILES) context = { 'form': form, 'form_action': form_action, } if form.is_valid(): saida = form saida.save() return redirect('saida:lista') return render( request, 'saida/create.html', context ) context = { 'form': saidaForm(), 'form_action': form_action, } return render( request, 'saida/create.html', context ) class … -
Problem communicating from celery container to redis
I'm Dockerizing my old project, but I came across this error: Traceback (most recent call last):File "/venv/lib/python3.10/site-packages/redis/connection.py", line 624, in connectsock = self.retry.call_with_retry(File "/venv/lib/python3.10/site-packages/redis/retry.py", line 46, in call_with_retryreturn do()File "/venv/lib/python3.10/site-packages/redis/connection.py", line 625, in <lambda>lambda: self._connect(), lambda error: self.disconnect(error)File "/venv/lib/python3.10/site-packages/redis/connection.py", line 690, in _connectraise errFile "/venv/lib/python3.10/site-packages/redis/connection.py", line 678, in _connectsock.connect(socket_address) During handling of the above exception ([Errno 99] Address not available), another exception occurred:File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 119, in reconnect_on_erroryieldFile "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 169, in _consume_fromself._pubsub.subscribe(key)File "/venv/lib/python3.10/site-packages/redis/client.py", line 1623, in subscriberet_val = self.execute_command("SUBSCRIBE", *new_channels.keys())File "/venv/lib/python3.10/site-packages/redis/client.py", line 1458, in execute_commandself.connection = self.connection_pool.get_connection(File "/venv/lib/python3.10/site-packages/redis/connection.py", line 1427, in get_connectionconnection.connect()File "/venv/lib/python3.10/site-packages/redis/connection.py", line 630, in connectraise ConnectionError(self._error_message(e)) During handling of the above exception (Error 99 connecting to localhost:6379. Address not available.), another exception occurred:File "/venv/lib/python3.10/site-packages/redis/connection.py", line 624, in connectsock = self.retry.call_with_retry(File "/venv/lib/python3.10/site-packages/redis/retry.py", line 46, in call_with_retryreturn do()File "/venv/lib/python3.10/site-packages/redis/connection.py", line 625, in <lambda>lambda: self._connect(), lambda error: self.disconnect(error)File "/venv/lib/python3.10/site-packages/redis/connection.py", line 690, in _connectraise errFile "/venv/lib/python3.10/site-packages/redis/connection.py", line 678, in _connectsock.connect(socket_address) During handling of the above exception ([Errno 99] Address not available), another exception occurred:File "/venv/lib/python3.10/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errorsyieldFile "/venv/lib/python3.10/site-packages/celery/app/base.py", line 787, in send_taskself.backend.on_task_call(P, task_id)File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 365, in on_task_callself.result_consumer.consume_from(task_id)File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 161, in consume_fromreturn self.start(task_id)File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 139, in startself._consume_from(initial_task_id)File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 168, in _consume_fromwith self.reconnect_on_error():File "/usr/local/lib/python3.10/contextlib.py", line 153, in … -
read two excel headers using django pandas
In an excel table I need to read a budget using pandas. In the first two lines are the columns with the header and content that will be used as objects to save in the Sorder class. in the third line I have a new header for the product items. I can't get pandas to recognize this new header with the items. EXCEL Sorder client payment_cond interest_discount_table price_list sorder_date requested_delivery_date 21101197111186 30/49 MT90 TEC9 01/11/2023 08/11/2023 product gross_price quantity LAAAAA1054 2 2 LAAAAA0962 3 3 `if excel_file.name.endswith('.xls') or excel_file.name.endswith('.xlsx'): try: df = pd.read_excel(excel_file) print("first two lines:") print(df.iloc[:1]) print("third line onwards:") df = pd.read_excel(excel_file, header=2) base_row = df.iloc[2] print(df.iloc[2:]) for index, row in df.iloc[2:].iterrows(): product = row['product'] gross_price = row['gross_price'] qtd = row['qtd'] product_base = base_row['product'] gross_price_base = base_row['gross_price'] qtd_base = base_row['qtd'] print( f"product: {product}, gross_price: {gross_price}, qtd: {qtd}") ` -
Netbox Plugin Integration Issue
I have a plugin that works when I install it manually in my VM, but when I try to run the program ./upgrade.sh, I get the error: django.core.exceptions.ImproperlyConfigured: Unable to import plugin ...: Module not found. Check that the plugin module has been installed within the correct Python environment. How do I get this to work as it will work manually, but not with the ./upgrade.sh. I have verified the filenames, the documentation, and other items, but not finding an answer that helps. -
django admin add extra content
I am not an expert in Django admin( I have models: class Device(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, max_length=128) name = models.CharField(max_length=256) class DeviceHistory(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name='device_history') created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) I want to add a table to the Django admin panel to the device's detailed page. There are two datetime inputs (start and end datetime). I need devide this time on hours, and check if exists one or more device history. This is how I've got the array of data: def get_device_history(device): date_first = timezone.now() - datetime.timedelta(hours=8) date_last = timezone.now() result = [] while date_first < date_last: date_end = date_first + datetime.timedelta(hours=1) histories_exists = DeviceHistory.objects.filter( device=device, created_at__gte=date_first, created_at__lte=date_end ).exists() result.append([str(date_first), str(date_end), histories_exists]) date_first = date_end And I've got something like this [['2023-11-08 10:03:00.577493+00:00', '2023-11-08 11:03:00.577493+00:00', False], ['2023-11-08 11:03:00.577493+00:00', '2023-11-08 12:03:00.577493+00:00', False], ['2023-11-08 12:03:00.577493+00:00', '2023-11-08 13:03:00.577493+00:00', False], ['2023-11-08 13:03:00.577493+00:00', '2023-11-08 14:03:00.577493+00:00', True], ['2023-11-08 14:03:00.577493+00:00', '2023-11-08 15:03:00.577493+00:00', True], ['2023-11-08 15:03:00.577493+00:00', '2023-11-08 16:03:00.577493+00:00', False], ['2023-11-08 16:03:00.577493+00:00', '2023-11-08 17:03:00.577493+00:00', True], ['2023-11-08 17:03:00.577493+00:00', '2023-11-08 18:03:00.577493+00:00', False]] How can I add this data to admin page like TabularInline table? And how can I add two datetime input for search in different range? Here is a picture of the functionality I need -
Django How to deploy image from database?
My project is the website which is moderated by a editor with admin laws (by the admin panel). He can add images for articles. Images are stored in the database. My problem is that I cant access images from the database in my website. They aren't displaying at all. Here is my structure of folders: folders in my project there are two apps: accounts and blog. For purpose of order i want to store images inside "blog" app in the folders like in the image. Here is my code: Models.py: class Reviews(models.Model): title = models.CharField(max_length=100) game_title = models.CharField(max_length=100) description = models.CharField(max_length=300) content = models.CharField(max_length=10000) game_rating = models.DecimalField(max_digits=2, decimal_places=1) game_user_rating = models.DecimalField(max_digits=2, decimal_places=1) date_of_publishing = models.DateField() def __str__(self): return f"{self.game_title}" class ReviewsMiniaturesImages(models.Model): miniature_image = models.ImageField(upload_to="blog/static/reviews_miniatures_images/") description = models.CharField(max_length=50) review = models.ForeignKey(Reviews, on_delete=models.CASCADE) Template: {% extends 'base.html' %} {% load static %} {% block content %} {% for review in reviews %} <div class="h-100 d-flex align-items-center justify-content-center"> <div class="card" style="width: 60rem;"> <img src="{% static review.reviewsminiaturesimages_set.get.miniature_image %}" class="card-img-top" alt="{{ review.reviewsminiaturesimages_set.get.description }}}}"> <div class="card-body"> <div class="row"> <div class="col"> <h5 class="card-title">{{review.game_title}}</h5> </div> <div class="col-7 d-flex justify-content-center"> <h4 class="card-title">{{review.title}}</h4> </div> <div class="col d-flex justify-content-end"> <h5 class="card-title">{{review.date_of_publishing}}</h5> </div> </div> <p class="card-text">{{review.description}}</p> <div class="row"> <div class="col"> <a href="{% … -
Django Migrations fails with postgres
I am trying to run a Django project with PostgreSQL but python manage.py migrate is failing with error - django.db.utils.ProgrammingError: relation "api_meeting" does not exist but there is not table with api_meeting on the other hand python manage.py migrate is working fine with sqlite database I tried - python manage.py migrate --fake but ended up with another error- relation "django_session" does not exist LINE 1: SELECT (1) AS "a" FROM "django_session" WHERE "django_sessio... my django version is 3.25 any ideas? Thanks -
Django pass user and product to current form
So i'm making a website that have some products and i want login user can leave a comment on that product but when submit a form (include rating from 1 to 5 star, text field), i can't set user and product therefor the form got error: {'user': ['This field is required.'], 'product': ['This field is required.']}. Because this method only for login user, is there a way to pass current user and the product get from product_id to the form. I think with the current user i can follow this question but what about the product. Any help would be appreciated! I already try to set it like below: @login_required(login_url='/login') def add_review(request, product_id): product = Product.objects.get(pk=product_id) nameForm = ProductNameForm() reviewForm = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) # print(form) if form.is_valid(): review = form.save(commit=False) print(review) review.user = request.user # Set the user review.product = product # Set the product review.save() product.average_rating = Review.objects.filter(product=product).aggregate(Avg('rating'))['rating__avg'] product.save() form = ReviewForm() print("Form is valid") else: print(form.errors) return render(request, 'add_review.html', {'form': nameForm, 'product': product, 'reviewForm': reviewForm}) Here is my review model: class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) rating = models.IntegerField() # You can add a rating field if needed … -
How to use ipdb debugger on Kubernetes environment
Traditionally I use ipdb as a debugger when I work on django. Here I want to use ipdb to debug so I put "import ipdb; ipdb.set_trace()" in my code. But on kubernetes I don't really know how to do it. I do kubectl attach pod-name -c container-name -i -t to access my django container, I see that the execution of the code stops on my breakpoint ok, BUT it continues and I get the error: "self.quitting: raise BdbQuit\nbdb.BdbQuit", the classic error that occurs when the code continues despite the breakpoint. It doesn't stop there, it continues straight on. How to properly use ipdb in a kubernetes env, any ideas ? Thank you ! -
Adminlte.io how to make the datable buttons work?
I wonder how to make the button works (copy CSV Excel PDF Print ..). See Data Table with default features {% extends 'adminlte/base.html' %} {% block title %}My App{% endblock %} {% block content %} <div class="card"> <div class="card-header"> <h3 class="card-title">DataTable with default features</h3> </div> <div class="card-body"> <div id="example1_wrapper" class="dataTables_wrapper dt-bootstrap4"><div class="row"><div class="col-sm-12 col-md-6"><div class="dt-buttons btn-group flex-wrap"> <button class="btn btn-secondary buttons-copy buttons-html5" tabindex="0" aria-controls="example1" type="button"><span>Copy</span></button> <button class="btn btn-secondary buttons-csv buttons-html5" tabindex="0" aria-controls="example1" type="button"><span>CSV</span></button> <button class="btn btn-secondary buttons-excel buttons-html5" tabindex="0" aria-controls="example1" type="button"><span>Excel</span></button> <button class="btn btn-secondary buttons-pdf buttons-html5" tabindex="0" aria-controls="example1" type="button"><span>PDF</span></button> <button class="btn btn-secondary buttons-print" tabindex="0" aria-controls="example1" type="button"><span>Print</span></button> <div class="btn-group"><button class="btn btn-secondary buttons-collection dropdown-toggle buttons-colvis" tabindex="0" aria-controls="example1" type="button" aria-haspopup="true"><span>Column visibility</span><span class="dt-down-arrow"></span></button></div> </div></div><div class="col-sm-12 col-md-6"><div id="example1_filter" class="dataTables_filter"><label>Search:<input type="search" class="form-control form-control-sm" placeholder="" aria-controls="example1"></label></div></div></div><div class="row"><div class="col-sm-12"><table id="example1" class="table table-bordered table-striped dataTable dtr-inline" aria-describedby="example1_info"> <thead> <tr><th class="sorting sorting_asc" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Rendering engine: activate to sort column descending">Rendering engine</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Browser: activate to sort column ascending">Browser</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Platform(s): activate to sort column ascending">Platform(s)</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Engine version: activate to sort column ascending">Engine version</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="CSS grade: activate to sort column ascending">CSS grade</th></tr> </thead> <tbody> <tr class="odd"> <td class="dtr-control sorting_1" … -
How to add Django ASGi in CPanel shared hosting?
I am using a shared hosting that provide cPanel, i am running a Django App with WSGI, and i want to use ASGI instead, to add the capability of real time stuff (like chat, ... etc). And i am not sure if that is possible with the shared hosting with cPanle option or not. I didn't try anything that may break the app. Thank you in advance. -
Cannot resolve keyword into field - Django shopping cart
Newby to Django here. I am trying to add a shopping cart to a simple project where users can pay for a single service. When a user provides basic info and clicks on 'checkout', I want to create the cart and add the only product they can pay for. It will always be one instance of the same product. I'm getting the following error when loading the cart page: Cannot resolve keyword 'product' into field. Choices are: id, quantity, user, user_id MODELS: class Product(models.Model) : name = models.CharField(max_length=100, unique=True) price = models.DecimalField(max_digits=8, decimal_places=2) description = models.TextField(null=True, blank=True, default='N/A') in_stock = models.BooleanField(default=True) updated_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['-id'] db_table_comment = 'Product catalog' def __str__(self) -> str: return self.name class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( max_length=150, validators=[UnicodeUsernameValidator, ], unique=True ) email = models.EmailField( max_length=150, unique=True ) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) objects = UserManager() USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email", ] class Meta: ordering = ['-date_joined'] class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.BigIntegerField quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} x {self.product}" def get_absolute_url(self): return reverse("cart:cart_detail") VIEWS: @login_required(login_url="/login_home") def cart(request): cart_item = Cart.objects.filter(user=request.user, product=1).first() if cart_item: cart_item.product = 1 cart_item.quantity = … -
How to serilaizer Both Image File and Array Field
Suppose I have this serializer in Django rest class CreateProfileSerializer(serializers.ModelSerializer): availability = UserAvailabilitySerializer(many=True) work_permit_pr = serializers.FileField() class Meta: model = UserProfile fields = [ 'work_permit_pr', 'availability' ] this is my views for above class but when i parse i am not able to either upload image or send data of array i.e many=True as front end always faces issue what is correct parser for both type i.e file and Serializer having many=True? class CreateUserProfileView(generics.CreateAPIView): serializer_class = CreateProfileSerializer permission_classes = [IsNanny, ] parser_classes = [parsers.MultiPartParser] def perform_create(self, serializer): return usecases.CreateUserProfileUseCase( serializer=serializer, user=self.request.user, ).execute() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) data = { "message": "User profile created successfully", "status": status.HTTP_201_CREATED } return Response(data)