Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + Mongoengine - settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details
And here I am again. I am trying to connect my app to MongoDB as I want to implement a non-rel database. The application works fine with SQL3Lite and I was also able to use Djongo. Yet, I am planning to use MongoEngine models and therefore I am trying to use it as DB Engine. However, for whatever reason I receive an error settings. "DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details." Here is what I did: django-admin startproject projectname python manage.py startapp appname Models.py: from django.db import models from django.db.models.fields.related import ForeignKey from django.db.models.query import EmptyQuerySet from django.contrib.auth.models import User,AbstractUser, UserManager import datetime import mongoengine # Create your models here. class Project(mongoengine.Document): projectName = mongoengine.StringField() Settings.py mport os from pathlib import Path import mongoengine mongoengine.connect(db="testdatabase", host="mongodb+srv://<Username>:<Password>@cluster0.qspqt0a.mongodb.net/?retryWrites=true&w=majority") # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = secretKey # 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 testing doesn't recognize dirty_fields?
One of my models uses dirty_fields. The save method detects when the field scale_mode changes. Once this happens, it goes through all the related grade objects and changes the field score for each affected grade. The goal is if VSB is swapped with VSBPLUS, then APP is swapped with APP+. model: class GradeBookSetup(DirtyFieldsMixin, models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=CASCADE) VSB = 'VSB' VSBPLUS = 'VSBPLUS' SCALEMODE = [ ('VSB', 'BEG DEV APP EXT'), ('VSBPLUS', 'BEG DEV APP APP+ EXT'), ] scale_mode = models.CharField( max_length=7, choices=SCALEMODE, blank=True, default=VSB) def save(self, *args, **kwargs): super(GradeBookSetup, self).save(*args, **kwargs) if self.is_dirty(): dirty_fields = self.get_dirty_fields() if 'scale_mode' in dirty_fields: if self.scale_mode == "VSB": n = 0 objs = Grade.objects.filter(user=self.user) for grade in objs: if grade.score == "APP+": objs[n].score = "APP" n = n + 1 Grade.objects.bulk_update(objs, ['score']) elif self.scale_mode == "VSBPLUS": objs = Grade.objects.filter(user=self.user) for grade in objs: if grade.score == "APP": objs[n].score = "APP+" Grade.objects.bulk_update(objs, ['score']) class Grade(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) INCOMPLETE = 'I' BEGINNING = 'BEG' DEVELOPING = 'DEV' APPLYING = 'APP' APPLYINGPLUS = 'APP+' EXTENDING = 'EXT' score = models.CharField( max_length=4, blank=True, default=INCOMPLETE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) assessment = models.ForeignKey( Assessment, on_delete=models.CASCADE, null=True, blank=True) objective = … -
Passing object to Django custom filter
I am using Django 3.2 I am writing a moderation app, and I want to be able to display only approved values in my template. I want to be able to use the new filter like this: {{ moderated_object.field_name | approved }} This is what I have so far: from django import template register = template.Library() @register.filter(name='approved') def moderator_approved_field_value(moderated_object, fieldname): return moderated_object.approved_value(fieldname) As I have written the filter above, I can only use it like this: {{ moderated_object| approved: fieldname }} Which is ugly. Is there a way that I can pass the object to the function behind the scenes, so that I can use the cleaner way of using the filter in my template? -
Get all objects' django guardian permissions of the authenticated user in template
I have an application where I am using django-guardian for object-level permission. In my ListView, I am listing all my instances in a table. In each row, I need to show the edit button if the user has the permission to edit this object. So, I doing something like: {% extends "base.html" %} {% load guardian_tags %} {% block content %} <table> <thead>...</thead> <tbody> {% for i in items %} <tr> <td>{{ i.name }}</td> <td> {% get_obj_perms request.user for i as "i_perms" %} <!-- this one --> {% if "change_item" in i_perms %} <a href="{% url 'edit_item' i.id %}">Edit</a> {% endif %} </td> </tr> {% endif %} </tbody> </table> {% endblock %} Problem Doing it that way is not optimized solution from database-wise. This solution makes a database query for each object to get the user permissions. How can I do so but with a single hit to the database to get all the objects' user permissions? -
Is there a way to make the 'One' table optional in OneToManyRelationship in Django
I have two tables, one is Anonym the other is Userdatabase. I want my app to work without requiring any login info therefore it will work with Anonym only by using the deviceid of the user to process account information. If however, a user wants to access extra features they need to create a user with username/password. Then I will process the data using Userdatabase table. A user can have multiple devices so there is a OneToMany relationship in there, but a device doesn't have to have a User (they don't need to register) which breaks the relationship. Is there a way to make the Userdatabase table optional while keeping the OneToMany relationship? Perhaps by inserting a method or another class within UserDatabase? Please find the code below: --Models-- class Anonym(models.Model): deviceid=models.ForeignKey(Userdatabase,max_length=200,on_delete=models.SET_NULL,null=True) accounttype=models.TextField(default='Free') numberofattempts=models.IntegerField(default=0) created=models.DateField(auto_now_add=True) class Userdatabase(models.Model): username=models.CharField(max_length=20,unique=True) password=models.CharField(max_length=20) deviceid=models.TextField(default='inputdeviceid') accounttype=models.TextField(default='Free') numberofattempts=models.IntegerField(default=0) created=models.DateField(auto_now_add=True) --urls-- urlpatterns=[path('deviceregister/<str:id>/',views.deviceregistration)] --views-- def deviceregistration(request,id): import time deviceid=id newdevice-models.Anonym(created=time.strftime("%Y-%m-%d"),deviceid=deviceid) newdevice.save() return HttpResponse('Succesful registration') When I send a request as '/deviceregister/123456/' for example, django raises an ValueError saying Cannot assign "'123456'": "Anonym.deviceid" must be a "Userdatabase" instance. -
Adding onclick into the field that's created by adding can_delete to formset
How can I add onclick="functionName()" to the field that is created by using can_delete=True in formset? <input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE" onclick="functionName()"> -
Does UserRateThrottle get overridden by ScopedRateThrottle?
We have a number of endpoints that we need burst speeds for which seems to perfectly be what ScopeRateThrottle is for, but we also have a number of endpoints we want to generally rate-limit. Is UserRateThrottle compatible with ScopedRateThrottle? Does one override the other? For example, can ScopedRateThrottle have a higher number than UserRateThrottle? "DEFAULT_THROTTLE_CLASSES": [ "rest_framework.throttling.AnonRateThrottle", "rest_framework.throttling.ScopedRateThrottle", <--- Maybe this is evaluated by order? "rest_framework.throttling.UserRateThrottle", ], "DEFAULT_THROTTLE_RATES": { "anon": "20/hour", "user": "60/hour", "burst": "100/minute", }, -
Django 3.2.5 read-only DateTimeField
I'm trying to get to show the creation date of a model inside the Django administration, but everytime I use auto_now_add, it disappears from the user (superuser) view. In models.py: class Project(models.Model): readonly_fields=('creation_date', 'modified') project_id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) name = models.CharField(max_length=200) description = models.TextField(blank=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=datetime.now) #This is what I want to show modified = models.DateTimeField(auto_now=datetime.now) #I also want to show this one start_date = models.DateField(blank=True, null=True) # Orders the projects by date class Meta: ordering = ['start_date'] def __str__(self): return '{} - {}'.format(self.brand.customer.name, self.name) My admin.py: from django.contrib import admin from .models import Customer, Project, Brand, Supplier, Quotation, Expense admin.site.register(Customer) admin.site.register(Brand) admin.site.register(Project) admin.site.register(Supplier) admin.site.register(Quotation) admin.site.register(Expense) -
How to Pass the request to another Serializer for Validation
I have two tables in my database to insert a product record. I am storing the product info in the Product table and the rest of the info like Pirce, Quantity etc storing to another table which is ProductStock. I am planning to send the data to a server something like this. { "name":'product name', "brand":"socialcodia" "product_stock":{ "price":"100", "quantity":"50" } } I am easily able to validate the product info from ProductSerializer. But I don't have any perfect idea to validate the ProductStockSerializer data. ProductSerializer from rest_framework import serializers from .models import Product from .models import Medical class ProductSerializer(serializers.ModelSerializer): medical = serializers.CharField(read_only=True) id = serializers.CharField(read_only=True) is_visible = serializers.CharField(read_only=True,default=True) class Meta: model = Product fields = ['id','medical','category','item','brand','is_visible'] def validate(self, attrs): request = self.context.get('request') attrs['medical'] = Medical.objects.get(pk=request.info.get('medical')) return attrs Here I want to validate the product_stock info as well. cuz it's coming with a single request. So is there any way that i can import the ProductStockSerializer into ProductSerializer and pass the data to that serializer. then validate it. ProductStockSerializer from rest_framework import serializers from .models import ProductStock from medical.models import Medical class ProductStockSerializer(serializers.ModelSerializer): medical = serializers.CharField(read_only=True) class Meta: model = ProductStock fields = ['medical','distributer','product','variant','batch','purchase_price','price','quantity','location','low_stock','expire_date'] def validate(self, attrs): attrs['medical'] = Medical.objects.get(self.context.get('request').info.get('medical')) batch … -
Still getting validation error despite using save(commit=False)
Model form: class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['title', 'slug', 'category', 'description', 'thumbnail', 'status', 'author'] view: if request.method == 'POST': form = ArticleForm(request.POST, request.FILES) if not request.user.is_superuser: art = form.save(commit=False) # Error line art.author = request.user art.status = 'd' art.save() return HttpResponseRedirect(reverse('account:home')) elif form.is_valid(): form.save() return HttpResponseRedirect(reverse('account:home')) return render(request, 'registration/add-update-article.html', { 'form': form }) If the user is not a superuser, they can not fill some fields in the form so I want to set their values in this view. Isn't commit=False supposed to prevent raising validation errors? Why do I still get an error? -
'bytes' object has no attribute 'name' django
so i want read file txt what i was input. but the file became in bytes because i encode it. how to open the file and can be print out? i want to encrypt that message in the file txt. the error message like this f = open('media/txt/'+f.name, 'r') AttributeError: 'bytes' object has no attribute 'name' i was trying like this to read the file def read_file(f): f = f.encode("utf8") f = open('media/txt/'+f.name, 'r') file_content = f.read() f.close() print(file_content) and i called that function plaintext = Audio_store.objects.all().values_list('password').last() pt = plaintext[0] read_file(pt) -
Django using functions outside of classes
I have this model class model(models.Model): user_fk = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) JGB_A1 = models.IntegerField(default=0) JGB_B1 = models.IntegerField(default=0) JGB_C1 = models.IntegerField(default=0) JGB_D1 = models.IntegerField(default=0) JGB_E1 = models.IntegerField(default=0) Davon_E3 = models.CharField(max_length=100, blank=True, null=True) @property def sum_of_1(self): return self.JGB_A1 + self.JGB_B1 + self.JGB_C1 + self.JGB_D1 + self.JGB_E1 def __str__(self): return '{}'.format (self.user_fk) and I need the calculations displayed in another model for further calculations. The goal is to have models with values from users and another model which calculates everything together and display other values based on users values a lot of values. What are my options, I thought about singals or using functions outside of classes but trying that gave me instant a server error -
BooleanField in ModelSerializer
I want to display the content of Trader class through an API call. But I don't know where am I wrong. models.py class Trader(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="trader") bot_status = models.BooleanField(blank=False, default=False) active_group = models.ManyToManyField(Entry, blank=True, related_name="active_group") def __str__(self): return f'{self.user.username}' def __repr__(self): return f'Trader=(bot_status={self.bot_status}, active_group={self.active_group})' serializers.py class BotStatusSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source = 'user.username') class Meta: model = Trader read_only_fields = ('bot_status', ) views.py class BotStatusView(viewsets.ModelViewSet): serializer_class = BotStatusSerializer def get_queryset(self): return self.request.user.trader.bot_status When I make the request I get the following Error. Error: return [ TypeError: 'bool' object is not iterable -
How to download file using django as backend and nginx
I have a filefield in a document model from which i can upload files like this document=models.FileField(max_length=350 ,validators=[FileExtensionValidator(extensions)]) uploading is working good, now i want to implement download feature for the frontend, but only those files which are uploaded by the user. using url method is think less secure, another way i saw is creating download function in the views, and another i saw using nginx i can implement. Kindly guide me which method is best, and what steps to take to implement the download feature, and will i need docker too if i am using nginx? -
List of objects return empty - using django - mixins, generic views
views.py class ReviewList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Review.objects.all() serializer_class = ReviewSerializer def get(self,request,*args,**kwargs): return self.list(request, *args, **kwargs) def post(self,request,*args,**kwargs): return self.create(request, *args, **kwargs) models.py class Review(models.Model): rating = models.PositiveIntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) description = models.CharField(max_length=200, null=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) watchlist = models.ForeignKey(WatchList, on_delete=models.CASCADE, related_name='reviews') def __str__(self) -> str: return str(self.rating) + ' - ' + self.watchlist.title urls.py urlpatterns = [ path('list/', WatchListAV.as_view(), name='movie-list'), path('<int:pk>', MovieDetailsAV.as_view(),name='movie-details'), path('stream/',StreamPlatformAV.as_view(),name='stream-list'), path('stream/<int:pk>', StreamDetailAV.as_view(), name="stream-detail"), path('review/', ReviewList.as_view(),name='review-list'), ] serializers.py class ReviewSerializer(serializers.Serializer): class Meta: model = Review fields = '__all__' the list of reviews return empty as attached in photo the list of reviews is empty, im new to django cant figure it out -
Log with django rest framework [closed]
I'm working on a registration system, where I need to view all the changes that have been made to this registration. If the user changes the age, I need to see the before and after. Does anyone know a django rest framework function that does this? -
Django/Celery - Filter each task result with periodic_task_name
I am quit new to Celery. Here is my code for conifguring Celery Beat. app.conf.beat_schedule = { # EMAILS 'send-feedback-mail-every-2-weeks': { 'task': 'stocks.tasks.send_ask_feedback', 'schedule': crontab(day_of_week=6), }, 'get-terminal-data-frequently': { 'task': 'stocks.tasks.get_terminal_data_func', 'schedule': crontab(minute="*"), }, # NEWS 'get-newyorktimes-api': { 'task': 'stocks.tasks.get_news_nyt', 'schedule': crontab(minute="*"), }, I am wondering how to query the associated tasks for the periodic task 'get-newyorktimes-api' in my view to pass the result of each into the context. I tried: context['celery'] = TaskResult.objects.filter(periodic_task_name='get-newyorktimes-api') It returned an empty queryset eventhough I've ran the task successfully multiple times. Where is my fault in this Task filter? -
InvalidCursorName, ProgrammingError, OperationalError related to postgres cursor while changing model
When we moved from aws to local provided we started to observe these three errors. It appears randomly while changing model. InvalidCursorName /core/family/{object_id}/change/ cursor "_django_curs_140667503112576_sync_1371" does not exist ProgrammingError /core/family/{object_id}/change/ cursor "_django_curs_140667503112576_sync_1139" already exists OperationalError /core/family/{object_id}/change/ cursor "_django_curs_140667503112576_sync_4004" does not exist This problem doesn't appear on our staging server, I can't neither reproduce it locally. Any ideas? -
django - get data from db and update him - how to take the last data and update, i get the data with CartOrder.objects.last()
i want that the paid status will be true on the last order i can filter the data but how i am changing him ? my views.py file: def payment_done(request): a = CartOrder.objects.last() orders = CartOrder.objects.filter(paid_status=a.paid_status) return render(request, 'payment-success.html',{'orders':orders}) my models.py file: class CartOrder(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) total_amt = models.FloatField() paid_status = models.BooleanField(default=False) order_dt = models.DateTimeField(auto_now_add=True) -
Best practices of choice sort in django
I believe everyone knows Counter Strike Global Offensive (CS:GO). So there we have weapons divided by types (Pistol, SMG, Rifle, Heavy). Each type has several weapons (e.g. AK-47, M4A4, AWP are Rifle-type weapons. I have the following model in my Django project: class Weapon(models.Model): WEAPONS = ( ('AK-47', 'AK-47'), ('M4A4', 'M4A4'), ... ) QUALITY_CONSUMER_GRADE = 'CONSUMER GRADE' QUALITY_INDUSTRIAL_GRADE = 'INDUSTRIAL GRADE' QUALITY_MIL_SPEC = 'MIL-SPEC' QUALITY_RESTRICTED = 'RESTRICTED' QUALITY_CLASSIFIED = 'CLASSIFIED' QUALITY_COVERT = 'COVERT' QUALITY = ( (QUALITY_CONSUMER_GRADE, 'Consumer grade'), (QUALITY_INDUSTRIAL_GRADE, 'Industrial grade'), (QUALITY_MIL_SPEC, 'Mil-spec'), (QUALITY_RESTRICTED, 'Restricted'), (QUALITY_CLASSIFIED, 'Classified'), (QUALITY_COVERT, 'Covert') ) CATEGORY_NORMAL = 'NORMAL' CATEGORY_STATTRAK = 'STATTRAK' CATEGORY = ( (CATEGORY_NORMAL, 'Normal'), (CATEGORY_STATTRAK, 'StatTrak') ) TYPE_PISTOL = 'PISTOL' TYPE_HEAVY = 'HEAVY' TYPE_SMG = 'SMG' TYPE_RIFLE = 'RIFLE' TYPE = ( (TYPE_PISTOL, 'Pistol'), (TYPE_HEAVY, 'Heavy'), (TYPE_SMG, 'SMG'), (TYPE_RIFLE, 'Rifle') ) EXTERIOR_FACTORY_NEW = 'FACTORY NEW' EXTERIOR_MINIMAL_WEAR = 'MINIMAL WEAR' EXTERIOR_FIELD_TESTED = 'FIELD-TESTED' EXTERIOR_WELL_WORN = 'WELL-WORN' EXTERIOR_BATTLE_SCARRED = 'BATTLE-SCARRED' EXTERIOR = ( (EXTERIOR_FACTORY_NEW, 'Factory New'), (EXTERIOR_MINIMAL_WEAR, 'Minimal Wear'), (EXTERIOR_FIELD_TESTED, 'Field-Tested'), (EXTERIOR_WELL_WORN, 'Well-Worn'), (EXTERIOR_BATTLE_SCARRED, 'Battle-Scarred') ) name = models.CharField(max_length=64, choices=WEAPONS, default=WEAPONS[0][0]) exterior = models.CharField(max_length=64, choices=EXTERIOR, default=EXTERIOR[0][0]) quality = models.CharField(max_length=64, choices=QUALITY, default=QUALITY[0][0]) category = models.CharField(max_length=64, choices=CATEGORY, default=CATEGORY[0][0]) type = models.CharField(max_length=64, choices=TYPE, default=TYPE[0][0]) price = models.FloatField() slug = models.SlugField(max_length=256, unique=True, editable=False) What is the best practice … -
Group_by in django with a Foreign key field
I've these model: class Student(models.Model): name = models.CharField(max_length=255) school = models.CharField(max_length=255) class Question(models.Model): question_text = models.CharField(max_length=255) correct_count = models.Integer_Field() incorrect_count = models.Integer_Field() class Answer(models.Model): question = models.ForeignKey(Question, related_name='answer_question', on_deleted=models.CASCADE) text = models.CharField(max_length=255) is_correct = models.BooleanField() class Quiz(models.Model): name = models.CharField(max_length=255) month = models.DateField() class QuizQuestion(models.Model): quiz = models.ForeignKey(Quiz, related_name='quiz_question_quiz', on_deleted=models.CASCADE) questions = models.ManyToManyField(Question, related_name='quiz_student') class QuizAnswer(models.Model): student = models.ForeignKey(Student, related_name='quiz_answer_student', on_deleted=models.CASCADE) question = models.ForeignKey(Question, related_name='quiz_answer_question', on_deleted=models.CASCADE) answer = models.ForeignKey(Answer, related_name='quiz_answer_answer', on_deleted=models.CASCADE) quiz = models.ForeignKey(Quiz, related_name='quiz_answer_student', on_deleted=models.CASCADE) marks = models.IntegerField() It's related to a contest in which students from different schools participate. Quiz contest will have multiple choice questions and student selects one answer which gets stored in our QuizAnswer table with question id, answer id, user id, quiz id and if the answer is correct our Question model's correct_count gets incremented otherwise incorrect count get incremented. Now I want to get top 5 schools whose students gave most correct answers with their percentage in descending order. How can I write a query for this? -
Default image didn't change Django
I try to make avatar upload in Django project. I made changes in templates and in models, but the default image does not change to a new one. What could be the problem? model.py class Person(models.Model): avatar = models.ImageField(upload_to="img", null=True, blank=True) template.html {% if person.avatar.url %} <th scope="row"><img height="50" width="50" src="{{ person.avatar.url }}" alt="no image" title="avatar"> {% else %} <th scope="row"><img height="50" width="50" src="{% static "img/default_avatar.jpg" %}" alt="no image" title="avatar"> {% endif %} -
Django Migration MySql to Postgres - IntegrityError
I am trying to migrate a fairly big Django project from using MySql to using Postgres. I am doing that locally for now and I was following the instructions of this guide here I found on the web. After installing the psycopg library correctly I can't execute the existing migrations over the new postgres Database because I get integrity errors. The error would look like this: django.db.utils.IntegrityError: Problem installing fixture '/home/user/project/venv/lib/python3.6/site-packages/allsports/core/fixtures/competitiontype.json': Could not load core.CompetitionType(pk=None): (1062, "Duplicate entry 'season' for key 'name'") and it is thrown when The python manage.py migrate command reaches the first migration that loads some data with the loaddata command from a file that looks like this: [ {"model": "core.competitiongrouptype", "pk": null, "fields": {"name": "conference"}}, {"model": "core.competitiongrouptype", "pk": null, "fields": {"name": "division"}}, {"model": "core.competitiongrouptype", "pk": null, "fields": {"name": "playoff series"}} ] I wanted to know if anybody had this error and whether it is because Postgres manages keys differently. If so any Idea on how to migrate the data from Mysql to Postgres? -
In django-taggit tag is not save along with question post
when I created djanog question models all the fields are created but tag is not created with question model but separately tags are created in django admin taggit model.py class Question(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False) nameuser = models.ForeignKey(Profile,on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = RichTextUploadingField() tag = TaggableManager() def __str__(self): return self.content class Meta: ordering = ['-timestamp'] view.py def createQue(request): User = request.user.profile form=QuestionForm() if request.method =='POST': form=QuestionForm(request.POST,request.FILES) if form.is_valid(): content = form.cleaned_data["content"] tag = form.cleaned_data["tag"] print(tag) blog = form.save(commit=False) blog.nameuser=User blog.content = content blog.tag=tag blog.save() return redirect('home') context={'form':form} return render(request,'blog_form.html',context) forms.py class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ['content','tag'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['content'].widget.attrs.update({'class':'form-control ','placeholder':'Enter your question'}) self.fields['tag'].widget.attrs.update({'class':'tag_inputbar','placeholder':'Enter Tags here'}) -
Change schema on views using Django Tenants
I'm using Django Tenants on my project and I'm creating a schema for each Tenant. I have 'django.contrib.auth' and 'django.contrib.contenttypes' both in SHARED_APPS and in TENANT_APPS, and now I want to create specific groups in each tenant schema. The problem is that I'm always reading and writing values from the public schema. I implemented the following: DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASS', 'HOST': 'DB_HOST', 'PORT': 'DB_PORT', } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) How can I change to a different schema? Can I do it on an app views?