Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After creating user order while verifying the payment and redirecting user to the page it give me this error
code 400, message Bad request version ('zz\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\x93ÚÚ\x00\x00\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00') You're accessing the development server over HTTPS, but it only supports HTTP. -
trying to print python function output in html page using django
enter image description here here -
Nothing showed up when looping dict items on Django Python
I have a json dict that store my values: [{'serial': 'DKFU-V7ZE-RD9R'}, {'serial': 'HKDR-SX7Z-29KR'}, {'serial': 'VSW9-XD3Q-GZ2W'}] I tried to display all the key and value to a table on my django template but it doesnt showed anything. My Html: <div class="col-md-5 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <h4 class="card-title">Available Minis Serial Code</h4> <div class="list-wrapper pt-2"> <ul class="d-flex flex-column-reverse todo-list todo-list-custom"> {% for key, value in item_list.items %} <li> <div class="form-check form-check-flat"> <label class="form-check-label"> {{ forloop.counter }}. {{ key }} : {{ value }} </label> </div> </li> {% endfor %} </ul> </div> </div> </div> </div> My views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib import messages import urllib.request from urllib.error import HTTPError import json # Create your views here. def index(request): return render(request,'AlertTraceApp/hi.html') def send(request): if request.method == 'POST': .... EmptyMiniSerial = [{'serial': dct['serial']} for dct in resp_dict2 if (dct['subject']) == None] #getting the serial value only print(EmptyMiniSerial) status_code = response.status if status_code == 200 or status_code == 201 or status_code == 204 : # request succeeded context = { 'item_list': EmptyMiniSerial, } return render(request, 'AlertTraceApp/mainpage.html', context) else: messages.error(request, 'username or password not correct') Does my syntax have any errors? When I run my app it doesn't showed me … -
Django form with repeated fields
I need to a django form with some fields unique (id_station and station name) and the fields: sensor_unity, id_sensor and sensor_name repeated. When form is loaded there are these fields and near the fields sensor_unity, id_sensor and sensor name there is a link to add another row of the same fields. I tryied with this tutorial: https://www.codementor.io/@ankurrathore/handling-multiple-instances-of-django-forms-in-templates-8guz5s0pc but my code doesn't work because I receive the error: ValueError: The view station.views.new_station didn't return an HttpResponse object. It returned None instead. [20/Sep/2021 18:00:16] "GET /station/new_station/ HTTP/1.1" 500 69039 This is my code: models.py from django.db import models nr_unities = [(x, x) for x in range(1, 10)] class Station(models.Model): id_station = models.IntegerField(blank=False) station_name = models.CharField(max_length=30, blank=False) units_number = models.IntegerField(choices = nr_unities, blank=False) nr_sensor_unity = models.IntegerField(blank=False) id_sensor = models.IntegerField(blank=False) sensor_name = models.CharField(max_length=50, blank=False) def __str__(self): return self.name forms.py from django import forms from .models import Station nr_unities = [(x, x) for x in range(1, 10)] class StationForm(forms.ModelForm): class Meta: model=Station fields = ['id_station'] #, 'station_name', 'units_number', 'nr_sensor_unity', 'id_sensor', 'sensor_name'] widgets = { 'id_station': forms.IntegerField(), 'station_name': forms.CharField(), 'units_number': forms.ChoiceField(choices = nr_unities), 'nr_sensor_unity': forms.IntegerField(), 'id_sensor': forms.IntegerField(), 'sensor_name': forms.CharField(), } id_station = forms.IntegerField(label='id della stazione') station_name = forms.CharField(label='nome della stazione', max_length=30) units_number = forms.ChoiceField(label='numero unita', choices … -
Get the boolean which values True within a model that contains two (x) booleans
I'm curious if (actually how) my below approach could be simplified. # Model class Vote(models.Model): """ A Class for Votes made by Users for a specific Poller """ poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote') user = models.ForeignKey(Account, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) def __str__(self): return f'Vote by {self.user}' # View @require_POST def submit_comment(request, poller_id): form = PollerCommentForm(request.POST) # Get the choice made by the user of the request user_vote = Vote.objects.get(poller=poller_id, user=request.user) # Check booleans vote_one = False if user_vote.poller_choice_one_vote: vote_one = True [..] Is there a more "django-way" to make this a one-liner to get the field which is True in the view? (e.g. if there would be multiple fields to check. Note: only one will be true) -
How to set a daily id for a model in django
I have a model which people use its id to remember a record for later use. But as the id is getting bigger and bigger, it's getting harder for people to remember that large number. So i thought a short and daily version of that id is needed. That number should start from 1 everyday and having the short id and a date should give the right record. So i thought of adding an AutoField to model and reset it to start from 1 everyday. How can i implement that? If you think it is not the right way to implement that functionality, what do you suggest? -
heroku and django: heroku stop the function before it done
I deployed a "django" app on "heroku" and I have a function (inside views) in my app that take some time (3m-5m) before it make a return. the problem is: - when I deployed my app on "heroku" the function didn't make a return, I tested my app on my pc and it work fine. "heroku" not telling me any thing in logs there is no 'timeout' or anything. -
query django model with same modelfields
so i have this django model class terrain(models.Model): location=models.CharField(max_length=200) size=models.CharField(max_length=200) def __str__(self): return str(self.location) how do i get the location of diffrent terrains having the same size ,i used the filter but i have to specify the size for example data=terrain.objects.filter(size="big") can't i do this without specifying the size just by pasing the size field -
Django, Mysql Docker Project can't connect to database
My docker file is as below : FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app COPY requirements.txt /app/ WORKDIR /app RUN pip3 install -r requirements.txt COPY . /app EXPOSE 8082 CMD ["python", "manage.py", "runserver", "0.0.0.0:8082"] And here is my db definitions in settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'knowledge_base_py', 'USER': 'root', 'PASSWORD': 'root' } } I run mysql separately outside a docker container because I want to use AWS RDS as a database in the production. When I run the docker run command, I receive a "django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)")" error. What should I do? -
Get the user instance from a profile model
Hella everyone, Alright I'm building an ecommerce website and stuck at a certain point, I got two models Seller and Product, as follows: class Seller(models.Model): seller = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=30) country = models.CharField(max_length=30) phone_number = PhoneNumberField() email = models.EmailField(max_length=300) def __str__(self): return self.seller.username class Product(models.Model): STATUS_CHOICES = [ ('New', 'New'), ('New', 'Used'), ] image = models.ImageField(default='dev1.jpg', upload_to='images/') condition = models.CharField(choices=STATUS_CHOICES, max_length=10) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() price = models.CharField(max_length=15) location = models.CharField(max_length=30) posted_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Now I have a form to save new Product as: class SellProductForm(forms.ModelForm): class Meta: model = Product fields = ('image', 'condition', 'title', 'description', 'price', 'location', ) The problem is in views.py: @login_required def sell(request): form = SellProductForm() if request.method == 'POST': form = SellProductForm(request.POST) if form.is_valid(): print('Ok') instance = form.save(commit=False) instance.seller = request.user instance.save() return redirect('index') context = { 'form': form, } return render(request, 'myapp/sell.html', context) At the end, I get the ERROR: "Product.seller must be a Seller instance." I understand the demand but I can't get myself to imagine the code and come up with a solution, for I'm giving it a User instance not a seller instance. -
Django vs ASP.NET is faster for a website with more than 5 millions pages
I want to create a website with millions of pages that only contain text like Google scholar. I have background knowledge in Python but I don't have any experience in asp.net. I want to know which language is faster and easier to create this website? -
How to avoid THOUSAND SEPARATOR in certain views in django?
I am using Django's THOUSAND SEPARATOR in the settings.py file for the entire project but due to this whenever the IDs of objects get greater than 1000 in my views e.g: 1200, they are read as 1.2 . How to avoid the THOUSAND SEPARATOR for certain views? -
How to create url to image in databse with expiration time
I have create model like: class Photo(models.Model): """ Photo model with automatically generated Thumbnail by TierPhotoSetting of UserTier """ user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) photo = models.ImageField(upload_to='photos', blank=False, null=False) and now I would like to create a new database object which stores a link to photo from Photo. This url link should have expiration time like 500 sec. How to serve user url to image which are active just some time? Thanks in advance. -
How can I call countries and cities to my dropdownlist with this json format
How do you get data from json doesn't have any id's/titles. I can't get the data to my dropdown selection. This is what I have so far...(and am new at this) Json file that looks like this: { "Afghanistan": [ "Herat", "Kabul", "Kandahar", "Molah", "Rana", "Shar", "Sharif", "Wazir Akbar Khan" ], "Albania": [ "Elbasan", "Petran", "Pogradec", "Shkoder", "Tirana", "Ura Vajgurore" ], "Algeria": [ "Algiers", "Annaba", "Azazga", "Batna City", .... register_1.html {% csrf_token %} <div class="col-md-6"> <div class="form-group"> <label for="inputStatus">Country</label> <select id="place-country" class="form-control-sm custom-select"> <option selected disabled>Country</option> {% for country_name in countries %} <option value="{{country.name}}">Country</option> {% endfor %} </select> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="inputStatus">City</label> <select id="place-city" class="form-control-sm custom-select" name="topic"> <option selected disabled>City</option> </select> </div> </div> views.py from django.http import JsonResponse import json import urllib.parse def get_cities_ajax(request): country_data = 'profileusers/static/profileusers/json/countries.json' url = country_data.urllib.parse.urlencode() data = request.get(url).json() print(data) for name in data: print(name) if request.method == "POST": country_name = request.POST['country_name'] try: countries = countries.objects.filter(name = country_name).first() cities = Topic.objects.filter(countries = countries) except Exception: data['error_message'] = 'error' return JsonResponse(data) return JsonResponse(list(cities.values()), safe = False) Or if I should use the form.py since its for registration? from django.http import JsonResponse import json import urllib.parse class ProfileForm1(forms.ModelForm): country = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label='Country:') city = … -
How to get count of foreign key relationship for each instance in queryset?
I have the following Models: # app_a/models.py class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_on = models.DateTimeField(auto_now_add=True) # app_b/models.py class PollerComment(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='PollerComment') user = models.ForeignKey(Account, on_delete=models.CASCADE) And this view to render the template: def render_pollboard(request): # Query Pollers poller_queryset = Poller.objects.all() # Convert to list qs_list = list(poller_queryset) # Shuffle the list shuffle(qs_list) # Retrieve comment count per Poller comments_qs = PollerComment.objects.filter(poller_id=poller.poller_id) [..] In the view I try to get the comment count for each Poller in poller_queryset. How to do this? Side note: I tried to implement the comment count as a method to the Poller model, but due to my design this leads into a circular import error of module of app_b/models.py -
Django/Heroku Error loading psycopg2 module: No module named 'psycopg2'?
Hi All I Re Creat django Local code Because my pc formatted and my project removed & when i push it on heroku when i try to open it again they give me this error 2021-09-20T14:55:18.814726+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/options.py", line 207, in contribute_to_class 2021-09-20T14:55:18.814726+00:00 app[web.1]: self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) 2021-09-20T14:55:18.814732+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/connection.py", line 15, in getattr 2021-09-20T14:55:18.814733+00:00 app[web.1]: return getattr(self._connections[self._alias], item) 2021-09-20T14:55:18.814733+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/connection.py", line 62, in getitem 2021-09-20T14:55:18.814733+00:00 app[web.1]: conn = self.create_connection(alias) 2021-09-20T14:55:18.814734+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 204, in create_connection 2021-09-20T14:55:18.814734+00:00 app[web.1]: backend = load_backend(db['ENGINE']) 2021-09-20T14:55:18.814734+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 111, in load_backend 2021-09-20T14:55:18.814735+00:00 app[web.1]: return import_module('%s.base' % backend_name) 2021-09-20T14:55:18.814735+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/init.py", line 127, in import_module 2021-09-20T14:55:18.814735+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-09-20T14:55:18.814736+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 29, in 2021-09-20T14:55:18.814736+00:00 app[web.1]: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) 2021-09-20T14:55:18.814736+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' 2021-09-20T14:55:18.814876+00:00 app[web.1]: [2021-09-20 14:55:18 +0000] [7] [INFO] Worker exiting (pid: 7) 2021-09-20T14:55:18.879919+00:00 app[web.1]: [2021-09-20 14:55:18 +0000] [8] [ERROR] Exception in worker process 2021-09-20T14:55:18.879943+00:00 app[web.1]: Traceback (most recent call last): 2021-09-20T14:55:18.879943+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 25, in 2021-09-20T14:55:18.879944+00:00 app[web.1]: import psycopg2 as Database 2021-09-20T14:55:18.879944+00:00 app[web.1]: ModuleNotFoundError: No module named 'psycopg2' 2021-09-20T14:55:18.879945+00:00 app[web.1]:undefined 2021-09-20T14:55:18.879945+00:00 app[web.1]: During handling of … -
Django celery beat not able to locate app to schedule task
I'm trying to schedule a task in celery. celery.py inside the main project directory from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE','example_api.settings') app = Celery('example_api') app.config_from_object('django.conf:settings',namespace="CELERY") app.conf.beat_schedule = { 'add_trades_to_database_periodically': { 'task': 'transactions.tasks.add_trades_to_database', 'schedule': crontab(minute='*/1'), # 'args': (16,16), }, } app.autodiscover_tasks() The project has a single app called transactions. function inside transactions/tasks.py @task(name="add_trades_to_database") def add_trades_to_database(): start_date = '20000101' #YYYYDDMM end_date = '20150101' url = f'https://api.example.com/trade-retriever-api/v1/fx/trades?fromDate={start_date}&toDate={end_date}' content = get_json(url) print(content) save_data_to_model(content,BulkTrade) settings.py """ Django settings for nordea_api project. Generated by 'django-admin startproject' using Django 3.2.7. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import environ env = environ.Env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env.read_env(env.str('BASE_DIR', '.env')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'example' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', … -
How can I solve the AttributeError?
Traceback (most recent call last): File "C:\Users\taink\PycharmProjects\upload\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\taink\PycharmProjects\upload\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\taink\PycharmProjects\upload\upload\views.py", line 23, in uploadFile documents = models.document.objects.all() Exception Type: AttributeError at /upload/ Exception Value: module 'django.db.models' has no attribute 'document' I'm trying to combine the two django projects that worked well when running each other, but it keep getting errors. Even if the code is separated and executed again after an error, the same error continues. What's the problem? -
Django - implications of READ COMMITTED isolation level in forms for users
So according to Django's doc, by default it implements Postgres' read committed isolation level. I understand the implications wrt to dirty read/writes. However, how does this play out from a user perspective in django? For instance: User A and User B both open the same model form. User A modifies the form, submit it and the commits the transaction, which passes. User B modifies fields "foo" and "bar" for instance. If "bar" has been modified by User A, will the transaction succeed for User B? If "foo" wasn't modified by User A, will the transaction succeed for B? In case a transaction doesn't succeed for B, would be details show up in non_form_errors? Or is the right thing to do is to manage it myself in the view & return a message/redirect to the user according to my business logic? Thanks! -
How to get passed JSON Data on Ajax Error?
I am using Django and Ajax. Im my view I have: return JsonResponse({"data": "success data"}, status=200) and return JsonResponse({"data": "error data"}, status=400) my ajax function looks like: $("#start_calculation_button").click(function () { $.ajax({ url: "/", type: 'get', data: { ... }, success: function (response) { console.log(response.data); }, error: function (response) { console.log(response.data); } }) }) But only the success function works? While the error part just gives back undefined Any idea's why it is that way? How can I fix it? -
authenticate on my models not User model in django
I have a model called Man which contain a name and a password do django support authentication on something other than User built-in model -
Passing URL Parameter to Django Form as an Attribute
Hello I am trying to use a URL parameter(id) in Django Model Forms as an attribute variable and getting an error as below. I am not sure if it's possible to pass id variable with calling "BidListing(id)" class like that. And getting it "BidListing(forms.ModelForm, id)" with this way. Error ...\forms.py", line 24, in <module> class BidListing(forms.ModelForm,id): TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases PS C:\Users\ycemalunlu\Desktop\commerce> Models.py class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing_bids") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_bids") bid = models.DecimalField(max_digits=22, decimal_places=2) class Meta: ordering = ('-bid',) def __str__(self): return f"£{self.bid} bid made for {self.listing.title} by {self.user.username}" Forms.py class Minval(): def getminv(id): listing = Listing.objects.get(id=id) minv = listing.listing_bids.first().bid return minv class BidListing(forms.ModelForm,id): class Meta: minval = Minval.getminv(id) model = Bid fields = ('bid',) labels = {'bid': '',} widgets = {'bid': forms.NumberInput(attrs={'min':minval}) } Views.py def listing(request, id): return render(request, "auctions/listing.html", { "bid_listing": BidListing(id), }) -
Django 3.2 - django.db.utils.ProgrammingError: column "id" referenced in foreign key constraint does not exist
I am currently developping a django project, and I needed to move to PostgreSql databases. I did it just like this in my settings.py file: DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.postgresql_psycopg2', 'NAME' : 'lifeplaner', 'USER' : 'postgres', 'PASSWORD': <my_password>, 'HOST' : 'localhost', 'PORT' : '5432', } } I deleted all my migration directories and ran python manage.py makemigrations and python manage.py migrate, but I am getting this error (which is didn't occur when I was using sqlite3): (life-planer-app-env) C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\LifePlaner>python manage.py migrate Operations to perform: Apply all migrations: Calendar, Manager, ToDoList, admin, auth, contenttypes, django_celery_beat, django_celery_results, sessions Running migrations: Applying ToDoList.0001_initial...Traceback (most recent call last): File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "id" referenced in foreign key constraint does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\commands\migrate.py", … -
Django How to pass signals in Abstract User model for create any custom model?
I have an Abstract user model. Where I have three type of user and I also have three custom model for three user. I want to pass signals in my Abstract user model for create my custom model. I have an custom model which name is MyAuthors. If I already have any user in my Abstract user model and save him as author but don't have any objects in MyAuthors model then it will create an objects in MyAuthors model for this user. I tried this code but didn't create user objects in MyAuthors model. class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class MyAuthors(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) is_blog_author = models.BooleanField(default=False) @receiver(post_save,sender=settings.AUTH_USER_MODEL) def user_objetcs(sender,instance,created,**kwargs): if created: author = MyAuthors.objects.filter(user=instance) #here I am checking does user have or not any profile in MyAuthors model. if not author: #if user don't have any objects in MyAuthors model then it will create MyAuthors.objects.create(user=instance,is_blog_author=instance.is_blog_authors) -
How to get two RichText features to be mutually exclusive
So basically I've added two custom features for coloring text to a RichTextBlock, and I'd like to make them so selecting one for a portion of text would automatically unselect the other color button, much like it's already the case for h tags. I've searched for a bit but didn't find much, so I guess I could use some help, be it advice, instruction or even code. My features go like this : @hooks.register('register_rich_text_features') def register_redtext_feature(features): feature_name = 'redtext' type_ = 'RED_TEXT' tag = 'span' control = { 'type': type_, 'label': 'Red', 'style': {'color': '#bd003f'}, } features.register_editor_plugin( 'draftail', feature_name, draftail_features.InlineStyleFeature(control) ) db_conversion = { 'from_database_format': {tag: InlineStyleElementHandler(type_)}, 'to_database_format': { 'style_map': { type_: {'element': tag, 'props': {'class': 'text-primary'}} } }, } features.register_converter_rule( 'contentstate', feature_name, db_conversion ) The other one is similar but color is different.