Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert a list into Django Queryset
Here I am trying for a different way. My products will show in two way if user is passing location then first take the location and then usually do my filter using django-filters. It is working fine my filter unless I have problem with list object has no attribute model. I am trying to simplify my problem. I have multi vendor ecommerce and now user want to see the closeby vendor products and then advance filtering. everythin will be okay If I can convert a list into queryset. this is my views.py @api_view(['GET']) def getProducts(request): nearby_locations = get_locations_nearby_coords(23.7106, 90.4349, 5) if(nearby_locations.count() > 0): products = [] for i in nearby_locations: print(i.name) products.extend(list(Product.objects.all().filter(user__id=i.id))) filterset = ProductFilter(request.GET, queryset=products) if filterset.is_valid(): products = filterset.qs else: products = Product.objects.all() filterset = ProductFilter(request.GET, queryset=products) if filterset.is_valid(): products = filterset.qs page = request.query_params.get('page') paginator = Paginator(products, 10) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if page == None: page = 1 print(products) page = int(page) serializer = ProductSerializer(products, many=True) return Response({'products': serializer.data, 'page': page, 'pages': paginator.num_pages}) in my first if i have a list of products and then I am passing this list as queryset because I have to … -
Optimization queries with foreign key to self model
I have following models.py class Comment(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="replys") ... class Notification(models.Model): comment = models.ForeignKey(Comment, null=True, on_delete=models.CASCADE) ... and serializers.py class CommentSerializer(serializers.ModelSerializer): replys = serializers.SerializerMethodField() ... def get_replys(self, obj): queryset = obj.replys.select_related("author", "author__avatar").prefetch_related("author__engagement") serializer = CommentSerializer(queryset, many=True, context=self.context) return serializer.data class NotificationSerializer(serializers.ModelSerializer): comment = CommentSerializer(read_only=True) ... class Meta: model = models.Notification fields = "__all__" and service.py from django.contrib.auth import get_user_model def send_notifs(recipient): from vitalvoices.vital_notif.serializers import NotificationSerializer latest_notifications = Notification.objects.select_related( "comment", "comment__author", "comment__author__avatar", "comment__topic", "comment__parent", ).prefetch_related( "comment__author__engagement", "comment__reports", "comment__parent__replys", ).filter(recipient=recipient, checked=False).order_by("-pk")[:20] notifications_data = NotificationSerializer(latest_notifications, many=True).data After queries optimization I have this log SQL - SELECT "discussions_comment"."id", "discussions_comment"."author_id", "discussions_comment"."topic_id", "discussions_comment"."parent_id", "discussions_comment"."body", "discussions_comment"."created_at" FROM "discussions_comment" WHERE "discussions_comment"."parent_id" IN (82) Time - 0.001 SQL - SELECT "discussions_comment"."id", "discussions_comment"."author_id", "discussions_comment"."topic_id", "discussions_comment"."parent_id", "discussions_comment"."body", "discussions_comment"."created_at", "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", ... FROM "discussions_comment" LEFT OUTER JOIN "users_user" ON ("discussions_comment"."author_id" = "users_user"."id") LEFT OUTER JOIN "core_mediafile" ON ("users_user"."avatar_id" = "core_mediafile"."id") WHERE "discussions_comment"."parent_id" = 154 Time - 0.031 I have many queries such as second query. Maybe this problem linked with recursive relation (ForeignKey to self model). How can to optimize these queries using Django ORM? -
Use or for filter combination
I have two query like this below, Both,It works correctly, but I want to use OR for these sentences. I have ideas to use Q But it has complex filter. cls.objects.filter(point1__gt=0).filter(point1__lt=100) cld.objects.filter(point2__gt=0).filter(point2__lt=100) Is there any method to use OR for this sentenses? -
href attribute in django templates not fetching data?
I have a series of buttons in my frontend that display dynamically produced data like shown I am creating a href for each of these buttons where I am sending that dynamic data to a views.py using URL's. href in HTML: <a href="{% url 'test_this' button_type='IP' test_data=stats_data.location %}"><button type="button" >{{stats_data.location}} Service </button></a> urls.py pattern : urlpatterns = [ path('', dashboard_page, name ="home"), path('test/<str:button_type>/<str:test_data>', test_page, name = "test_this") ] URL produced on clicking the button: http://127.0.0.1:8000/dashboard/test/IP/202.154.121.13 My URL seems to be correct but I get this error: Reverse for 'test_this' with keyword arguments '{'button_type': 'IP', 'test_data': ''}' not found. 1 pattern(s) tried: ['dashboard/test/(?P<button_type>[^/]+)/(?P<test_data>[^/]+)$'] I dont get an error when I hard code Button_type and test_data values. Why am I not able to parse test_data=stats_data.location into <str:test_data>? -
VSCode: failed to load available options for Django's `load` template tag?
Suppose down there I can choose crispy_forms_tags (since I have installed) and others. The "Loading..." just persists without listing all available options. How to fix it please? Thank you. -
How can I check my society models name contains city's id or not?
I want to check my society's name contains the city's id and locality's id or not. First I want to iterate each society name and get city id by locality id and check that city name is appended at the end of the society name or not if yes then update all the society names by removing the city name. Second Then again I want to iterate each society name and get locality id and check the locality name is appended at the end of the society name or not if yes then update all the society names by removing the locality name. society.py class Society(models.Model): name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase. updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase. locality = models.ForeignKey('Locality', models.DO_NOTHING, db_column='localityId', blank=True, null=True, related_name='society_set') # Field name made lowercase. dot_com_database_id = models.IntegerField(db_column='dotComDatabaseId', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'societies' locality.py class Locality(models.Model): name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase. updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase. city = models.ForeignKey('City', models.DO_NOTHING, db_column='cityId', blank=True, null=True, related_name='locality_set') # Field name made lowercase. connect_database_id … -
Chained Dropdown in ModelFormset_Factory - Django
I want chained dropdown list in model formset. I have 4 models in my app App_Prod - Category, Product, OrderInfo, Order In my form, I used two views combinely. OrderInfo and Order So the choice list of product field of the Order model should be dependent on the category field of the OrderInfo model. Like if I select Electronics category the choice list should return only laptop and mobile option instead of showing all. See the image for your better understanding. Please suggest me what should I edit in my codes, or is there any other way to do so. models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) def __str__(self): return self.name class OrderInfo(models.Model): category = models.ForeignKey(Category, related_name='orderInfo', on_delete=models.CASCADE) date = models.DateField() def __str__(self): return self.category.name class Order(models.Model): info = models.ForeignKey(OrderInfo, related_name='orders', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='productName', on_delete=models.CASCADE, null=True) quantity = models.IntegerField() def __str__(self): return self.product.name forms.py class OrderInfoForm(forms.ModelForm): date = forms.DateField(widget=DateInput) class Meta: model = OrderInfo fields = ["category","date",] class OrderForm(forms.ModelForm): class Meta: model = Order fields = ["product","quantity",] widgets = { 'product': forms.Select(attrs={'class': 'formset-field form-control'}), 'quantity': forms.NumberInput(attrs={'class': 'formset-field form-control'}), } views.py def order_create(request): … -
How can I filter items in DjangoRestFramework?
I am complete beginner and I made a django project a while ago. Its main purpose is adding restaurants and categories and food menu respectively. For now, it is working well, if I go to the required restaurant, it shows its categories. But now, I want to improve it via Vuejs and that's why I'm trying to make Django REST API. But I can't filter categories and food according to their restaurant, because category model is not directly connected to restaurant model. My models.py is: from django.db import models from django.conf import settings class Restaurant(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL, related_name="restaurant", on_delete=models.CASCADE) name = models.CharField(max_length=256, db_index=True) slug = models.SlugField(max_length=256, unique=True) logo = models.ImageField(upload_to='logos/', blank=True) def __str__(self): return str(self.name) class Category(models.Model): name = models.CharField(max_length=256, db_index=True) slug = models.SlugField(max_length=256, unique=True) icon = models.ImageField(upload_to='categories/', blank=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return str(self.name) class Food(models.Model): restaurant = models.ForeignKey(Restaurant, related_name='foods', on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='foods', on_delete=models.CASCADE) name = models.CharField(max_length=256, db_index=True) slug = models.SlugField(max_length=256, blank=True) price = models.IntegerField(default=0) description = models.TextField(blank=True) image = models.ImageField(upload_to='foods/', blank=True) available = models.BooleanField(default=True) def __str__(self): return str(self.name) As you see, category class is not directly connected to restaurant. It is filtered with views.py. My views.py is: from django.shortcuts … -
can't login with facebook using allauth library using Django because of CSRF token and gave me CSRF verification failed. Request aborted
i have a server deployed in AWS using Django and every thing working fine until i tap on login with facebook Button it shows the normal facebook login popup and after typing my email and password instead of going to the next page it gave me CSRF verification failed. Request aborted. as you can see i've {% csrf_token %} in the code for showing login with facebook button using js_sdk: {% extends 'restaurant/base_auth.html' %} {% load bootstrap4 %} {% block title %}Akalat-Shop{% endblock %} {% block heading %}Akalat-Shop - Sign In{% endblock %} {% block content %} {% load socialaccount %} {% providers_media_js %} <a href="{% provider_login_url "facebook" method="js_sdk" %}">Login with Facebook</a> <form action="" method="post"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-primary btn-block">Sign In</button> </form> <div class="text-center mt-3"> <a href="{% url 'restaurant_sign_up' %}">Become a Restaurant</a> </div> {% endblock %} also i tried those in settings.py : LOGIN_REDIRECT_URL = '/' ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' SOCIAL_AUTH_REDIRECT_IS_HTTPS = True //all configurations of facebook login my views.py i've checked also for using @csrf_exempt: from django.views.decorators.csrf import csrf_exempt @csrf_exempt @login_required(login_url="/restaurant/sign_in/") def restaurant_home(request): return redirect(restaurant_order) from django.views.decorators.csrf import csrf_exempt @csrf_exempt @login_required(login_url="/restaurant/sign_in/") def restaurant_order(request): if request.method == "POST": order = Order.objects.get(id=request.POST["id"]) if order.status == … -
Django, how to set group based permissions
I am working on a project which has different types of users. Each group of user should be able to access some pages and be restricted to access other pages. I saw various solutions for this like. Some assign users to specific groups and then write a custom decorators to restrict pages like def allowed_users(groups=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in groups: return view_func(request, *args, **kwargs) else: return HttpResponse("You are not authorize to view this page ") return wrapper_func return decorator @allowed_users(groups=["admin"]) def products(request): pass and some tutorials and books recommend to assign user to groups and then give permissions to each group. like admin_group.set.permissions([list_of_permissions]) admin_group.add.permissions(per1, per2, ...) a quote which says Note: do not check the user in the group to verify whether the users have permission or not, so must use has_perm because at the bottom line user will inherit the permissions from the assigned groups and you can use groups to categorize users if your intention was just to use a User Role model alternative. My question is, which method is appropriate and why? and if we prefer the first method doesn't it break the role … -
django throws an error when there is no row in the table! django.db.utils.OperationalError: no such table: home_general
mainly the issue is creating on views.py queryset! I've tried with an existing database with some rows...there was nothng wrong! but if I remove all rows from admin panel then it shows this error django.db.utils.OperationalError: no such table: home_general here is my queries general = General.objects.first() social = Social_URI.objects.all() seo = SEO.objects.first() project_data = Project.objects.all() -
django.core.exceptions.ImprperlyConfigured solution
I wonder why I get this error : django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. this is my code : from main_app.models import student std1 = student(name='tom', fullname='scholz') std1.save() print(student.objects.all()) there is not any problem with running server and migrations. but when it comes to running a .py file (made by myself) such an error rises. -
Problem with installing psycopg2 with pipenv
I am trying to install psycopg2 via pipenv. I run the command pipenv install psycopg2 and it gives me this error message: Error: An error occurred while installing psycopg2! Error text: Collecting psycopg2 Using cached psycopg2-2.9.3.tar.gz (380 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [23 lines of output] running egg_info creating /private/var/folders/6c/c4fg2j7d5pjf9x_jqghl6z340000gn/T/pip-pip-egg-info-4dgmuaxk/psycopg2.egg-info writing /private/var/folders/6c/c4fg2j7d5pjf9x_jqghl6z340000gn/T/pip-pip-egg-info-4dgmuaxk/psycopg2.egg-info/PKG-INFO writing dependency_links to /private/var/folders/6c/c4fg2j7d5pjf9x_jqghl6z340000gn/T/pip-pip-egg-info-4dgmuaxk/psycopg2.egg-info/dependency_links.txt writing top-level names to /private/var/folders/6c/c4fg2j7d5pjf9x_jqghl6z340000gn/T/pip-pip-egg-info-4dgmuaxk/psycopg2.egg-info/top_level.txt writing manifest file '/private/var/folders/6c/c4fg2j7d5pjf9x_jqghl6z340000gn/T/pip-pip-egg-info-4dgmuaxk/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned … -
[DRF][Django][Github Action] I got 502 error from github actions workflows
I replaced some sync view class with async view class and async serializer class in my api server. what I used the class that is inherited for asynchronous is from here And when I deployed it through a github actions(with zappa), I got the following error from github actions Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code. ... Error: Process completed with exit code 1. I still haven't been able to solve it. I think this error is caused by the async view class, because the only change I made was to create an asynchronous view class and async serializer class. Is there any solution? -
Python TikTokApi SynchronousOnlyOperation error
I have a Django project where I am trying to fetch TikTok user info from a class based django view. I am running into an issue that appears to be related to async/sync/threading. Related documents: https://docs.djangoproject.com/en/3.2/topics/async/ I tried decorating views described in the link above still no luck. I added this bit of code to my gunicorn wsgi file os.environ.setdefault("DJANGO_ALLOW_ASYNC_UNSAFE", "true") which does fix the problem but seems like a bad idea. Here is the bit of code that I am using to call the TikTokAPI: def get_user_info(username): verify_fp = "code here" try: api = TikTokApi(custom_verify_fp=verify_fp) user = api.user(username=username) info = user.info_full() return info except Exception: return None class TikTokAccount(APIView): def post(self, request, *args, **kwargs): ... info = get_user_info(username) ... Traceback (most recent call last): File "/projects/social-bean/.pyenv/lib/python3.9/site-packages/gevent/pywsgi.py", line 999, in handle_one_response self.run_application() File "/projects/social-bean/.pyenv/lib/python3.9/site-packages/gevent/pywsgi.py", line 951, in run_application close() File "/projects/social-bean/.pyenv/lib/python3.9/site-packages/django/http/response.py", line 259, in close signals.request_finished.send(sender=self._handler_class) File "/projects/social-bean/.pyenv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 177, in send return [ File "/projects/social-bean/.pyenv/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/projects/social-bean/.pyenv/lib/python3.9/site-packages/django/db/__init__.py", line 57, in close_old_connections conn.close_if_unusable_or_obsolete() File "/projects/social-bean/.pyenv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 510, in close_if_unusable_or_obsolete if self.get_autocommit() != self.settings_dict['AUTOCOMMIT']: File "/projects/social-bean/.pyenv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 389, in get_autocommit self.ensure_connection() File "/projects/social-bean/.pyenv/lib/python3.9/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call … -
I am trying to display id page on to my home page
I'm trying to display id page http://127.0.0.1:8000/1/ on to my home page but I can't get it to work, I tried {{ posts.photos.id.slideshow }} but I can't display it on the home page home.html, is there anyway to display the the post image id page on to my homepage? views.py def SlidesShowView(request): posts = Slideshow.objects.all() return render(request, 'slideshow.html', {'posts':posts}) def ShowCaseView(request, id): post = get_object_or_404(Slideshow, id=id) photos = Showcase.objects.filter(post=post) return render(request, 'showcase.html', { 'post':post, 'photos':photos }) models.py class Slideshow(models.Model): title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField(blank=True) def __str__(self): return self.title class Showcase(models.Model): post = models.ForeignKey(Slideshow, default=None, on_delete=models.CASCADE) images = models.ImageField(null=True, blank=True, upload_to="showcase/images/") def __str__(self): return self.post.title urls.py from django.contrib import admin from django.urls import path from . import views from .views import HomeView, ArticleDetailView, AddPostView, EditPostView, DeletePostView, AddCategoryView, CategoryView, CategoryListView, LikeView, AddCommentView, SlidesShowView, ShowCaseView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ #path('', views.home, name="home"), path('', HomeView.as_view(), name="home"), path('article/<int:pk>', ArticleDetailView.as_view(), name='article-detail'), path('add_post/', AddPostView.as_view(), name='add_post'), path('add_category/', AddCategoryView.as_view(), name='add_category'), path('article/edit/<int:pk>', EditPostView.as_view(), name='update_post'), path('article/<int:pk>/remove', DeletePostView.as_view(), name='delete_post'), path('category/<str:cats>/', CategoryView, name='category'), #path('<str:cats>/', CategoryView ,name='category'), path('category-list/', CategoryListView, name='category-list'), path('like/<int:pk>', LikeView, name='like_post'), path('article/<int:pk>/comment', AddCommentView.as_view(), name='add_comment'), path('search_index', views.search_index, name='search-index'), path('', views.SlidesShowView, name='slideshow'), path('<int:id>/', views.ShowCaseView, name='showcase') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)**strong text** -
Django channels error : TypeError: __call__() missing 1 required positional argument: 'send'
I am working on Django channels and Async application and I am totally new into it. I started seeing tutorials for that . When I ran django server , it works fine but when I load the page or try to connect with websocket king client for testing the server , it show the error -> WebSocket HANDSHAKING /ws/game/roomname [127.0.0.1:51190] Exception inside application: __call__() missing 1 required positional argument: 'send' Traceback (most recent call last): File "C:\Users\user\anaconda3\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\user\anaconda3\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\routing.py", line 150, in __call__ return await application( File "C:\Users\user\anaconda3\lib\site-packages\asgiref\compatibility.py", line 34, in new_application return await instance(receive, send) TypeError: __call__() missing 1 required positional argument: 'send' WebSocket DISCONNECT /ws/game/roomname [127.0.0.1:51190] I am new into it and I am unable to solve the problem . Kindly help . My project asgi.py import os from channels.routing import ProtocolTypeRouter , … -
Que significa STATICFILES_ROOT? en si estoy trabajando en python y django
Si me podrian ayudar con lo que es, para que sirve y sus caracteriticas pero mas me interesa lo que es. -
I need help! insert qrcode in Django
I’m not good at Django. I asked the django community to help me with a problem. I want to create a form to upload a pdf file to the database , then take that file out to add qr code at the top of the first page . Then save it in databse . I have sketched my idea. If Django can’t solve it, please give me a solution. I’m writing a functional website in django. Pleenter image description herease help don’t reject me -
DRF: How do you create multiple "detail" views for a model?
I have a django model that has multiple fields that need to be used as a key, and also has some detail views. For example, my endpoints currently look like this, using detail=True to get the second set: my.api/things/{id_1} (GET, POST, DELETE) my.api/things/{id_1}/whatever (GET, POST) That's all great, but I have to get to something that looks like this instead: my.api/things/{id_1} (GET, POST, DELETE) my.api/things/{id_1}/whatever (GET, POST) my.api/things/other_id/{id_2} (GET, POST, DELETE) my.api/things/other_id/{id_2}/whatever (GET, POST) If it helps, the set of detail endpoints (ie. whatever) is identical, and there's no difference in functionality between the two. I just need to be able to access the database through either field. I'm new to django so I'm sorry if this is a simple question. Any help would be appreciated! -
Trying to follow a turorial code and I'm having path error
I'm a beginner trying django for the first time trying to map my urls together, but after following the necessary steps the django installation page keeps on showing on my browser. for my project app from django import path from django.urls import path from . import views urlpatterns = [ path('',views.index ) ] for my parent app from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] for my project views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('good sir') -
Django UpdateView creates duplicated formsets
I'm having problems when updating the entries of my products, discounts and inventory in the database, the inventories and discounts have the product id as a foreign key and I have defined two inline formsets to enter all the data in one single form ProductMeta=forms.inlineformset_factory(Product,Inventory,InventoryForm,extra=0,can_delete=False) DiscountMeta=forms.inlineformset_factory(Product,ProductDiscount,DiscountForm,extra=0,can_delete=False) Something strange happens, both formsets work normally when creating using extra=1 in the formsets, but in the UpdateView I must use extra=0, otherwise the inventory and discount forms get duplicated, and both forms disappear from the creation view views.py class UpdateProduct(UpdateView): model=Product form_class =ProductForm template_name = 'new_product.html' title = "UPDATE PRODUCT" def get_context_data(self, **kwargs): context = super(UpdateProduct, self).get_context_data(**kwargs) if self.request.method == 'POST': context['product_meta_formset'] = ProductMeta(self.request.POST,instance=self.object) context['discount_meta_formset'] = DiscountMeta(self.request.POST,instance=self.object) else: context['product_meta_formset'] = ProductMeta(instance=self.object) context['discount_meta_formset'] = DiscountMeta(instance=self.object) return context def form_valid(self, form): context=self.get_context_data() productMeta=context['product_meta_formset'] discountMeta=context['discount_meta_formset'] if productMeta.is_valid() and discountMeta.is_valid(): self.object=form.save() productMeta.instance=self.object productMeta.save() discountMeta.instance=self.object discountMeta.save() if not productMeta.is_valid(): print("productMeta invalid") if not discountMeta.is_valid() : print("discountMeta invalid") return redirect(reverse("products:listProducts")) For some reason Django considers that my productMeta and discountMeta are invalid since both prints are executed and obviously the changes are not saved in the database, for now I fix the inlineformset extra=0 problem using other inlineformsets, but I would like to know how to solve the invalid … -
(Hidden field id) Select a valid choice. That choice is not one of the available choices. (Django)
I'm receiving this error when I try to submit two formsets. After I fill the form and click the save button, it gives the error: (Hidden field id) Select a valid choice. That choice is not one of the available choices. I'm trying to create dynamic form so that the user can add new sections and also new lectures inside the section when they click "Add" button. The adding new form function works well, I just have problem saving it to the database. Views.py def addMaterials(request, pk): course = Course.objects.get(id=pk) sections = CourseSection.objects.filter(course_id=pk) materials = CourseMaterial.objects.filter(section__in=sections) SectionFormSet = modelformset_factory(CourseSection, form=SectionForm, extra=0) sectionformset = SectionFormSet(request.POST or None, queryset=sections) MaterialFormSet = modelformset_factory(CourseMaterial, form=MaterialForm, extra=0) materialformset = MaterialFormSet(request.POST or None, queryset=materials) context = { 'course': course, 'sectionformset': sectionformset, 'materialformset': materialformset, } if request.method == "POST": if all([sectionformset.is_valid() and materialformset.is_valid()]): for sectionform in sectionformset: section = sectionform.save(commit=False) section.course_id = course.id section.save() for materialform in materialformset: material = materialform.save(commit=False) print(material) material.section_id = section #section.id or section.pk also doesn't work material.save() return('success') return render(request, 'courses/add_materials.html', context) Forms.py class SectionForm(forms.ModelForm): class Meta: model = CourseSection fields = ['section_name', ] exclude = ('course_id', ) class MaterialForm(forms.ModelForm): class Meta: model = CourseMaterial fields = ['lecture_name', 'contents'] The second formset … -
Rebuilding a PyQt5 Desktop App for the web? with Python/Django
I have created a PyQt5 Desktop App but I've decided I want it as a webpage instead. So, to do this I think I'm going to completely remake the app using Django/python. My app is essentially 1 page of around 100 buttons that output midi notes when clicked. I would like to see exactly the same layout of buttons and CSS on a webpage as I currently do on my Desktop App and need to have the buttons call functions, just as they do on the desktop app. Essentially I need to translate my PyQt5 Desktop app to a Webpage and need help understanding how to start, thanks. -
aws codestar deploy daphne django
I need deploy my proyect with dpahne in aws codestar but, i can't do it, i do this in file install_dependencies # Set up a virtual environment python3.8 -m venv environment source environment/bin/activate # Install awscli and python dev libraries python3.8 -m pip install -r requirements.txt daphne -u /tmp/daphne.sock my_project.asgi:application but not works, do this in supervisor.conf environment/bin/daphne my_project.asgi:application --port 8000 --websocket_timeout -1 --bind 0.0.0.0 -v2 codestar use ami aws linux and i can't install like apt because yum is so restricted and somone know if i'm bad o know how do it, thanks.