Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django signals in ManyToManyField
I have simply following model in my django project. It was created by adding to User (where User is imported from django.contrib.auth.models) below attribute. User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) I also added to User class another attribute for better ordering. User.add_to_class('total_followers', models.PositiveIntegerField(db_index=True, default=0)) I wrote the function to change total_followers attribute after changing in following attribute. In my signals.py i have : from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import m2m_changed @receiver(m2m_changed, sender=User.following.through) def users_follow_changed(sender, instance, **kwargs): instance.total_followers = instance.followers.count() instance.save() In shell I can manipulate total_followers attribute i.e: from django.contrib.auth.models import User for user in User.objects.all(): user.total_followers = user.followers.count() user.save() print(user.username) print(user.total_followers) and this return a right data. But when i add to some User another follower, number of total_followers does not change. This should be a problem in my users_follow_changed function but its does not inform me of an error. -
How to get image path from azure storage?
i am building an app using django and django rest framework , in views.py i need to get image path of a patient to analyse the image.When i working in locally 'instance.path' works fine but when i deploy the app to azure then it doesnt get the image path by instance.py method & showing an error 'this backend doesnt have any absolute path' , so i changed to MEDIA_ROOT + instance.name for image path ,It get the working link from azure storage perfectly but showing that no such file or directory. Views.py: class PatientImagePrediction(viewsets.ModelViewSet): serializer_class = PatientImageSerializer def get_queryset(self,pk=None): queryset = PatientImage.objects.all() pk = self.kwargs.get('pk') print("Primary ky is " , pk) if pk is not None: queryset = PatientImage.objects.filter(pk=pk) instance = PatientImage.objects.get(pk=pk); print("Image 1:",instance.Image1) if instance.Image1: image1_full_path = MEDIA_URL + instance.Image1.name print("image 1 " , image1_full_path) -
How to call django class based view get function from normal function?
I want to get a response of get function present inside class-based view. So I have written a small function outside the scope of a class. How to pass a URL to this get function or how to call this function directly in order to get its response? Sample code: class Get_data(APIView): def get(self, request): username = request.GET.get('username') # Processing Code # response_data = {'status': 'SUCCESS', 'data': XYZ} return Response(response_data, status=status.HTTP_200_OK) def fetch_value(): # Code to get response data from GET function of class Get_data # So what should be the code inside the function fetch_value in order to get response data from GET function of class Get_data? -
How do I select distinct from the Django model
If only address and address_detail variables are the same among model variables, I want to remove duplicates. How should I use select distinct address, address_detail? class Information(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) address = models.CharField(max_length=200) address_detail = models.CharField(blank=True, max_length=100) zipcode = models.CharField(max_length=50) email = models.EmailField(blank=True) created_at = models.DateTimeField(auto_now_add=True) (table) user, my address, my address detail, 11122, myemail@email.com user, my address, my address detail, 12345, test@email.com user, my address, my address detail, 22211, example@email.com (result) user, my address, my address detail, 11122, myemail@email.com -
Obtaiing values from Mysql tables in django
I am new to Mysql and connecting to Django. This is for learning purpose and i selected a school project as an example. I connected my database to django. I want to enable user (teacher) insert the name of a student and get test results on certain subjects. I run python3 manage.py inspectdb and inserted it into models.py class Profilez(models.Model): student = models.CharField(max_length=255) schgroup = models.CharField(max_length=255) class Meta: managed = False db_table = 'profilez' class Schoolz(models.Model): profilez_id = models.AutoField(primary_key=True) lit = models.IntegerField(blank=True, null=True) math = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'schoolz' in forms.py i put: class StudentForm(forms.ModelForm): SUB = ( ('lit', 'lit'), ('math', 'math') ) student = forms.CharField(max_length=150, label='', widget=forms.TextInput) class Meta: model = Schoolz fields = ('student',) in views.py: def home(request): if request.method == "POST": form = StudentForm(request.POST) if form.is_valid(): form1 = form.save(commit=True) name = form1.student ab=schoolz.objects.all() context={ 'name':name, } return render(request, 'book/analysis.html', context) else: form = StudentForm() return render(request, 'book/search.html', {'form': form}) Can you please help me to understand what i am doing wrong and how to get value for certain subject for exmaple math subject. I would appreciate any help and guidance to undertand and execute it. I am struggling a month. -
Render a django form in multiple templates of different view class and function
I want to render the form in the the template of mydetails class i.e. details_detail.html views.py class mydetails(generic.DetailView): model = details def get_context_data(self, **kwargs): context = super(ads_detail_vis, self).get_context_data(**kwargs) context['test'] = Type_details.objects.all() return context def formView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): {some code} return redirect('success') return render(request, "my_app/form.html", {'form': form}) details_detail.html <html> some code context from mydetails class... {% csrf_token %} {{ form }} </html> -
django in docker not detecting SIGINT
This is a funny stackover flow question, because I have an answer, but the answer is a few years old. I can't find much content which is new, yet it seems like it would be quite high profile. I am using docker-compose to start a few containers. Two of them use standard postgres and redis images. The others are django 2.2.9 (and celery) This is a development environment, and I start them with docker compose, like this: command: ./manage.py runserver 0.0.0.0:80 docker-compose stop sends a SIGINT. The redis and postgres containers exit quickly. the django containers don't. docker-compose stop loses patience and kills them. (and pycharm has infinite patience currently, and doesn't send a kill until I force it). This post from 2015 referring to Django 1.9 (http://blog.lotech.org/fix-djangos-runserver-when-run-under-docker-or-pycharm.html) says that "The quick fix is to specifically listen for SIGINT and SIGTERM in your manage.py, and sys.kill() when you get them. So modify your manage.py to add a signal handler:" and it says how. The fix to change manage.py to catch SIGINT works and it's a handful of lines, although it doesn't work for celery which has its own startup. So I can carry forward my own version of of manage.py … -
after updating form in django it create new instance of the form instead of updating it
i haven't been able to correct the code and it doesn't work just inserting the question in database after every update. Here's the view code views.py #form for creating question def get_name(request): if request.method=='POST': form = QuestionForm(request.POST) if form.is_valid(): instance = form.save() return HttpResponseRedirect(reverse('poll:index')) else: form = QuestionForm() return render(request,'poll/name.html',{'form':form}) #for updating the form def update(request,question_id=None): if question_id: instance=get_object_or_404(Question,pk=question_id) else: instance=None if request.method=='POST': form = QuestionForm(request.POST,instance=instance) if form.is_valid(): instance=form.save(commit=False) instance.save() return HttpResponseRedirect(instance.get_absolute_url()) else: form=QuestionForm(instance=instance) return render(request,'poll/name.html',{'form':form}) -
Update if "Email already exist" in Django Rest Framework
I have a Candidates object model in Django Application, who I get from a form in a Front End. If this Candidate send personal data again with the same email, DRF response {"email":["A user with that email already exists."]} and not save the form. The idea is, if this candidate send the form again with personal email and I have saved it in my database, I will update personal data of this candidate. I tried with: My view: @csrf_exempt @api_view(['GET', 'POST','PATCH']) def CandidatesCreate(request, *args, **kwargs): parser_classes = (FileUploadParser,) if request.method == 'PATCH' or request.method == 'POST': serializer = CandidatesSerializer(data=request.data) if serializer.is_valid(): instance, created = serializer.get_or_create() if not created: serializer.update(instance, serializer.validated_data) return Response(serializer.data, status=status.HTTP_202_ACCEPTED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My Serializer class CandidatesSerializer(serializers.ModelSerializer): cv = serializers.FileField(required=False,max_length=None, use_url=True) class Meta: model = Candidates fields = ( 'pk', 'user', 'name', 'email', 'whatever', 'whatever' ) However, it not working.I am not be sure if get_or_create() was depreciated, to be honest. I not found real information about it. -
Unable to pass list to the SQL query in python
Am using the code bellow:: def GetDetails(request): try: year='' month=[] results=[] conn = connections["connection1"] cursor = conn.cursor() year = request.GET.get('year') print(year) month = request.GET.getlist('month[]') response_list = [] query = (" select Year,month,student_name,admission_date,class from admission_table\ where MONTH(admission_date) in (' + ','.join(map(str, month)) + ') AND YEAR(admission_date) in ('"+year+"') AND class in ('"+class+"')") cursor.execute(query,month) rows = cursor.fetchall() print(rows) if rows: for row in rows: response_list.append({'year':row[0],'month':row[1],'student_name':row[2],'admission_date':str(row[3]),'class':row[4]}) except Exception as e: print(str(e)) return HttpResponse(json.dumps(response_list)) The error am getting is: ('22018', "[22018] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the varchar value '.join(map(str,month)) + ' to data type int. (245) (SQLExecDirectW)") The month variable has the value : ['01', '02', '03'] How can I achieve this ? Please help! Thanks for time and help in advance! I would appreciate the help! -
using set instead of list in django and checking the id with each id in the list
def user(request): users_list = UserConfig.objects.get(meta_key="ALLOWED_USERS") users_list = [int(x) for x in user_list.meta_value.split(",")] if request.user.id not in users_list: // some logic else: // other logic How can i convert the above snippet by using of a set, currently i am using list to check. So if the Object gets more then it won't be a efficient way. Using Django 1.8 Any help is appreciated -
Django: Update multiple fields at once
I am fairly new to Django, but it's fun. I built a table with billing information. Let's say I have table structure like this: id, date, price, money received, and so on. Now, once in a while, I would like to update that table, because everything may have been filled in except for the receipt of the purchase price. Therefore I thought it to be cool to generate a html table with all the entries from the db table in it. Then in the last column there could be input fields so that I could fill in whether there was a payment or not. But I do not want to make separate entries for each bill. Instead it would be cool, just to fill in the last column at once and the just to click a button "update". And then all the fields in the db should get an update about the payment. But generic views like UpdateView seem to only apply to single objects (or data rows if this is a better name for it). Could you give me an advice how to get such an update table in Django? Best regards -
django dict to excel, httpresponse to download excel file
I have a dictionary: a = {'name0': [1, 2, 3], 'name1': [4, 5, 6]} how can I download this data as xlsx file via Django framework and httpresponse? -
celery with django error when doing a db query via task: DatabaseWrapper objects created in a thread can only be used in that same thread
Stack: Django 3.0.2 python 3.8.1 celery 4.4.0 redis 3.2.0 command to start celery: celery -A app_project worker -l info I am using celery to run background tasks in my django project. On development machine it was running perfectly without any error. Both development and production are running on the same stack; I have checked and matched them manually. Yet, still I am facing this issue. Problem: Celery is throwing the below error when trying to do a query on the database. Traceback (most recent call last): File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/celery/app/trace.py", line 385, in trace_task R = retval = fun(*args, **kwargs) File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/celery/app/trace.py", line 650, in __protected_call__ return self.run(*args, **kwargs) File "/webapps/app/backend/app/tasks.py", line 22, in task_assign_photo_to_dish if dishq.exists(): File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/django/db/models/query.py", line 777, in exists return self.query.has_results(using=self.db) File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 537, in has_results return compiler.has_results() File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1114, in has_results return bool(self.execute_sql(SINGLE)) File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor = self.connection.cursor() File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 238, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 228, in _prepare_cursor self.validate_thread_sharing() File "/webapps/app/.virtualenvs/base38/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 553, in validate_thread_sharing raise DatabaseError( django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in … -
How to use field.set() in create function for Django REST Framework ModelSerializer?
I have an intermediate model called RoomMarket connecting 2 related models. Market - RoomMarket - Room. When I tried to insert a record for RoomMarket using writable nested serializer I got an error: TypeError at /room_markets/ Direct assignment to the forward side of a many-to-many set is prohibited. Use regions.set() instead. Here's my simplified models.py: class RecordStatus: published = 'Published' drafted = 'Drafted' hidden = 'Hidden' status = [ (published, 'Published'), (drafted, 'Drafted'), (hidden, 'Hidden'), ] class Market(models.Model, RecordStatus): name = models.CharField(max_length=100) regions = models.ManyToManyField(Region) languages = models.ManyToManyField(Language) status = models.CharField(max_length=20, choices=RecordStatus.status, default=RecordStatus.published) @property def get_product_variations(self): return Product.objects.filter(distributor__region__market=self).distinct().count() class Room(models.Model, RecordStatus): style = models.ForeignKey(Style, on_delete=models.CASCADE) markets = models.ManyToManyField(Market, through='RoomMarket') image = models.ImageField(upload_to='room_images', width_field=None, height_field=None, max_length=250, null=True, blank=True) name = models.CharField(max_length=50) status = models.CharField(max_length=20, choices=RecordStatus.status, default=RecordStatus.published) class RoomMarket(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) landing_page = models.BooleanField(blank=True, null=True) def __str__(self): return '%s - %s' % (self.market, self.room) Here's my serializers.py: class CustomRelatedField(serializers.RelatedField): def display_value(self, instance): return instance def to_representation(self, value): return str(value) def to_internal_value(self, data): model = self.queryset.model return model.objects.get(id=data) class MarketSerializer(serializers.ModelSerializer): regions = CustomRelatedField(many=True, queryset=Region.objects.all()) languages = CustomRelatedField(many=True, queryset=Language.objects.all()) variation = serializers.ReadOnlyField(source='get_product_variations') landing_page = serializers.SerializerMethodField(source='get_landing_page') class Meta: model = Market fields = ['id', 'regions', 'languages', 'name', 'status', 'variation', … -
Database error in django while running local sever?
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Getting this error even installed the mysqlclient python version:Python 3.6.9 -
How Postgres save data?
I have django-project where i have model: class Example(models.Model): title = models.CharFied(blank=False, null=False) I have a form associated with class Example, where input "title" is not required. How postgres can save this empty data? I am afraid that I will have a lot of errors in future. -
Authentication in Django is_authenticated
is_authenticated¶ Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn’t check if the user is active or has a valid session. Even though normally you will check this attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User instance. from django.conf import settings from django.shortcuts import redirect def my_view(request): if not request.user.is_authenticated: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) is_authenticated says that it doesn't check whether a user has a valid session, isn't that technically false because on each request the Session table is checked against the client session cookie and only returns a User if there is a match? Otherwise you wouldnt be able to return a User if the client doesnt not send authentication details like username, password? -
Django:error on form field validation int() / str
I develop a Django app and have an error when submit an update form and I do not understand my form update a model Sortie (below) and error occur with asp_sor_pre variable (integer): ValueError: invalid literal for int() with base 10: '' Below the trace of the error raised by Django my problem is that I am not sure which field raise this error... I have identified one scenarii that raise this error: when database instance is: med_num : AAA asp_sor_dat : 2020-02-01 asp_sor_typ : 2 asp_sor_pre : null pat : null asp_sor_des : TR asp_sor_loc : CR opr_nom : admin opr_dat : 2020-02-01 and I try to update with: med_num : AAA asp_sor_dat : 2020-02-01 asp_sor_typ : 3 ********* asp_sor_pre : null pat : patient1 ********* asp_sor_des : null ********* asp_sor_loc : CR opr_nom : admin opr_dat : 2020-02-01 error should be link with one of the 4 fields: asp_sor_typ, asp_sor_pre, pat, asp_sor_des before submission, asp_sor_pre is NoneType and when I submit the form, it is a String type which raise the error... I do not understand how/why it becomes a string...? the form field asp_sor_pre is a ChoiceField with choices=REASON REASONS is a list of tuples extracted from … -
Slow loading of lazy loaded elements with Django EL(Endless) Pagination
I've implemented a Twitter-style on-scroll lazy pagination in my django App using Django EL(Endless) Pagination. Everything seems to work fine but the loading of new elements is very slow (more than 5 sec on a queryset that contains 5000 entries). Is there anything I can do to improve loading time? My views.py def articles_list(request, template='articles_list.html', page_template='articles.html'): qs = Article.objects.all().order_by('fb_total_engagement_count') qs.delete() form = ArticlesSearchForm(request.GET or None) if form.is_valid(): api = services.Session() search_result = api.search(form.cleaned_data['q']) if not search_result['success']: form.add_error('q', search_result['message']) else: objs = [Article(**art) for art in search_result['articles']] Article.objects.bulk_create(objs) context = { 'search_result': qs, 'page_template': page_template, 'total_interactions': qs.aggregate(Sum('fb_total_engagement_count')), 'form': form } if request.is_ajax(): template = page_template return render(request, template, context) Part of articles_list.html: <div class="row endless_content_wrapper"> {% lazy_paginate search_result %} {% include page_template %} </div> <div class="row"> <div class="col text-center"> {% show_more %} </div> </div> Part of articles.html: {% if request.is_ajax %}{% lazy_paginate search_result %}{% endif %} {% for article in search_result %} ...do stuffs {% endfor %} -
Cannot access admin site in django with custom user
I have a problem with django, I cannot login to admin site, the app just stops when I try to login to admin but everything is fine if I try to login user to site, just cant access admin. I've read all articles about it on the stackoverflow, I tried different AUTH_BACKENDS and none of them works. I'm really desperate So, this is my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'untitled.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'untitled.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mentor', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' AUTH_USER_MODEL = "users.CustomUser" LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.RemoteUserBackend' ) … -
__str returned non-string (type NoneType)
while opening my admin pannel and clicking on add_model category getting an str returned non-string (type NoneType) error(while opening admin pannel) # my model class add_model(models.Model): select_category = models.ForeignKey( "add_category", on_delete=models.CASCADE, related_name="select_category", ) select_sub_category = models.ForeignKey( "sub_category", on_delete=models.CASCADE, related_name="select_sub_category", ) available_in = models.ForeignKey( "add_texture_categ", on_delete=models.CASCADE, related_name="available_in", ) model_name = models.CharField( max_length=10, blank=True, null=True ) size = models.CharField( max_length=50, blank=True, null=True ) image = models.FileField( blank=True, default="", upload_to="media/images", ) def __str__(self): return self.select_category.addcategory # my viewset def create(self, request): try: data = request.data model_name = data.get("model_name") size = data.get("size") select_category = data.get("select_category") select_sub_category = data.get( "select_sub_category" ) available_in = data.get("available_in") new = add_model() new.model_name = model_name new.size = size new.select_category = add_category.objects.get( addcategory=select_category ) new.select_sub_category = sub_category.objects.get( subcategory=select_sub_category ) new.available_in = add_texture_categ.objects.get( addtexturecategory=available_in ) new.save() return Response({"submit": True}) except Exception as error: return Response( {"message": str(error), "success": False}, status=status.HTTP_200_OK, ) -
How to show all objects with same field value as 1 result and aggregate another field in django
it is a little complicated, here is how my model looks like: class Warehouse(models.Model): in_move = "in" out_move = "out" move_type_choices = ( (in_move, _('دخول')), (out_move, _('خروج')) ) item = models.ForeignKey(Item, on_delete=models.CASCADE) branch = models.ForeignKey(Branch, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=6, decimal_places=2) move_type = models.CharField(choices=move_type_choices, max_length=120) text = models.CharField(max_length=1200) date = models.DateTimeField(auto_now=True) employee = models.ForeignKey(Employee, on_delete=models.PROTECT) what I need to do is : A queryset like warehouse.objects.filter(branch=spicific_branch) group it by the item name so it shows all the queryset that have same item as one result Get the sum of the field quantity Define if it in or out move to get the current quantity inside the warehouse -
jQuery DataTable - element class is removed after sort
I am developing a django app. In my HTML template I have a table, where one of the is 2 rows of that I am dynamically creating. This is the relevant td: <td> <div class="row"> {% for d in p.get_list_of_lists %} <div class="a-box">{{ d.0 }}</div> {% endfor %} </div> <div class="row"> {% for d in p.get_list_of_lists %} <div class="b-box">{{ d.1 }}</div> {% endfor %} </div> </td> I am running a javascript function on document ready to dynamically add class to each of the a-box: function createSquares() { $('.a-box').each(function () { a= this.innerText switch (a) { case "1": $(this).addClass('great') break; case "2": $(this).addClass('good') break; case "3": $(this).addClass('ok') break; case "4": $(this).addClass('tough') break; case "5": $(this).addClass('bad') break; default: // code block } }); } Here is the code for the jQuery dataTable: function createTable() { dt = $('#data') if (dt) { dt.DataTable({ "order": [[3, "desc"]], "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]], "iDisplayLength": 25, 'aoColumnDefs': [{ 'bSortable': false, 'aTargets': ['nosort'] }] }); } } Everything is working well. I am able to color each box with the desired color. However, when I sort the table by one of its columns, some of the classes I added are removed and some … -
Django REST framework: deserializing foreign key fails (many-to-many)
I have the following model: models.py: class Host(models.Model): serialnr = models.IntegerField(primary_key=True) ...some other fields... class Event(models.Model): id = models.AutoField(primary_key=True) hosts = models.ManyToManyField(Host, through='EventHost') ...some other fields... class EventHost(models.Model): serialnr = models.ForeignKey(Host, on_delete=models.PROTECT) event = models.ForeignKey(Event, on_delete=models.CASCADE) ...some other fields... class Meta: unique_together = ("serialnr", "event") serializers.py: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = '__all__' class HostSerializer(serializers.ModelSerializer): class Meta: model = Host fields = '__all__' class EventHostSerializer(serializers.ModelSerializer): event = EventSerializer(read_only=True) serialnr = HostSerializer(read_only=True) class Meta: model = EventHost fields = '__all__' views.py class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.order_by('-date') serializer_class = EventSerializer class HostViewSet(viewsets.ModelViewSet): queryset = Host.objects.order_by('-serialnr') serializer_class = HostSerializer class EventHostViewSet(viewsets.ModelViewSet): queryset = EventHost.objects.order_by('-start_date') serializer_class = EventHostSerializer I'm sending the following JSON with HTTP POST: {event: {id: 4}, serialnr: {serialnr: 1234}, other_filed: 20} but it's not event_id and serialnr_id are not deserialized as seen in the log: psycopg2.errors.NotNullViolation: null value in column "event_id" violates not-null constraint DETAIL: Failing row contains (12, 20, null, null). I can read the data with HTTP GET but can't write with POST. How should I construct proper serializer to make it work? Also when I tried to send JSON like below it fails: {event_id: 4, serialnr_id: 1234, other_filed: 20}