Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do we have to host our Django site for our Flutter App backend?
Suppose I am creating a todo list app in Flutter. I have used Django to connect flutter's backend with the local host database. Now my API's(Django Rest Framework) are working fine if the is on local machine. But what if I deploy my Flutter app to Play Store? Then I need to host my Django site as well or it can be upon the local machine? -
How to make CRUD on a model through related model in Django Rest Framework?
For example: models class User(models.Model): nickname = models.CharField(max_length=30) email = models.CharField(max_length=60) class Group(models.Model): name = models.CharField(max_length=60) user = models.ForeignKey(User, on_delete=models.CASCADE) I have simplest serializers and view sets and I need to make CRUD part which on url would look like this: GET POST api/groups/{group_id}/users/ PUT PATCH DELETE api/groups/{group_id}/users/{user_id} so I can just see users which are related to the pointed group. Is there any provided or common way for such case? Thanks :) -
Django is not serving staticfiles
I would like to use django staticfiles, but unfortunately I can't get it to serve to images locally. This is what I have done so far: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'content.apps.ContentConfig', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) When I do a print(os.path.join(BASE_DIR, 'staticfiles')) I see the correct local path. urls.py: from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path import content.views urlpatterns = [ path('admin/', admin.site.urls), path('', content.views.index, name='index'), path('/about', content.views.about, name='about'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) templates: {% load static %} ... {% static "css/master.css" %} resolves to /static/css/master.css I am maybe missing something, just need an additional pair of eyes. Thanks. -
jsonb join not working properly in sqlalchemy
I have a query that joins on a jsonb type column in postgres that I want to convert to sqlalchemy in django using the aldjemy package SELECT anon_1.key AS tag, count(anon_1.value ->> 'polarity') AS count_1, anon_1.value ->> 'polarity' AS anon_2 FROM feedback f JOIN tagging t ON t.feedback_id = f.id JOIN jsonb_each(t.json_content -> 'entityMap') AS anon_3 ON true JOIN jsonb_each(((anon_3.value -> 'data') - 'selectionState') - 'segment') AS anon_1 ON true where f.id = 2 GROUP BY anon_1.value ->> 'polarity', anon_1.key; The json_content field stores data in the following format: { "entityMap": { "0": { "data": { "people": { "labelId": 5, "polarity": "positive" }, "segment": "a small segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 75, "anchorOffset": 3 } }, "type": "TAG", "mutability": "IMMUTABLE" }, "1": { "data": { "product": { "labelId": 6, "polarity": "positive" }, "segment": "another segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 138, "anchorOffset": 79 } }, "type": "TAG", "mutability": "IMMUTABLE" } } } I wrote the following sqlalchemy code to achieve the query first_alias = aliased(func.jsonb_each(Tagging.sa.json_content["entityMap"])) print(first_alias) second_alias = aliased( jsonb_each( first_alias.c.value.op("->")("data") .op("-")("selectionState") .op("-")("segment") ) ) polarity = second_alias.c.value.op("->>")("polarity") p_tag = second_alias.c.key _count = ( Feedback.sa.query() .join( CampaignQuestion, … -
How to retrieve data from comma separated values in Django admin
I am using a legacy database where many to many values are stored in an array like 1,2,3,4.. In django forms I am trying to use the below custom field to read multiple values. However they are getting stored as ['1','2'] instead of 1,2. Since it is an already existing database, I cannot go with many to many field. I have to store and retrieve values in the said format. class MultiSelectFormField(forms.MultipleChoiceField): widget = forms.CheckboxSelectMultiple def __init__(self, *args, **kwargs): self.max_choices = kwargs.pop('max_choices', 0) super(MultiSelectFormField, self).__init__(*args, **kwargs) def clean(self, value): if not value and self.required: raise forms.ValidationError(self.error_messages['required']) # if value and self.max_choices and len(value) > self.max_choices: # raise forms.ValidationError('You must select a maximum of %s choice%s.' # % (apnumber(self.max_choices), pluralize(self.max_choices))) return value I have changed my modelfield from ManytoManyField to Charfield in the process of achieving this functionality. In django admin page, if the dbtable has 1 value in the multiselectfield, django admin edit form page is showing the selected value, but if there are multiple values, nothing is getting populated... How do I achieve manytomany kind of functionality in this way--- like the column in the db field should have array of id's of the selected values. -
Bulk save edited items with Django?
I am editing a large number of model instances in django and I would like to save all these changes at once. The instances are already created so I am not looking for bulk_create. The changes are also different for each instance, so I can't use QuerySet.update(...) to apply the same change to all of them. I would like to replace this: for item in items_to_modify: item.some_field = process_new_data() item.save() by something like: for item in items_to_modify: item.some_field = process_new_data() items_to_modify.save_all_at_once() I am using django 3.1 -
How to make a choice field from many to many related classes in django?
I have a django web project. There are products for sales points. The points can have similar and different products to sale. So, i have created many to many relationship between them. class SalesPoint(models.Model): pointID = models.IntegerField() def __str__(self): myStr = str(self.pointID) + "ID'li nokta" return myStr class Product(models.Model): productID = models.IntegerField(verbose_name="Kaydedilecek ürünün ID'si", default=0) productName = models.TextField(verbose_name="Kaydedilecek ürünün adı") salesPoint = models.ManyToManyField(SalesPoint, verbose_name="Nokta ID", blank=False) def __str__(self): return self.productName Then I have a web page asking the user what product wants to be predicted. In this page, i want to create choice fields, and first i want to ask user which point he/she wants, then according to this point, i want to show available products(products that only belong to that sales point) to user. How can i make it? Here is my querying page module. class SalesPrediction(models.Model): whichPoint = models.ForeignKey(SalesPoint, on_delete=models.CASCADE, default=0) whichProduct = models.ForeignKey(Product, on_delete=models.CASCADE, default=0) However, this show all the products and points, i want to show only related points and products. -
Invalid block tag on line 90: 'cart_product_form', expected 'endblock'. Did you forget to register or load this tag?
I keep getting this error when I add the 2 lines below in the cart app in cart/detail.html {% item.update_quantity_form.quantity show_label=False %} {% item.update_quantity_form.update %} and a line below in the product app in products/product_detail.html {% cart_product_form %} how can I solve this error? Invalid block tag on line 90: 'cart_product_form', expected 'endblock'. Did you forget to register or load this tag? eshop_cart/views.py @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={ 'quantity': item['quantity'], 'update': True }) return render(request, 'cart/detail.html', {'cart': cart}) eshop_products/views.py def product_detail(request, *args, **kwargs): selected_product_id = kwargs['productId'] product = Product.objects.get_by_id(selected_product_id) if product is None or not product.available: raise ("not valid") related_product_pictures = ProductGallery.objects.filter(product_id=selected_product_id) pictures = MainTopSlider.objects.all() cart_form= CartAddProductForm() context = { 'product': product, 'related_product_pictures': related_product_pictures, "pictures": pictures, 'cart_form': cart_form } return render(request, 'products/product_detail.html', context) eshop_products/templates/products/product_detail.html <div class="pro-details-cart"> <form action="{% url "cart_add" product.id %}" method="post"> {% cart_product_form %} {% buttons %} <button type="submit" class="btn btn-success btn-product"> <span class="glyphicon glyphicon-shopping-cart"></span> Add to cart </button> {% endbuttons %} </form> … -
Run spiders in the background every n minutes when django server is running
I have a django project. Inside this project, there are some crawlers that crawl data from some websites and store it in database. With the django, these crawled data is shown. This is the structure of project: -prj db.sqlite3 manage.py -prj __init__.py settings.py urls.py wsgi.py -prj_app __init__.py prj_spider.py admin.py apps.py models.py runner.py urls.py views.py I want to run all spiders in the background every 5 minutes when django server is running. In the views.py I have import runner.py and in the runner.py all spiders start crawling. views.py: from . import runner runner.py: from twisted.internet import reactor from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from multiprocessing import Process, Queue from .prj_spider import PrjSpider from background_task import background @background() def run_spider(spider): def f(q): try: configure_logging() runner = CrawlerRunner() deferred = runner.crawl(spider) deferred.addBoth(lambda _: reactor.stop()) reactor.run() q.put(None) except Exception as e: q.put(e) q = Queue() p = Process(target=f, args=(q,)) p.start() result = q.get() p.join() if result is not None: raise result for spider in spiders: run_spider(DivarSpider, repeat=60) When run the server, I get this error: TypeError: Object of type type is not JSON serializable Also with this type of runner.py, I get below error: runner.py: @background() def fetch_data(): runner = CrawlerRunner() runner.crawl(DivarSpider) … -
Static content not served in https with Django and nginx
I have a Django project served by Nginx + Gunicorn. It all works well and everything is served via https excepts the content that the users upload in a /media folder, which are served via http. server { server_name mydomain; ssl on; ssl_certificate_key /home/me/private_key.key; ssl_certificate /home/me/ssl-bundle.crt; return 301 https://$host$request_uri; } server { server_name myip; ssl on; ssl_certificate_key /home/me/private_key.key; ssl_certificate /home/me/ssl-bundle.crt; return 301 https://mydomain$request_uri; } server { listen 80; listen 443; ssl on; ssl_certificate_key /home/me/private_key.key; ssl_certificate /home/me/ssl-bundle.crt; server_name mydomain; location /media/ { root /home/me/nms; client_max_body_size 100M; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The images coming from the media have the full address http://myip/media/.... Why is that? -
Timed Based Graph Plotting Python Django Using Firebase
I am using Django to make a dashboard to show sensor data. I am using chart.js for that I am retrieving sensor data of two days or less only. The problem is that how can I divide my graph for it.I think it might be possible using python time library or Django or something like that if so kindly suggest me some way to do it. I think that if java script can help us that will be great too. I just want data parsing based on time to plot and view it nicely. -
how to use django class model self in views.py
I want to create a filtering function and output the result value to the table. [A - models.py] class School(models.Model): .... def proceeding(self, request): from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') student= Student.objects.filter(school_id=self.id) return Feedback.objects.filter( entry_date__range=[from_date, to_date], student_id__in=student).values('entry_date').distinct().count() [B- models.py] class Student(models.Model): ... school = models.ForeignKey(School, on_delete=models.CASCADE) class Confirm(models.Model): .... school = models.ForeignKey(Student, on_delete=models.CASCADE) I know why the results are not displayed. I know that the request written next to self in models.py doesn't work. However, the reason you must use it in models.py rather than views.py is that you must use self. Please answer to the seniors who know how to make a request in models.py!! -
django-environ with gunicorn
Just followed the guide https://django-environ.readthedocs.io/en/latest/ added my .env file to project and settings, this runs fine with manage.py runserver, but goes to error with gunicorn: source project/settings/.env # export my local var echo $DEBUG #check if they exist on # this is the correct value from bash pipenv run gunicorn project.asgi:application -w 2 -k uvicorn.workers.UvicornWorker --log-file - #starting the server [2021-04-13 14:37:05 +0200] [80721] [INFO] Starting gunicorn 20.1.0 [2021-04-13 14:37:05 +0200] [80721] [INFO] Listening at: http://127.0.0.1:8000 (80721) [2021-04-13 14:37:05 +0200] [80721] [INFO] Using worker: uvicorn.workers.UvicornWorker [2021-04-13 14:37:05 +0200] [80737] [INFO] Booting worker with pid: 80737 [2021-04-13 14:37:05 +0200] [80738] [INFO] Booting worker with pid: 80738 [2021-04-13 14:37:05 +0200] [80737] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/uvicorn/workers.py", line 63, in init_process super(UvicornWorker, self).init_process() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in … -
Assign a model to another model using ModelChoiceField
I am new to Django and would like to create a platform where teachers can create student profiles and assign reports to the specific student. Therefore, I have made two models (Student & Report) and two CreateViews. When creating a report, the teacher has the option to select a student from a choice field. This I have done using ModelChoiceField. However, when submitting the report model, the students name is not saved to that model. How can I accomplish this? Ultimately I would like to have a profile to each student showing their info and reports attached to their model. models.py class Student(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30, default="") age = models.CharField(max_length=2, default="", blank=True) class Report(models.Model): date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=30) forms.py class StudentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) class Meta: model = Student fields = ['name','age',] class ReportForm(forms.ModelForm): student = forms.ModelChoiceField(queryset=Student.name, initial=0) class Meta: model = Report fields = ['title','file','player',] views.py class StudentCreate(LoginRequiredMixin, CreateView): model = Student template_name = 'student_create.html' form_class = forms.StudentForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class ReportCreate(LoginRequiredMixin, CreateView): model = Report template_name = 'report_create.html' form_class = forms.ReportForm def form_valid(self, form): form.instance.author = … -
Dynamic filter in django template
I would like to provide users possibility of filtering orders by any value, for example date, id etc. Is there any way how to do it using django feautures? I know, that i could create API and sort the values using js, but for the time being i would like to avoid it. Model: class Order(models.Model): is_printed = models.BooleanField(default=False) id = models.IntegerField(primary_key=True) done = models.BooleanField(default=False) ...other fields View: class OrdersView(View): def get(self, request, *args, **kwargs): orders = Order.objects.all().order_by('-id') return render(request, "orders.html", {"orders": orders} HTML Template: {% for o in order %} {{o}} {% endfor %} -
Iframe stops working after upgrading to Django 3.2 LTS
I was using Django 2.2 up till now and I recently tried upgrading to Django 3.2 We use a website live chat plugin called tawk.to which works by embedding an iframe to our page with the chat option in there. However, after upgrading to Django 3.2, even though the plugin's JS code is loading, the iframe is missing from the website altogether. I am not sure what is causing the issue. Is the iframe blocked in Django 3.2 or do I have to enable any setting for it? -
Django - reading MultiPolygons from postgres database does not return valid geometries
I'am creating web app to display some data in forms of charts, maps etc. I am using Bokeh for plotting. For maps I need to load shapefile with MultiPolygons containing regional borders. I have it loaded in my PostgreSQL database and I can display geometries from pgAdmin. I have a model for this table registered, here's the code class Polska(models.Model): gid = mdls.AutoField(primary_key=True) region = mdls.CharField(max_length=80, blank=True, null=True) geom = mdls.MultiPolygonField(srid=0, blank=True, null=True) When I'm trying to load these shapes and pack them into GeoDataFrame from geopandas I get a massive wall of text with an error (its just a snippet, basically it prints me the entire geometry) Input must be valid geometry objects: MULTIPOLYGON (((494179.5260320738 358814.2954531405, 494173.5314778397 358816.6456283908, 494178.0633204972 358822.8603784787, 494231.7738932786 358896.5675205989, 494321.7782545781 359023.6103092115, 494341.6988730072 359051.7332468079.....))) Code from loading in my views:geodf = gpd.GeoDataFrame(pd.DataFrame(Polska.objects.values("region","geom")),geometry="geom") So there is a geometry object, but for some reason it doesnt read as one. Interestingly when I try to check the type of this Multipolygon object it tells me "MULTIPOLYGON EMPTY". Can someone help me out and suggest where the problem can be? If some info is missing than let me know, I'll update asap. -
Argparse arguments in Flask application (production)
I'm trying to refactor a command line Python 3 application to an API with Flask. The application has a computer vision use case and I'm receiving an image for analysis. I'm currently using OpenCV, Python 3.8.7 I am not sure on how to refactor the arguments passes into the command line. What is the best way to bring these arguments into a production environment? Maybe move away from them? These are the Arguments: ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to image") ap.add_argument("-y", "--yolo", required=True, help="path to YOLO Directory") ap.add_argument("-c", "--confidence", type=float, default=0.8, help="minimum confidence") ap.add_argument("-t", "--thereshold", type=float, default=0.3, help="thereshold") args = vars(ap.parse_args()) Thank you! -
Is my approach for creating a custom user model for my Ecommerce website correct?
I am creating a Custom User Model for my Ecommerce website . There are three types types of users in my website : Buyer Seller Company employee (Note : Company employee are further classified into the following types) 3.a) Sales support 3.b) Moderation team 3.c) Analytics team 3.d) Ticket manager 3.e) Super admin So basically there are 7 different types of users in our ecommerce seller , buyer and 5 types of company users . Now , In order to achieve this , I first created a new app called "Users" in my freshly made blank Django project . Inside the Users/models.py , I created the Custom user model as follows : #Users/models.py from django.contrib.auth.models import AbstractUser from django.db import models user_type_choices = ( (1, 'buyer'), (2, 'seller'), (3, 'Sales-Support'), (4, 'Moderator-Team'), (5, 'Analytics-Team'), (6, 'Ticket-Manager'), (7, 'Super-Admin') ) class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) user_type = models.PositiveIntegerField(choices=user_type_choices) phone = models.PositiveBigIntegerField() After this model was created , I did the required changes to the settings.py file in the main app of the project by adding the "Users" app to the list of installed apps and adding the following line : AUTH_USER_MODEL = 'Users.CustomUser' Is my approach for creating custom user … -
Django channels doesn't work properly with production environment
i have a really big problem with channels. when I try to run asgi server in production the problems come up but there is no problem when running in terminal. first let me show you a little code class LogConsumer(AsyncConsumer): async def websocket_connect(self, event): print('befor') await self.send({ "type": "websocket.accept", "text": "hellow" }) print('after') async def websocket_disconnect(self, event): print(event) there are more but i commented them too see problem is solving or not and guess what ... application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^ws/monitoring/$", LogConsumer), ] ) ), ) }) ASGI_APPLICATION = "fradmin_mainserver.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } ASGI_THREADS = 1000 supervisor config [fcgi-program:asgi] socket=tcp://localhost:8008 environment=PYTHONPATH=/home/datis/.pyenv/versions/cv/bin/python User=datis environment=HOME="/home/datis",USER="datis" # Directory where your site's project files are located directory=/home/datis/PycharmProjects/fradmin_mainserver/ # Each process needs to have a separate socket file, so we use process_num # Make sure to update "django_chanels.asgi" to match your project name command=/home/datis/.pyenv/versions/cv/bin/daphne -u /run/uwsgi/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers fradmin_mainserver.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=1 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # … -
How can I access my graphql endpoint with authentication implemented using graphene_django_crud?
I want my api to be accessible by only authenticated user, So, I used **views.py** class PrivateGraphQLView(LoginRequiredMixin, GraphQLView): pass **urls.py** from users.views import PrivateGraphQLView from users.views import activate_account,password_reset from graphene_django.views import GraphQLView urlpatterns = [ path('admin/', admin.site.urls), path('api/',PrivateGraphQLView.as_view(graphiql=True)), But now I am not able to login , which seems reasonable since I put my endpoints in the LoginRequiredMixin. What I thought to make two endpoints but which is also not possible. What should I do, so that it won't be accessible to unauthenticated user and also able to do the login. I also tried schema.py from graphene_django_crud.types import DjangoGrapheneCRUD from graphene_permissions.mixins import AuthNode class ItemType(AuthNode,DjangoGrapheneCRUD): permission_classes = (AllowAuthenticated,) class Meta: model = Item max_limit = 10 but then I am able to access Item query being unauthorized user -
ModelViewSet multiple databases put get post serializer.is_valid
I use multiple databases. Branch.objects.using (db_name) .update (** validated_data) also updates this way, but I have to do "serializer.is_valid(raise_exception=True)". It constantly returns valid errors from the default database. How do I mount ModelViewSet put get and post "using(db)". Can you help me? I'm sorry for my bad english. class BranchViewSet(viewsets.ModelViewSet): queryset = Branch.objects.all() serializer_class = BranchSerializer def get_queryset(self): company_db = self.request.GET.get('company-db', False) db_name = self.request.GET.get('db-name', False) if db_name and company_db : queryset = Branch.objects.using(db_name).filter(company_db=company_db) else: queryset = Branch.objects.none() return queryset def update(self, request, *args, **kwargs): request.data._mutable = True instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) # is_valid().using("self.request.GET.get('db-name')") < does it check from the second database here? self.perform_update(serializer) return Response(serializer.data) -
Django - return each model value without field
The Priority model has three values, for each of them values I'm returning an inlineform which allows the user to set a score for each priority & then save with the Project. This is what it currently looks like: Current view My problem is: how can I automatically show all the priority values and allow the user to enter the score but not have to pick the Priority. Is it possible to show it like the image below? What I'm trying to do. Views.py class ProjectCreateview(LoginRequiredMixin, CreateView): model = Project form_class = ProjectCreationForm login_url = "/login/" success_url = '/' def get_context_data(self, **kwargs): PriorityChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('project', 'priority', 'score'), can_delete=False, extra=Priority.objects.count(), ) data = super().get_context_data(**kwargs) if self.request.POST: data['priorities'] = PriorityChildFormset(self.request.POST) else: data['priorities'] = PriorityChildFormset() return data def form_valid(self, form): context = self.get_context_data() prioritycriteria = context["priorities"] form.instance.creator = self.request.user self.object = form.save() prioritycriteria.instance = self.object if prioritycriteria.is_valid(): prioritycriteria.save() return HttpResponseRedirect(self.get_success_url()) Models.py class Priority(models.Model): title = models.CharField(verbose_name="Priority Name", max_length=250) def __str__(self): return self.title class Project(models.Model): name = models.CharField(verbose_name="Name", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) creator = models.ForeignKey(User, on_delete=models.CASCADE) class ProjectPriority(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) priority = models.ForeignKey(Priority, on_delete=models.CASCADE) score = models.CharField(max_length=1000, choices=priority_choices) class Meta: verbose_name = "Priority" verbose_name_plural = "Priorities" Template <table … -
Why do you use Stack Overflow? [closed]
For a few weeks I've been busy working on a research of different forum-like websites. A few examples are; Quora, Stack Overflow and of course Reddit. You would help me out a lot if you could fill in this survey (takes 5 min most!) in which I would like your opinion and usage of this platform; Stack Overflow. Your submission will be highly appreciated. PS: I'm sorry for the misusage of this platform, but this is the best way to reach the actual users. https://docs.google.com/forms/d/e/1FAIpQLSeI9ipMOUEmruvpGTFIId9Xgx1f-J-R8lKGoECMDWjPIfENcA/viewform?usp=sf_link -
How to make custom and dynamic forms in django?
i want to make custom and dynamic rendered forms in django , Like i have data , { 'members': [ { 'id': 621, 'name': 'abcd abc', 'relation': 'self', 'dob': datetime.date(1999, 4, 13), 'blood_group': 'A+ve', 'gender': 'male', 'height': 123.0, 'weight': 70.0, 'bmi': 46.27, 'ped': <QuerySet[ ]> }, { 'id': 622, 'name': 'acbd abc', 'relation': 'spouse', 'dob': datetime.date(1999, 4, 13), 'blood_group': 'B+ve', 'gender': 'female', 'height': 123.0, 'weight': 70.0, 'bmi': 46.27, 'ped': <QuerySet[ ]> }, { 'id': 625, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ ]> }, { 'id': 626, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ ]> }, { 'id': 627, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ ]> }, { 'id': 628, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ ]> }, { 'id': 629, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ …