Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use finished Templates
i have a question. Im working on a Project and i finished the Logic Part. So this was my first Project with Django and Web in generell. And my .html files are really really bad! So, now i want to change this. Work with a new Template and rework this a bit. The first "base.html" was from W3Schools and now i want to use a bootstrap Theme. The Question is, how can i import the Files? So i know that i have to put css,js Files into my static Folder and then import them into my base.html. The Thing now is, that i have much Folders and Files. I have a css, img, js, scss and vendor Folder and some Files like package.json, gulpfile.js and stuff like that. In these Folders are files like .css or .min.css, .js and .min.js, much scss Files and in the Vendor File are even more Folders with Files! So the question now is, how can i import this good? That i dont destroy anything, which File should be in css, js and ?scss? dont know if i need a file for this in django! And how can i import them correct? Maybe anyone has … -
How to access data from django all-auth?
I want to create a portal application that runs in django, i used django allauth to get registration and login done, the problem is that how to add extra field in django allauth and how to relate in user details with other models Example: There are two type account holders, (Individual / Business). A person comes signup and choose Individual and how to recognize who is who( Individual/Business). Thanks in advance -
using re.sub for a substring which is stripped from spaces to convert it into html tags
My code aims to find substrings which start by hash sign, check whether they exist in database, and if so convert them into tags. Basically I want users to be able to referance to titles in their entries. The code is: def prettytext(content): c = content if "#" not in content and "@" not in content and "|" not in content: c={"content":content,"safe":0} return c else: if not bool(BeautifulSoup(content,"html.parser").find()): if "#" in content: baslik= re.findall(r"[#]([^#@$\\|]*)(?=[#@$\\|]|$)", content) baslik= list(set(baslik)) baslik.sort(key=len,reverse=True) for i in baslik: try: title= Title.objects.get(title = i) c = re.sub("[#]({})(?=[#@$\\|]|$)".format(i,),"<a class='title-link' href='/titles/{}--{}'>{} </a> ".format(i,title.id,i),c) print(c) except: if " " in i: j = i.rstrip() try: c = re.sub("[#]('{}')(?=[#@$\\|]|$)".format(i,),"<a class='title-link' href='/titles/{}--{}'>{} </a> ".format(j,title.id,i),c) except: pass Let's say my database has the value "title5" and the string is "#title5 #title5" the result is: print(prettytext("#title5 #title5")) {'content': "#title5 <a class='title-link' href='/titles/title5--5'>title5 </a> ", 'safe': 1} but it is supposed to be: {'content': "<a class='title-link' href='/titles/title5--5'>title5 </a> <a class='title-link' href='/titles/title5--5'>title5 </a> ", 'safe': 1} So at first, the code gets all the substrings as a set then sorts them by length from longest to shortest and it starts to check them. The reason why I wanted it to be sorted is because one substring … -
Conditional in a Django Model Field Type for blank=True
I want to add if the voltage value is selected in the value_needed field, then the voltage field can be null but if it is not selected it should not be null and so on for the remaining fields if they are selected in the value_needed field then null=True thanks class Ohms(models.Model): value_needed_choices = ( ('voltage', 'Voltage'), ('current', 'Current'), ('resistance', 'Resistance') ) value_needed = models.CharField(choices = value_needed_choices, max_length = 20, default = 'voltage') voltage = models.IntegerField() current = models.IntegerField() resistance = models.IntegerField() -
I was unable to combine 2 query_set of same model without apply ordering in Django?
I was working on a project and I came across a problem. I need a query_set which should have ordering according to created date but there are some items in the query_set which I need to place at the end of the query_set at all times. I don't need to apply ordering for those items. Those items should be always at the end of the query_set Here is my model class Bookings(model.Model): booking_title = models.CharField('Booking title', max_length=125, blank=True, null=True) user = models.ForeignKey(User, related_name='request_user', on_delete=models.CASCADE) practice = models.BooleanField(default=False) status = models.IntegerField(choices=[1, 2], default=1) created_date = models.DateTimeField(auto_now_add=True) Here is my query_set query_set = Bookings.objects.filter(status=1) Here is my solution (Which is don't work) query_set_practice = query_set.filter(practice=True) query_set_normal = query_set.filter(practice=False).order_by('created_date') query_set = query_set_normal | query_set_practice I need normal bookings first and practice bookings. The normal bookings should be in the order (last should be first). I need an optimized solution without adding any loops and multiple query_set creations. Please help me. -
How to Animate <tr> using slideDown() Jquery
I have used the below code in my Django template, which prints the song title and a download button in a . (PS: "songs" is an array of song, that is coming from a Django view ) I want to apply animation to every row , that is printed. I have heard of slideDown() in jquery, but don't know how to use it. {% if songs %} <table class="table text-justify" style="margin-left:0px;"> <tbody> {% for song in songs %} <tr> <td>{{song.title}}</td> <td><a class="btn btn-block btn-success" href="/search/search/?song_id={{song.id}}">Download</a></td> </tr> {% endfor %} </tbody> </table> {% endif %} {% if ERROR %} <div class="alert alert-danger" role="alert"> {{ERROR}} </div> {% endif %} I tried the following : (but didn't work ) {% if songs %} <script> $('tr').slideDown(); </script> <table class="table text-justify" style="margin-left:0px;"> <tbody> {% for song in songs %} <tr> <td>{{song.title}}</td> <td><a class="btn btn-block btn-success" href="/search/search/?song_id={{song.id}}">Download</a></td> </tr> {% endfor %} </tbody> </table> {% endif %} {% if ERROR %} <div class="alert alert-danger" role="alert"> {{ERROR}} </div> {% endif %} Also, "songs" array is calculated after submitting a form, using a post method. Please help. -
Setting a new user inactive based on group -- Django
I am currently busy with my user app and trying to achieve a way to add new users to different pre-defined groups. My sign_up view for one of the groups is as follows: def signup_view_zakelijk(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name='zakelijk') user.groups.add(group) return redirect('user:login') return render(request, 'user/signup.html', {'form': form}) else: form = UserCreationForm() return render(request, 'user/signup.html', {'form': form}) The group is assigned after the save form.save so i made a post_save signal: @receiver(post_save, sender=User) def user_zakelijk_inactive(sender, instance, **kwargs): group = Group.objects.values_list('name', flat=True) print(group) if group == 'zakelijk': if instance._state.adding is True: instance.is_active = False else: return else: return I've set the print statement to check if the user group names got printed and this works. But the new added user is not inactive by default. When I erase the if group == 'zakelijk' conditional the signal works properly but is also executed for other user groups (so every new user is inactive by default - only need this for the group 'zakelijk'. The Signal code that works properly: @receiver(pre_save, sender=User) def user_zakelijk_inactive(sender, instance, **kwargs): if instance._state.adding is True: instance.is_active = False else: return Does anyone have some ideas to addin the … -
Ajax data shown on table but not appending
i am trying to update my table without refreshing the page is my firsttime using ajax so i tried to do it, it shown on the console logs(the data i collect it) but the problem is that the data i got won't appending to my main table can anyone help me? here is my dashboard.html where i want to update the table {% load staticfiles %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <table id="_appendHere" class="table table-striped table-condensed"> <tr> <th>name</th> <th>desc</th> <th>status</th> <th>price</th> </tr> {% for i in dest %} <td>{{ i.name|upper }}</td> <td>{{ i.desc|capfirst }}</td> <td>{{ i.status|capfirst }}</td> <td>{{ i.price | capfirst}}</td> </tr> {% endfor %} </table> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script> <script> function updateTable(){ console.log("hello") $.ajax({ method: "GET", url: "get_more_table", success: function(data) { console.log(data) $("#_appendHere").append(data); } }) } var interval = setInterval(function () { updateTable(); }, 10000); </script> </body> </html> view def record_table(request): dest = Destination.objects.all() return render(request,"destination.html",{'dest':dest}) def get_more_table(request): <--- my callback table dest = Destination.objects.all() return render(request,"get_more_table.html",{'dest':dest}) get_more_table.html {% for i in dest %} <td>{{ i.name|upper }}</td> <td>{{ i.desc|capfirst }}</td> <td>{{ i.status|capfirst }}</td> <td>{{ i.price … -
How to mimic upload_to function in models with ordinary form
Hi I'm having this models, forms, views, settings let say models.py class ProfileModel(models.Model): user = Foreignkey(get_user_model()...) first_name = forms.CharField(....) # some attrs photo = models.ImageField(uploads_to='uploads/%Y/%m/%d', ...) forms.py class ProfileForm(forms.Form): first_name = forms.CharField() photo = forms.ImageField() def handle(self, request, *args, **kwargs): data = self.cleaned_data # update the profile model Profile.objects.filter(user__exact=request.user, **data) views.py def update_profile(request): if request.method == 'POST': form = forms.ProfileForm(request.DATA, request.FILES) if form.is_valid(): # update here via handle of form form.handle(request, *args, **kwargs) else: #... something settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Please bare with me its a hybrid or bizzare in any case. The idea here is just use a form to update a model (not a modelform). via admin, upload_to seems to work e.g upload a picture, url = /media/uploads/..../photo when its comes to my form it just recognizes /media/ but not the upload_to, [btw its working its just that its behavior] e.g upload a picture, url = /media/photo it seems its not triggering the upload_to, I know the benefit of the modelform but in this case, is there a way? so anyone can help me much appreciated. Thank you for the help. -
Make Django and ReactJS friends. Authorization. Routing
I'm developing a Shopify App. I'm using Django for backend and React for frontend. I chose React because I want to use React Shopify Polaris components. I want to be able to have different pages (Settings, Dashboard, Statistics and so on). On the pages, I want to display some information retrieved from the server and processed by React. I don't know how to make them work together. I've seen a tutorials where people use React and Redux for all the logic and routing, Django-Rest-Framework for the server. I wanted to do the same. I faced the problem of authorization. It's done now with Django this way: https://github.com/Shopify/shopify_django_app/blob/master/shopify_app/views.py As a result, we have access_token variable inside request.session. We can check if user added the shop by the presence of this variable. Also after this process, we have our shopify.Shopify.session set. I don't know how to work this out with React. How to check in React if user added the shop (if is authenticated)? How to manage routing correctly? Which way do I have to use Django-React pair to achieve my goal? Maybe there are other ways of using Django and React together. -
How to integrate React-Django without REST API
I am new to web development I want to create an application using react and django but all tutorials show that by using REST API. is there a way to use Django and react without REST API and perform CURD. -
my django project database will take thousands of data to populate the table, how am I to do it?
I am working on a django project and I have created the database but I am having difficulty populating the database with data. my database has 6 tables and I am to input data of over 2 two thousand. I asked a friend who told me to create python scripts and run it to input the data in the database. How do i write a python script? or is there another way to populate the database. -
how to show a blog according to category and the list of category in html template?
i am trying to make site with django and want to category for each post and a category list. in the category list every category name will be listed and linked to the posts according to their category. here is my models.py: class Category(models.Model): name=models.CharField(max_length=1000,null=True) def __str__(self): return self.name class Post(models.Model): title=models.CharField(max_length=200,blank=True,null=True) author=models.ForeignKey(get_user_model(),on_delete=models.CASCADE,null=True) body=RichTextField(blank=True,null=True) image=models.FileField(upload_to="mediaphoto") topImage=ImageSpecField(source='image',processors=[ResizeToFill(750,300)],format='PNG',options={'quality':60}) date=models.DateField(default=datetime.now, blank=True) category = models.ForeignKey(Category,on_delete=models.CASCADE,verbose_name="Categories") def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail',args={str(self.id)}) here is my views.py: def Categorylist(request): categories = Category.objects.all() return render (request, 'category_list.html', {'categories': categories}) def CategoryDetail(request,pk): category = get_object_or_404(Category, pk=pk) return render(request, 'post_category.html', {'category': category}) here is my urls.py: urlpatterns = [ path('post/<int:pk>/delete/',BlogappDeleteView.as_view(),name='post_delete'), path('post/<int:pk>/edit/',BlogappUpdateView.as_view(),name='post_edit'), path('post/new/', BlogappCreateview.as_view(),name='post_new'), path('post/<int:pk>/',BlogappPostView.as_view(),name='post_detail'), path('post/<int:pk>/category', views.CategoryDetail, name='category'), path('search',views.Search,name='search'), path('',BlogappListView.as_view(),name='home'), ] here is post_category.html <h3>{{ category.name }} Category</h3> {% for category in object_list %} <h2 class="card-title">{{post.title}}</h2> <p class="card-text">{{post.description|truncatechars:400|safe}}</p> <a href="{% url 'post_detail' post.pk %}" class="btn btn-primary">Read More &rarr;</a> Posted on {{post.date|safe}} by <a href="/">{{post.author}}</a> in <a href="/">{{post.category}}</a> {% endfor %} here is category_list.html: {% for list in Category %} <li> <a href="{% url 'category' post.pk %}">{{list.name}}</a> </li> {% endfor %} main problem is that category list is not fetching any list from the Category name and when click on the category in a post below, it is not … -
How do I protect secret data in database by Django?
I make an application. Services: Django application, on-premises. Started as a separate Docker container. PostgreSQL for this Django. Also started as a separate Docker container. Workflow: Django get's some secret data via REST API. Encrypts with AES. Saves encrypted data into PostgreSQL database. Problem: Anybody who has an access to Django container (or its backups) can take key/vector and decrypt data stored in PostgreSQL. Question: How do I protect key/vector from access of anybody but keep it resilient between upgrades of Docker container? -
Django: Page not found (404), Request URL: http://127.0.0.1:8000/Loader/confirm_booking/17 Raised by: Loader.views.booking_approve
working on a project where the user approves the post and then click on the button the post should be approved by the user ...however, while clicking its shows an error like this. this is model of booking class Booking(models.Model): order_id = models.AutoField(primary_key= True,default='1') b_price = models.ForeignKey(price, on_delete=models.CASCADE, related_name='b_prices',default='') b_post = models.ForeignKey(Loader_post, on_delete=models.CASCADE, related_name='b_posts',default='') booked_at = models.DateField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') approved_price = models.BooleanField(default=False) this is my views.py def booking_approve(request,pk): booking = get_object_or_404(Booking, pk=pk) booking.save() booking.approve() return redirect('Loader:post', pk=pk) this is my HTML of approval and rejection page where user can reject the offer and approve when it click on approve button the post , user, driver all detail should save onto database and it's not working. {% for loader_post in request.user.Loader.all %} {% for price in loader_post.prices.all %} <div class="card" style="margin-right: 30%; width: 22%; margin-bottom: 5%; text-align: left;"> <div class="container"> <img src="{{loader_post.image_of_load.url }}" alt="Avatar" style="width:100%; height: 25%; margin-bottom: 10px; "> <h4><b>Post id : {{loader_post.id }}</b></h4> <p>Driver offer : <i class="fa fa-inr" aria-hidden="true"></i>{{price.driver_price }}</p> <p>Offer by : {{price.driver_name }}</p> <a style="margin-right:20px;" href="{% url 'Loader:booking_remove' pk=price.pk %}"><i class="fa fa-times fa-4x" style="color: red;" aria-hidden="true"></i></a> <a href="{% url 'Loader:booking_approve' pk=price.pk %}"><i class="fa fa-check-circle fa-4x" aria-hidden="true"></i></a> </div> -
deploying django app using heroku, but No module Found error persist
I am trying to deploy Django app using Heroku, but Heroku keeps giving me No module found error. Below are my codes and errors. this is my project structure: . ├── Procfile ├── db.sqlite3 ├── hello │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-37.pyc │ ├── models.py │ ├── static │ │ └── hello │ │ └── css │ │ └── style.css │ ├── templates │ │ └── hello │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── requirements.txt ├── runtime.txt └── test_app ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-37.pyc │ ├── local_settings.cpython-37.pyc │ ├── settings.cpython-37.pyc │ ├── urls.cpython-37.pyc │ └── wsgi.cpython-37.pyc ├── asgi.py ├── local_settings.py ├── settings.py ├── urls.py └── wsgi.py this is my Procfile: web: gunicorn test_app.wgi --log-file - error screen shots requirements.txt python path is this on heroku: PYTHONPATH:/app any help is appreciated! -
ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
I have a problem with migration with my Django project. I run in the command line python3 manage.py migrate For some reasons I got the error ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' But I have checked the psycopg2 installation and it seems that it is ok (myenv) (base) Elenas-MacBook-Air:myenv elenaorlova$ pip install psycopg2==2.7.5 DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release- process/#python-2-support Requirement already satisfied: psycopg2==2.7.5 in ./lib/python2.7/site-packages (2.7.5) Do you know what could be the reason of this problem? I already re-installed psycopg2 several times, including manual. Will be very thankful for any help! -
Calculating the hours between two 24 hour time formats
Views Let us Consider shift.start_time : 14:30 shift.end_time : 15:30 of same day. Actual time difference is 1 hours.But its showing 22 hours.But I need to get 1 hr. for shift in shift_bokings: if shift.start_time < shift.end_time: start = pendulum.instance(timezone.now()).start_of('day') end = start.end_of('day') print("SHIFT START AND END TIME",shift.start_time,shift.end_time) dateTime3 = datetime.datetime.combine(datetime.date.today(), shift.start_time) - datetime.datetime.combine(datetime.date.today(), shift.end_time) # dateTimeDifference = (dateTime3.total_seconds() /3600 ) # y = dateTimeDifference - shift.break_time print("DATETIME IS",dateTime3,end) else: dateTime3 = datetime.datetime.combine(datetime.date.today(), shift.end_time) - datetime.datetime.combine(datetime.date.today(), shift.start_time) print("DATETIME 3 IS",dateTime3) dateTimeDifferenceInHours = (dateTime3.seconds / 3600) work_time = dateTimeDifferenceInHours - shift.break_time print('WORK TIME',work_time) writer.writerow([shift.date, shift.worker_name, shift.shift_status, shift.location, shift.start_time, shift.end_time, shift.break_time, work_time]) return response -
Unable to import 'django.contrib'pylint(import-error)
I am trying to create my very first django project using VS Code editor. Here i created a virtual environment and activate that (by : pipenv shell). After that i created a project and an app. Unfortunately, i got an error in every import in every python module. How to i solve that problem. Python 3.8.2 Django 2.1 Unable to import 'django.contrib'pylint(import-error) Error -
Link html buttons to user registration form
My login forms are working properly but are not connected to the html button. The page with this button is on another url different from the accounts page. How do i link it with the app for accounts or folder containing my html forms. Is there a way of inheriting the app folder into this main folder or inporting just to have a link. -
import_data() missing 1 required positional argument: 'dataset' -
I have an issue when i want import data from an dataset with django import export user model ressource : error : import_data() missing 1 required positional argument: 'dataset' Request Method: GET Request URL: http://localhost:8000/home/ Django Version: 1.11.6 Exception Type: TypeError Exception Value: import_data() missing 1 required positional argument: 'dataset' Exception Location: /code/data_integration/tasks.py in MvmtjsHms, line 197 Python Executable: /usr/local/bin/python3 Python Version: 3.4.2 My ressource : class MasterDossierResource(resources.ModelResource): class Meta: model = MasterDossier skip_unchanged = True report_skipped = False import_id_fields = ('indice',) exclude = ('id',) fields = ('indice', 'plt', 'ref_dossier',) My model : class MasterDossier(models.Model): indice = models.CharField(max_length=40, primary_key=True) plt = models.CharField(max_length=3) ref_dossier = models.CharField(max_length=20) My code: I use an existing file for implemented my dataset depending to confitions, et i want to test dataset integration using ressource of my model def Mvmtjs(self,file, espace): import csv csvfile = open(file, 'r') reader = csv.reader(csvfile,delimiter=';') dataset = tablib.Dataset(headers=['indice', 'plt', 'ref_dossier_ath']) ] with open('tmp/edi/in/working/write_file.csv', "w+", encoding='mac_roman', newline='') as csv_file1: next(reader) # Skip header row. next(reader) # Skip header row. for row in reader: if row[2] != "": if espace == '1' or '2': dataset.append( ( row[2], row[0], row[2], )) result = MasterDossierResource.import_data(dataset, dry_run=True, raise_errors=True) thank you in advance -
Python log file/folder delete/modify/create on network map drive
I want to be able to see with python the following logging info live: Timestamp with which folder/files were accessed/deleted/created/modified Need to be able to put down a domain name to that action so I know who performed the action This will be on a network mapped drive on a server. I already have the logging info about the files/folders being modified/deleted/created etc. I'm struggling to be able to put the domain username of the person the performs that specific action. Anyone able to help out? Thanks in advance -
(Django) ForeignKey and Comment: Having a problem trying to save the username of the user who posts the comment
I have been trying to emulate the comment functionality of Instagram. the problem is that the 'username' key of each new comment only takes the user_id number instead of the actual username and I can't figure out a way to fix this despite all the documentation readings. Below are my codes. comment/views.py import json import jwt from django.views import View from django.http import JsonResponse from functools import wraps from django.db.models import Q from .models import Comment from account.models import Account def login_required(func): #@wraps(func) def wrapper(self, request, *args, **kwargs): given_token = json.loads(request.body)['access_token'] decoded_token = jwt.decode(given_token,'secret', algorithm='HS256')['username'] try: if Account.objects.filter(username=decoded_token).exists(): return func(self, request, *args, **kwargs) else: return JsonResponse({"message": "username does not exist"}) except KeyError: return JsonResponse({"message": "INVALID_KEYS"}, status=403) return wrapper class CommentView(View): @login_required def post(self, request): data = json.loads(request.body) given_token = json.loads(request.body)['access_token'] decoded_token = jwt.decode(given_token,'secret', algorithm='HS256')['username'] account = Account.objects.get(username=decoded_token) Comment.objects.create( username = account.username, content = data['content'], ) return JsonResponse({"message":"Comment Created!"}, status=200) def get(self, request): return JsonResponse({'comment':list(Comment.objects.values())}, status=200) account/models.py from django.db import models class Account(models.Model): email = models.EmailField(max_length = 254, null=True) password = models.CharField(max_length=700) fullname = models.CharField(max_length=200) username = models.CharField(max_length=200) phone = models.CharField(max_length=100, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'accounts' def __str__(self): return self.username + " " + … -
How to make a hierarchy "choices" in django?
Have model with 3 tuple(choices). How to display in forms.py or views.py choice according to choice. For example i chose CATEGORY - 1 SUB_CAT1 unlock, chose CATEGORY - 2 SUB_CAT2 unlock models.py class Category(models.Model): CATEGORY = ( ('1','1'), ('2','2'), ('3','3'), ) SUB_CAT1 = ( ('1','1'), ('2','2'), ('3','3'), ) SUB_CAT2 = ( ('1','1'), ('2','2'), ('3','3'), ) category_choices = models.CharField(max_length=1, choices=CATEGORY, default='1') sub_cat1_choices = models.CharField(max_length=1, choices=SUB_CAT1, default='0') sub_cat2_choices = models.CharField(max_length=1, choices=SUB_CAT2, default='0') forms.py class MyModelForm(forms.ModelForm): class Meta: model = Category fields = ['category_choices'] I need something like class MyModelForm(forms.ModelForm): class Meta: model = Category fields = ['category_choices'] class MySubModelForm(forms.ModelForm): class Meta: model = Category fields = '' if Category.category_choices == 1 fields = ['sub_cat1_choices'] elif Category.category_choices == 2 fields = ['sub_cat2_choices'] Then in template.html <form action="" method="post"> {% csrf_token %} {{ form.as_p }} </form> <form action="" method="post"> {{ sub_form.as_p }} <input type="submit" value="Create" /> </form> -
DRF Methodserializer : Object of type <XXX>is not JSON serializable
i am trying to convert my existing project to the DRF . However im facing the error of : : Object of type TransitionApproval is not JSON serializable TransitionApproval object comees from a package called django-river. Here is my code: class ProjectDetailSerializer(serializers.ModelSerializer): requirements = CustomerRequirementSerializer(many=True) transitionApproval = serializers.SerializerMethodField('get_transition_approval') class Meta: model = Project fields = '__all__' depth = 2 def get_transition_approval(self,project): transitions = TransitionApproval.objects.filter(object_id=project.pk).filter(workflow__field_name='project_status') print(transitions) return transitions My console prints : <CTEQuerySet [<TransitionApproval: TransitionApproval object (1)>, <TransitionApproval: TransitionApproval object (2)>, <TransitionApproval: TransitionApproval object (3)>]> Is there a good way to solve this? I have tried doing this : class ProjectDetailSerializer(serializers.ModelSerializer): requirements = CustomerRequirementSerializer(many=True) transitionApproval = TransitionSerializer(many=True) class Meta: model = Project fields = '__all__' depth = 2 but it seems that 'transitionApproval' is not an attribute of Project. Im not sure how to resolve this.