Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Counting number of object visits per day in django
I have a model like below class Watched(Stamping): user = models.ForeignKey("User", null=True, blank=True, on_delete=models.CASCADE, default=None) count = models.PositiveIntegerField() Each time an object is viewed, the count attribute will increase by 1. My problem is how to find the number of times an object was hit per day. How can I achieve this. The Stamping is another model with created_at and updated_at -
Django how to track each models fields when it was last updated? or is it possible to use autonow in boolean or char fields?
I have a model name CustomerProject and I want to track individually few fields when it was last updated. Right now I am using auto_now= True in datetime fields which can tell me when the whole model was last edited but I want to track individually few boolean fields such as when the work started? when the work delivered etc. here is my models.py class CustomerProject(models.Model): project_title = models.CharField(max_length=2000,blank=True,null=True) project_updated_at = models.DateTimeField(auto_now= True,blank=True,null=True) #I want to track separately those BooleanField project_started = models.BooleanField(default=True) wting_for_sample_work = models.BooleanField(default=False) sample_work_done = models.BooleanField(default=False) working_on_final_project = models.BooleanField(default=False) project_deliverd = models.BooleanField(default=False) project_closed = models.BooleanField(default=False) -
Nested List within Bootstrap 4
I have a table with the following information: Name | Address John | 6432 Newcastle Way Rob | 893 Lake Point St Rob | 1900 Harbor Lane Rob | 124 Marginal St I am trying to create a nested list... That is, to show two total rows (one for John, one for Rob) and within the row, have another list showing each distinct Address (so Rob has 3 lines within his row). This output is not giving me unique values and is not grouping them... any ideas how to tweak this or any walkthroughs I can find? Views.py from django.http import HttpResponse from django.views.generic import TemplateView,ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Book class BookList(ListView): queryset = Book.objects.all().distinct('name') HTML Try 1 <ul class="list-group"> {% for book in object_list %} <li style="margin-bottom: 25px;"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{ book.name }}</h5> <h6 class="card-subtitle mb-2 text-muted">{{ book.address }}</h6> <a href="{% url 'books_cbv:book_edit' book.id %}">Edit</a> <a href="{% url 'books_cbv:book_delete' book.id %}">Delete</a> </div> </div> </li> {% endfor %} </ul> HTML Try 2 <table> {% for book in object_list %} <li>{{ book.name }} <li> {{ book.address }} </li> </li> {% endfor %} </table> -
AttributeError: module 'student.models' has no attribute 'ManyToManyField'
I'm using the below models: models.py class Student(models.Model): name = models.CharField(max_length = 200) country = models.ManyToManyField(Country, null = True,blank=True) class Country(models.Model): title = models.CharField(max_length = 100, null = True) def __str__(self): return self.title admin.py @admin.register(models.Student) class StudentAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } I get this error: AttributeError: module 'student.models' has no attribute 'ManyToManyField' -
How to use @font-face with production Django on Digital Ocean?
I can't seem to access my static fonts using @font-face CSS property with the font stored on digital ocean spaces. All my other static items work in the html section. For example, I can do: {% load static %} <div class = "statusImg"><img id = '{{machine.id}}simLight' src="{% static 'images/simLight_off.png' %}"></div> And this will work as expected, bringing in the image from digital ocean. I am not sure how to do this in <style> section though? I tried: <style> @font-face { font-family: PSSroboto; src: url("/static/fonts/roboto/Roboto-Regular.ttf") } </style> and: <style> @font-face { font-family: PSSroboto; src: url({% static '/static/fonts/roboto/Roboto-Regular.ttf' %}) } </style> and: <style> @font-face { font-family: PSSroboto; src: "{% static '/static/fonts/roboto/Roboto-Regular.ttf' %}" } </style> I even hardcoded the URL and made the font public, but this resulted in a CORS policy violation, and in general, probably isn't a great idea anyway. I am hoping it is something small I am missing? Thanks! -
DJango forms: A dynamic integer model choice field always fails form.has_changed()
So I have a list of items, with an integer associated with each values: e.g. CAKE = 1 CHOC = 2 CHIPS = 3 A model with a field foo uses these values as its field, so the model's field is an integer field. This choice selection is not fixed, its dynamic at the point of render. In order to get create a dynamic choice field for an integer field, after much trial and error I eventually got the following solution: class FooForm(forms.ModelForm): def __init__(self, *args, foo_choices, **kwargs): super().__init__(*args, **kwargs) self.fields['foo'].choices = foo_choices def clean_foo(self): foo = int(self.cleaned_data['foo']) return foo class Meta: model = Foo field_classes = { 'foo': forms.ChoiceField, } widgets = { 'property_id': forms.Select(), } All is good, except when i call form.has_changed, the only field which incorrectly reports has changed is 'foo'. The default to_python for a choice field is: def to_python(self, value): """Return a string.""" if value in self.empty_values: return '' return str(value) As you can see the value is always a string. This is fine, because my clean then changes it to an int. However the problem with the has_changed method, is that it checks whether it has changed as follows: if field.has_changed(initial_value, data_value): Where … -
How to implement HATEOS-style links with Django REST framework's ModelViewSets?
I have this product model import uuid from django.db import models class Product(models.Model): """Product in the store.""" title = models.CharField(max_length=120) description = models.TextField(blank=True) price = models.DecimalField(decimal_places=2, max_digits=10) inventory = models.IntegerField(default=0) uuid = models.UUIDField(default=uuid.uuid4, editable=False) def __str__(self): return f'{self.title}' and I defined a serializer for it from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['title', 'description', 'price', 'inventory', 'uuid'] and this is my view from rest_framework import viewsets from .serializers import ProductSerializer from .models import Product class ProductViewSet(viewsets.ReadOnlyModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'uuid' To start the question, just keep in mind that this view is routed on /store/products/. Now, for example I can do GET http://localhost/store/products/ and it returns [ { "title": "Computer", "description": "", "price": "50.00", "inventory": 10, "uuid": "2d849f18-7dea-42b9-9dac-2ea8a17444c2" } ] but I would like it to return something like [ { "href": "http://localhost/store/products/2d849f18-7dea-42b9-9dac-2ea8a17444c2" } ] and then have http://localhost/store/products/2d849f18-7dea-42b9-9dac-2ea8a17444c2 return { "title": "Computer", "description": "", "price": "50.00", "inventory": 10, "uuid": "2d849f18-7dea-42b9-9dac-2ea8a17444c2" } as it already does. Is this possible using the build-in serialization, or how can I define one that does this? I've played around with the list_serializer_class property but I can't get anything working. -
User modifying field only for themselves in Django
I'm sort of new to Django and am currently struggling with a certain aspect of it. In my project I want all Users to have access to certain Jobs added by the admin and appear on the Front end. However each Job has a field called userStatus that the user should be able to edit. This field however should not change for any other users. Currently I have created a model out of userStatus and created a Foreign Key field to link to a Job. Then userStatus has a User Foreign Key Field. class Job(models.Model): name = models.CharField(max_length=200, help_text='Enter the Spring/Internship') course = models.ForeignKey('Course', on_delete=models.RESTRICT,null=True) company = models.ForeignKey('Company', on_delete=models.RESTRICT,default='N/A') deadline = models.DateField(null=True, blank=True) userStatus = models.ForeignKey('userStatus', on_delete=models.RESTRICT, null=True, blank=True) class userStatus(models.Model): user = models.ForeignKey(User, on_delete=models.RESTRICT) USER_STATUS = ( ('n', 'Not Applied'), ('a', 'Applied'), ('i', 'Got Interview'), ('o', 'Got Offer'), ('r', 'Rejected'), ) stage = models.CharField( primary_key=True, max_length=1, choices=USER_STATUS, blank=False, default='c', help_text='What is the current stage of the process', ) The User should not be able to edit any field except for the userStatus that should only belong to them. The tuple USER_STATUS should be the only options for that model and every Job should have access to these 5 options. … -
Django : how to create a mailbox for each users i have
I have a project with 3 groups of user who are admin, prof, and student. I want all my users to be able to send messages to each other privately. For example if I want a teacher to send a message to a student or admin, how should I proceed? Do I need to create a new model or I just need to add a mailbox field to my models. that's my models models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import RegexValidator from phonenumber_field.modelfields import PhoneNumberField class Prof(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) location = models.CharField(max_length=150) date_of_birth = models.DateField(null=True, blank=True) phone = PhoneNumberField(blank=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) speciality = models.CharField(max_length=150) location = models.CharField(max_length=150) date_of_birth = models.DateField(null=True, blank=True) phone = PhoneNumberField(blank=True) here is how I register my 3 types of users with django signals signals.py from django.db.models.signals import post_save from django.contrib.auth.models import Group from django.dispatch import receiver from .models import Prof, Student from django.contrib.auth.models import User @receiver(post_save, sender=User) def admin_profil(sender, instance, created, **kwargs): if created and instance.is_superuser: group = Group.objects.get(name='admin') instance.groups.add(group) @receiver(post_save, sender=Prof) def prof_profil(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='prof') instance.user.groups.add(group) @receiver(post_save, sender=Student) def student_profil(sender, instance, created, **kwargs): if created: group … -
How to translate form error messages in django?
I want to translate error messages in django's forms and show the translation in my template, but I don't know how to translate error messages when I am using form.errors to get form's error messages. should I use ugettext or ugettext_lazy or something else? How to use them to translate form's messages? -
Django: annotate(sum(case(when())))
In my project, I'm trying to aggregate the data based on the status of a 'field'. The 'view' is expected to return a table like so: SERVICE_CODE SUCCESS TECHNICAL_DECLINES BUSINESS_DECLINES Service-1 S11 S12 S13 Service-2 S21 S22 S23 where S11,S12... are the aggregates taken based on the value of the field 'STATUS' in the model given below: models.py from django.db import models class Wfmain(models.Model): ENTITY_NUM = models.IntegerField() SRV_REF_NUM = models.CharField(max_length=30,primary_key=True) ITER_SL = models.IntegerField() STAGE_ID = models.CharField(max_length=30) ACTION = models.CharField(max_length=30) STATUS = models.CharField(max_length=30) REQUEST_DATE = models.DateField() SERVICE_CODE = models.CharField(max_length=30) SERVICE_TYPE_CODE = models.CharField(max_length=30) FUNCTION_CODE = models.CharField(max_length=30) REQUEST_START_TIME = models.DateField() class Meta: db_table = "WFMAIN" unique_together = (("ENTITY_NUM", "SRV_REF_NUM"),) The aggregates ought to be grouped by the field 'SERVICE_CODE' views.py from django.db.models import When, Case, Sum, IntegerField from django.shortcuts import render,redirect from hr.models import * def financial(request): S=['0','00','000'] NT=['0','00','000','099','100','101','102','103','104','105','107','108','109','110','111','113','114','116','117','118','119','120','121','122', '123','124','180','181','182','183','184','185','186','187','188','189','200','201','205','213','217','218','219','220','221','222','223','224', '230','231','232','233','234','235','236','237','238','239','240','241','248','249','250','256','258','260','262','263','264','265'] B=['S','099','100','101','102','103','104','105','107','108','109','110','111','113','114','116','117','118','119','120','121','122','123','124', '180','181','182','183','184','185','186','187','188','189','200','201','205','213','217','218','219','220','221','222','223','224','230','231', '232','233','234','235','236','237','238','239','240','241','248','249','250','256','258','260','262','263','264','265'] wf=Wfmain.objects.using('MBDB') fin = wf.values('SERVICE_CODE').annotate( Success=Sum(Case(When(STATUS in S, then=1), when(STATUS not in S, then=0), output_field=IntegerField())), Technical_declines=Sum(Case(When(STATUS not in NT, then=1), When(STATUS in NT, then=0), output_field=IntegerField())), Business_declines=Sum(Case(When(STATUS in B, then=1), When(STATUS not in B, then=0), output_field=IntegerField()))).order_by('SERVICE_CODE') I'm stuck with error: "name 'STATUS' is not defined" Output @browser: Please tell me where I went wrong. -
Is there a way to delete an object from database in html document? (django)
view.html <th><button id={{p.id}} onclick="Delete(this.id)" class="btn btn-outline-danger">Delete</button></th> <script> function Delete(row_id){ document.getElementById(row_id).remove(); {{dogss.objects.filter(id=1)}.delete()}} //I wanted this to happen, but it's not working } </script> </tr> view.py def view(response): return render(response, "main/view.html", {"dogs": Dog.objects.filter(user=response.user), "dogss": Dog}) I know that I can make that button interact with .py file and from there it will probably work. But I'm curious why this isn't working? -
calendar-telegram not forwarding more than 1 month
I found th is calendar-telegram https://github.com/unmonoqueteclea/calendar-telegram I'm using python-telegram-bot with the Conversation Handler, but some how when I want to forward in the calendar to a future month it does not work, this is what I have tried so far: bot.py def get_telefono(update: Update, context: CallbackContext) -> None: telefono = update.message.text context.user_data['telefono'] = telefono user_data = context.user_data respuesta = 'Fecha de Vencimiento AAAA-MM-DD' update.message.reply_text(respuesta, reply_markup=telegramcalendar.create_calendar()) return GET_VENCIMIENTO def get_vencimiento(update: Update, context: CallbackContext) -> None: bot = context.bot selected, date = telegramcalendar.process_calendar_selection(bot, update) if selected: respuesta = date.strftime("%d/%m/%Y") update.message.reply_text(respuesta, reply_markup=ReplyKeyboardRemove()) return GET_PAGO class Command(BaseCommand): help = 'test' def handle(self, *args, **options): updater = Updater(settings.TOKEN) dispatcher = updater.dispatcher conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start, Filters.user(username="@cokelopez"))], states={ GET_TELEFONO: [MessageHandler(Filters.regex('^\+?1?\d{9,15}$'), get_telefono)], UP_TELEFONO: [MessageHandler(Filters.regex('^\+?1?\d{9,15}$'), up_telefono)], GET_VENCIMIENTO: [CallbackQueryHandler(get_vencimiento)], GET_PAGO: [MessageHandler(Filters.text, get_pago)], }, fallbacks=[CommandHandler('cancel', cancel)], allow_reentry = True, ) dispatcher.add_handler(conv_handler) dispatcher.add_error_handler(error) updater.start_polling() updater.idle() *it's just part of the code The calendar just hangs and nothing happens, I'm in Auguts and when I click next it goes to September, but ir I try the next mont, October, it just hangs in September -
Chinese characters to equivalent html on python
I am working on a Japanese project on Django. I have most of characters on its html code equivalent to avoid them to display unproperly. For insance, instead of "死", I use "死". However, I hace a csv with info I need to compare to other data on the project, but its characters are not in html code. Is there a way to decode those chinese characters into html code to have the code comparing some entries? Thanks! -
Can I use the default login view to login multiple users to different profile pages in Django?
I am using Django 3.2 and I recently learned to create custom user models with email instead of username and the default authentication views. I implemented the following form in my login.html <form action="{%url 'login'%}" class="mx-3" method="post"> {% csrf_token %} <div class="emailAddressLog"> <label data-error="wrong" data-success="right" for="modalLRInput10" class="mt-3">Email Address:</label> <div class="input-group mb-3"> <i class="bi bi-envelope-fill input-group-text"></i> <input type="text" class="form-control validate" name="username" autocapitalize="none" autocomplete="username" autofocus="" id="id_username" maxlength="60" required=""> </div> </div> <div class="passwordLog mb-4"> <label data-error="wrong" data-success="right" for="modalLRInput11">Password:</label> <div class="input-group"> <i class="bi bi-lock-fill input-group-text"></i> <input required type="password" id="id_password" class="form-control validate" contenteditable="true" autocomplete="current-password" name="password"> </div> </div> {% if form.errors %} <p class=" label label-danger" style = "color:red"> Your username and password didn't match. Please try again. </p> {% endif %} {%if next%} {%if user.is_authenticated%} <p>Your account does not have access, please login with an account that has access.</p> {%else%} <p>Please login to see this page</p> {%endif%} {%endif%} My project based urls.py has in patters path('login/', auth_views.LoginView.as_view(), name='login'), I followed the documentation and so far it seems to work as when I input an incorrect user it gives me the error message but when I input the correct user with email and password then it throws me to an error as I have not implemented … -
Getting an empty list when using filter - Django REST
I have my API in Django REST Framework: Here is my models.py: class myModel(models.Model): user_email = models.CharField(max_length= 200, null= False) Here is my views.py: class GetItemsByEmail(generics.ListAPIView): def get_queryset(self): email_items = self.request.query_params.get("user_email") if(email_items is not None): itemsReturned = myModel.objects.all().filter(user_email = email_items) return Response(data= itemsReturned) Here is my urls.py: url_patterns = [ path('users/account=<str:id>/shipments', GetItemsByEmail.as_view()), ] My Question: I am getting an empty list, getting nothing from making an API call to the above endpoint. I want to get all the items in the database associated with a particular email? -
I'd like to save all the options selected in Django
I am a student who is studying Django. I want to save all of the selected option values when I select the option. However, we are facing a problem where all of the selected option values are not saved. Of the selected option values, only the last selected option values are saved. How can I save all of the selected option values? I tried 1:1 to the experts, but it didn't work out. I don't know how to solve it, so I put up a question here. Please, I want to know how to solve it. form class ElementForm(forms.Form): value_code = forms.ModelChoiceField(error_messages={'required': "옵션을 선택하세요."}, label="옵션") views.py if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = form.cleaned_data['value_code'] element.save() else: element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = None element.save() html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}" enctype="multipart/form-data"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} … -
How to display richtext {{content |safe}} as in regular html to vue template
I am making this website where I am using a richtext editor for input, what I usually did before is that I include the 'safe' tag as in {{Content|safe}} in django HTML template.However, recently I want to convert it to a spa website, I am not able to render the ** |safe tags in the vue template** . How should I resolve this? -
Invoke JavaScript function when the select element is first displayed
I have the following HTML in my Django app: <select required size="1" name="relevancy" id="relevancy{{result.report_id}}" onChange="change_relevancy(this.value,{{ result.report_id }});"> <option value="" {% if result.relevance == " " %} selected {% endif %}>Select...</option> <option value="N" {% if result.relevance == "N" %} selected {% endif %}>None</option> <option value="M" {% if result.relevance == "M" %} selected {% endif %}>Moderate</option> <option value="H" {% if result.relevance == "H" %} selected {% endif %}>High</option> </select> How do I call a JavaScript function when the select is first displayed? -
Django query by filter different attributes from slug
I have a model with lots of attributes. I want to query the model by filters in attritbutes. The problems is that I have to write lots of function to query by different attributes. models.py class ETF(models.Model): ticker = models.CharField(max_length=6, blank=False, db_index=True, unique=True) full_name = models.CharField(max_length=200, blank=False) region = models.ManyToManyField(Region) sector = models.ManyToManyField(Sector) industry = models.ManyToManyField(Industry) # Even more attributes here class Theme(models.Model): name = models.CharField(max_length=50, blank=False, unique=True) slug = models.SlugField(default="", null=False) def __str__(self): return self.name I am writing a function to filter ETF by attritbutes. Here is Views.py: class Categories_selector(): def __init__(self): pass def theme(self, category_slug): return ETF.objects.filter(theme__slug=category_slug).order_by('-aum') def sector(self, category_slug): return ETF.objects.filter(sector__slug=category_slug).order_by('-aum') def region(self, category_slug): return ETF.objects.filter(region__slug=category_slug).order_by('-aum') # more function here c_object = Categories_selector() def get_etf_list(request, categories_slug, category_slug): filtered_results = getattr(c_object, categories_slug)(category_slug) return render(request, "etf/list_etf.html", { "ETFs": filtered_results }) urls.py path("<slug:categories_slug>/<slug:category_slug>/", views.get_etf_list) Is there better way to do this? I feel like this is really dumb. -
Django DRF nested relationships - how to add objects in a ManyToMany field
I am building an API with DRF. I have two models, Folder and User, connected through a ManyToMany field. models.py class Folder(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=250) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) users = models.ManyToManyField(User, related_name='folders') def __str__(self): return self.title class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email serializers.py class FolderSerializer(serializers.ModelSerializer): class Meta: model = Folder fields = ("id", "title", "description", "users", "organization") def create(self, validated_data): users = validated_data.pop('users') if 'users' in validated_data else [] folder = Folder.objects.create(**validated_data) for user in users: if user in User.objects.all(): User.objects.filter... **not sure** else User.objects.create(folder=folder, **user) return folder The part I am stuck on is the custom create method: basically, users do not get created when the folder is created, they just get added to the newly created folder, so I think that in the for loop for user in users I should check if user exists within the instances of model User and if it does, I should update its property folder. I have no idea how to do so though. Also, I am … -
In Django, optimize performance when using a foreign key's attribute in the __str__method
The implementation of DocumentDetail's str method works, but is slows everything down by running a bunch of extra queries when I try to use it views, forms, etc. Does anyone know a way around this? models.py class Document(models.Model): description = models.CharField(max_length=50) def __str__(self): return self.description class DocumentDetail(models.Model): document = models.ForeignKey(Document, on_delete=models.CASCADE) detail = models.CharField(max_length=50) def __str__(self): return self.document.description -
Django aggregate sum for each user
I'm creating a budget application and wanted to find the sum of each user who's signed in. Right now I'm using function-based views and I sum up the expenses with Post.objects.aggregate(sum = Sum('expense')) The issue with this is it sums up everyone in the database but I wanted it to only sum up the expenses of the user that is currently signed in. In my model, I have an author field but I'm not sure how to go about summing only for the user currently signed in. -
DRF - APIView and Serializing a model with multiple foreign Keys(User)
How to save multiple foreign keys(User) data? In my case, the client(foreign key) should be able to hire to professional(foreign key) to the User model, how is it possible? models class User(AbstractUser): email = models.EmailField(max_length=255, unique=True) is_client = models.BooleanField(default=False) is_professional = models.BooleanField(default=False) class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='client') ## class Professionals(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='professional') ## class HireProfessional(models.Model): user = models.ForeignKey(User, related_name='owner', on_delete=models.CASCADE) hire = models.ForeignKey(User, on_delete=models.CASCADE, related_name="hire") hire_start_date_time = models.DateTimeField(default=timezone.now) hire_end_date_time = models.DateTimeField(default=timezone.now) serializer class UserSerializer(serializers.ModelSerializer): client = ClientSerializer() professional = ProfessionalSerializer() class Meta: model = User fields = ('email', 'username', 'is_client', 'is_professional', 'client', 'professional') class HireProfessionalSerializer(serializers.ModelSerializer): user = UserSerializer() hire = UserSerializer() class Meta: model = HireProfessional fields = ['id','user', 'hire', 'hire_start_date_time', 'hire_end_date_time'] views class HireProfessionalCreateApp(APIView): permission_classes = (IsAuthenticated, IsClientUser,) def get_user(self): user = self.request.user return user def post(self, request, pk, format=None): try: professional = User.objects.get(id=pk) data = request.data _mutable = data._mutable data._mutable = True data['user'] = self.get_user() data['hire'] = professional data._mutable = _mutable serializer = HireProfessionalSerializer(data=data) data = {} if serializer.is_valid(): hire = serializer.save() data['hire'] = hire.hire return JsonResponse ({ "message":"professional hired success.", "success" : True, "result" : data, "status" : status.HTTP_201_CREATED }) else: data = serializer.errors return Response(data) except User.DoesNotExist: return JsonResponse ({"status":status.HTTP_404_NOT_FOUND, 'message':'user … -
Django-Tinymce with Tailwind CSS
I am currently using django-tinymce4-lite for my project and everything else works as expected. But on the actual rendered HTML page where the tinymce4 formatted content is supposed to be displayed, tailwind-preflight messes up the formatting with lists and spaces. I found this solution here. It is the exact problem I am facing. The first answer doesn't work for me and I want to get that working. I am following this tutorial to use Tailwind CSS with Django. I am new to npm so I blindly followed, and everything works but when I try to implement the first answer nothing happens. Using the second answer works but then it messes up the entire front-end.