Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django translation get_language returns default language in detail api view
this is the api which sets language when user selects some language this works fine. class SetLanguage(APIView): def get(self, request, *args, **kwargs): user_language = kwargs.get("lan_code") translation.activate(user_language) response = Response(status=status.HTTP_200_OK) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) request.session[LANGUAGE_SESSION_KEY] = user_language return response viewset here with this viewset only in the api blog/{id} the function get_language returning default language code but on other api it working properly. I am not being able to find the issue. What might gone wrong ? class BlogViewSet(ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerilizer detail_serializer_class = BlogDetailSerializer def get_serializer_class(self): if self.action == "retrieve": return self.detail_serializer_class return super().get_serializer_class() def list(self, request, *args, **kwargs): queryset = Blog.objects.filter(parent=None) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) @action(detail=True, methods=["get"]) def childs(self, request, id): child_blogs = Blog.objects.filter(parent_id=id) serializer = self.get_serializer(child_blogs, many=True) return Response(serializer.data) model from django.utils.translation import get_language class MyManager(models.Manager): def get_queryset(self): current_language = get_language() print(current_language) return super().get_queryset().filter(language=current_language) class Blog(models.Model): title = models.CharField(_("Title"), max_length=100) objects = MyManager() -
How can I add two date fields in Django
Is it possible to add two date fields in Django models as single field. typically this field I have added from date range picker JavaScript picker which user can select from n to in the single field. Is any way to achieve it in Django -
'NoneType' object has no attribute 'transform'
AttributeError at /turboai/turboAI/jaaiparameters/ enter image description here def transform_data(df, cols, scaler, n_days_past=120): n_cols = len(cols) # df to np array np_arr = np.array(df.values.flatten().tolist()) np_arr = scaler.transform([np_arr]) np_arr = np_arr.reshape((np_arr.shape[0], n_days_past, n_cols)) return np_arr -
Couldnt save Modelform to database
I am trying to save the model form and getting error that foreign key column is not there. Error: column "connection_type_id" of relation "connection_details_test" does not exist ( There is no column connection_type_id, why its looking for this column, should I change my model?) Models: class ConnectionTypes(models.Model): connection_type_id = models.IntegerField(primary_key=True,default=re_sequence('connection_type_seq')) connection_type_name = models.CharField(max_length=100) connection_type_desc = models.CharField(max_length=300) connection_type_category = models.CharField(max_length=100) last_update_date = models.DateTimeField(default=dbcurr_ts) class Meta: managed = False db_table ='connection_types_test' verbose_name = 'connection_types_test' verbose_name_plural = 'connection_types_test' def __str__(self): return str(self.connection_type_id) class ConnectionDetails(models.Model): connection_id = models.IntegerField(primary_key=True,default=re_sequence('connection_seq')) connection_name = models.CharField(max_length=200) connection_type = models.ForeignKey(ConnectionTypes, on_delete=models.CASCADE) endpoint = models.CharField(max_length=100) port = models.IntegerField() login_id = models.CharField(max_length=100) login_password = fields.CharPGPPublicKeyField(max_length=100) connection_string_1 = fields.CharPGPPublicKeyField(max_length=100) connection_string_2 = fields.CharPGPPublicKeyField(max_length=100) connection_string_3 = fields.CharPGPPublicKeyField(max_length=100) aws_region = models.CharField(max_length=20) owner_id = models.IntegerField() last_update_date = models.DateTimeField(default=dbcurr_ts) working_schema = models.CharField(max_length=100) service = models.CharField(max_length=100) def generate_enc(mystrenc): return 'pass' class Meta: managed = False db_table = 'connection_details_test' verbose_name = 'connection_details_test' verbose_name_plural = 'connection_details_test' Model Form : class ConnectionForm(forms.ModelForm): login_password = forms.CharField(widget=forms.PasswordInput()) owner_id = forms.IntegerField(widget=forms.HiddenInput(), required=False) class Meta: model = ConnectionDetails exclude = ['connection_id','last_update_date'] View.py def addconnection(request): connectionform = ConnectionForm(request.POST or None) if connectionform.is_valid(): ownerqs = AuthUser.objects.values('id').get(username = request.user.username) connectionform.cleaned_data['owner_id'] = int(ownerqs['id']) connectionform.save() messages.success(request, f"sucess!") else: messages.success(request, f"Failure!") return render(request,'main/ssaddconnection.html',{"cform": connectionform,"CanUseMod":UserModules.objects.filter(user_id=request.user.id).filter(module_id=1).count(),"UserIsAuth":request.user.is_authenticated}) Anyone can help me on this?? Thanks, Aruna -
Get Foreign Key objects in the query
I have two models. The first one represents different Projects with a name, an ID and a description The second one is for tracking wich user is in wich Project. So my models look like this: from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True) project = models.ForeignKey('Project', on_delete = models.SET_NULL, null = True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id In the Userproject there there is only the UserID and the ProjectID, both are ForeignKeys to the other models. When I get a GET-Request with a username, I can get the userID , then I can filter all the Userprojects by the userID and serialize all those where the given ser is present. But How would I include the Project data as well If I want to send the name … -
Import-export module works not with User model for me in Django
I am trying to import new users to original User model form the Django admin site. I used to add the users one-by-one manually to the model but now I need to import lots of users and I need a solution to bulk import. I tried the code below, but I have an error: django.contrib.admin.sites.NotRegistered: The model User is not registered Please help me to solve this. admin.py from django.contrib import admin from django.contrib.auth.models import User from import_export.admin import ImportExportModelAdmin from import_export import resources class UserResource(resources.ModelResource): class Meta: model = User fields = ('id','username','first_name', 'last_name', 'email' 'password1', 'password2') class UserAdmin(ImportExportModelAdmin): list_display = ('id','username','first_name', 'last_name', 'email') resource_class = UserResource pass admin.site.unregister(User) admin.site.register(User, UserAdmin) -
django-ajax-selects autocomplete function doesn't work with inlineformset_factory
Is it possible to use the autocomplete function from django-ajax-selects (https://github.com/crucialfelix/django-ajax-selects) using inlineformset_factory? In my case the autocomplete doesn't work, when I write a letter it doesn't search anything... This is my forms.py: class FormulariMostra(ModelForm): class Meta: model = Sample fields = ("name", "sample_id_sex",) class FormulariPoolIndexList(ModelForm): class Meta: model = SamplePoolIndexCand fields = ("pool_id", "index_id", "gene_cand_list_id",) pool_id = AutoCompleteSelectField('pool_tag') index_id = AutoCompleteSelectField('index_tag') gene_cand_list_id = AutoCompleteSelectField('list_tag') PoolIndexListFormset = inlineformset_factory(Sample, SamplePoolIndexCand, form=FormulariPoolIndexList, extra=2,) My models.py: class Index(models.Model): id_index = models.AutoField(primary_key=True) index_name = models.CharField(max_length=30) index_id_index_type = models.ForeignKey(IndexType, on_delete=models.CASCADE, db_column='id_index_type', verbose_name="Tipus d'índex") index_id_index_provider = models.ForeignKey(IndexProvider, on_delete=models.CASCADE, db_column='id_index_provider', verbose_name="Proveïdor d'índex") miseq = models.CharField(max_length=9) nextseq = models.CharField(max_length=9) class Meta: db_table = 'index' unique_together = (("index_name", "index_id_index_type", "index_id_index_provider", "miseq", "nextseq"),) def __str__(self): return self.index_name class GeneCandList(models.Model): id_gene_cand_list = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=150, verbose_name="Llista de gens candidats") class Meta: db_table = 'gene_cand_list' def __str__(self): return self.name class Pool(models.Model): id_pool = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Pool") hibridation = models.BooleanField(verbose_name="Hibridació OK?") samples = models.ManyToManyField('Sample', through='SamplePoolIndexCand', blank=True, verbose_name="Mostres" class Meta: ordering = ['-id_pool'] db_table = 'pool' def __str__(self): return self.name class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe') indexes = models.ManyToManyField(Index, through='SamplePoolIndexCand', through_fields=('sample_id', 'index_id'), blank=True, verbose_name="Índexs") pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), … -
How to check if django admin is logged in or not?
I have a django project where I have 2 different login page. 1 is in the landing page. ex: https://website.com/ 2 is the django admin login. ex: https://website.com/admin/ For both the login, I am using the same postgres table. The requirement is, When I login from login page, if the user has access to admin, he should be able to login both landing page and admin page and vice versa. When I logout from any of the 2 logins, it should be able to logout from both the logins if the logged in user is same for both the logins. My login and logout code from the landing page @api_view(['POST']) def login(request): """ API for user login -> store username password using posted request.data -> check the username exists in database -> if username exists, authenticate the username,password and return response -> if username does not exists, return response """ if request.method == 'POST' and request.data: data = request.data username = data['username'] password = data['password'] user = auth.authenticate(username=username, password=password) if (user is not None) and (user.is_active): auth.login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({"username": str(user), "token": token.key, "status": STATUS['SUCCESS'], "message": MESSAGE_SUCCESS['LOGIN']}, status=status.HTTP_200_OK) return Response({"status": STATUS['ERROR'], "message": MESSAGE_ERROR['LOGIN']}, status=status.HTTP_200_OK) @api_view(['POST']) @authentication_classes((TokenAuthentication,)) … -
What's the best or the most secure Authentication type in django authentication
I would like to know what the best and the most secure authentication is for django, for like a big social media app. Thanks in advance. -
Why the elif part in my if-else statement does not give me desired output even if the condition is True in Django?
I'm using a signal which was working perfectly fine earlier, when it had only one if part: @receiver(post_save, sender=Realization) def new_receivable_save(sender, instance, created, **kwargs): print('Sender: ', sender) print('Instance: ', instance) print('Instance expansion: ', instance.patient) print('Created?: ', created) print('---------------------------') pkg=Package.objects.filter(patient=instance.patient).order_by('-id').first() print('patient type: ', pkg.patient_type) print() rec=Receivables.objects.filter(patient=instance.patient).order_by('-id').first() print('expected value: ', rec.expected_value) print() print('deficit?', instance.deficit_or_surplus_amount<0) print() if created: if pkg.patient_type!='CASH' and instance.cash==False: if instance.deficit_or_surplus_amount<0: Receivables(patient=rec.patient, rt_number=rec.rt_number, discount=rec.discount, approved_package=rec.approved_package, proposed_fractions=rec.proposed_fractions, done_fractions=rec.done_fractions, base_value=rec.base_value, expected_value=instance.deficit_or_surplus_amount).save() print('The End') But I had another scenario and had to apply an elif and an else part too but that wouldn't work somehow. It looks like this now: @receiver(post_save, sender=Realization) def new_receivable_save(sender, instance, created, **kwargs): print('Sender: ', sender) print('Instance: ', instance) print('Instance expansion: ', instance.patient) print('Created?: ', created) print('---------------------------') pkg=Package.objects.filter(patient=instance.patient).order_by('-id').first() print('patient type: ', pkg.patient_type) print() rec=Receivables.objects.filter(patient=instance.patient).order_by('-id').first() print('expected value: ', rec.expected_value) print() print('deficit?', instance.deficit_or_surplus_amount<0) print() if created: if pkg.patient_type!='CASH' and instance.cash==False: if instance.deficit_or_surplus_amount<0: Receivables(patient=rec.patient, rt_number=rec.rt_number, discount=rec.discount, approved_package=rec.approved_package, proposed_fractions=rec.proposed_fractions, done_fractions=rec.done_fractions, base_value=rec.base_value, expected_value=instance.deficit_or_surplus_amount).save() print('The End') elif pkg.patient_type == 'CASH': print('patient type: ', pkg.patient_type) print() if instance.deficit_or_surplus_amount<0: print('deficit?', instance.deficit_or_surplus_amount<0) Receivables(patient=rec.patient, rt_number=rec.rt_number, discount=rec.discount, approved_package=rec.approved_package, proposed_fractions=rec.proposed_fractions, done_fractions=rec.done_fractions, base_value=rec.base_value, expected_value=instance.deficit_or_surplus_amount).save() print('The End') else: pass The if part says that if the patient is using some Government scheme instead of cash payment run the code below. The elif part … -
How to get user first login time and last logout time ,everyday?
all user login & logout number of time, everytime the datetime is storing into the db but i need everyday first logintime and last logout time of every user? models.py class AllLogout(models.Model): user = models.ForeignKey(Account,on_delete= models.CASCADE) login_time = models.DateTimeField(null=True) logout_time = models.DateTimeField(null=True) def __str__(self): return str(self.user) + ': ' + str(self.logout_time) views.py This is my view function @login_required(login_url='login') @allowed_users(allowed_roles=['Manager', 'Admin']) def welcome(request): # list of agent ids im getting data1 = Account.objects.filter(Role='Agent').values_list('id', flat=True) startdate = date.today() enddate = startdate + timedelta(days=5) some_day_last_week = timezone.now().date() - timedelta(days=7) res = [] for agentname in data1: agentdata = AllLogout.objects.filter(user_id=agentname).filter(login_time__range=[startdate,enddate]) agentdata = AllLogout.objects.filter(user_id=agentname).values('logout_time') res.append(agentdata) print(agentdata) lasttime = [] for agentname in data1: agentdatalast = AllLogout.objects.filter(user_id=agentname).filter(logout_time__range=[startdate,enddate]).last() lasttime.append(agentdatalast) zippedList = zip(res, lasttime) return render(request, 'all_adminhtmlpages/welcome.html', {'zippedList': zippedList}) -
Ram size and deep learning model disk size in production
I am trying to host a deep learning model of size 1 GB on a server with ram 512. I am using django framework. But i have confusion, when a query is sent to model, first it load into the ram. So it will give out of memory error. This is my assumption. Is it true? if it is true is there a way to resolve this issue. -
Django REST, multiple querysets in one GET
I have the following two models: models.py: from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True) project = models.ForeignKey('Project', on_delete = models.SET_NULL, null = True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id The Userprojects 'user' and 'project' field point to the Usermodel and the Projectmodel above. Right now I have this view: class GetUserDataByNameView( APIView, ): def get(self, request, username): if User.objects.filter(username = username).exists(): uid = User.objects.get(username = username).id queryset = Userproject.objects.filter(user_id = uid) readSerializer = GetUserDataSerializer(queryset, many = True) return Response(readSerializer.data) else: return Response({"status": "error", "data":"no user with this username"}, status = 200) and this serializers from rest_framework import serializers from .models import Project from .models import Userproject class ProjectSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length = 500, required = True) descriptor = serializers.CharField(max_length = 1000, default = None) class Meta: model = … -
Django DataTable with Dynamic Models
I want to read a csv or text file then create a DataTable to allow users to search and filter the loaded file. I currently have pre-defined models for sample csv files but the challenge is not knowing what file format (columns) the user will load to view and query. Is there a way to simply load a file (csv or text) in Django then interact with the data (DataTables preferred) via the browser? Thanks I currently use https://github.com/morlandi/django-ajax-datatable and it's great but requires models to be pre-defined. -
Saving the all checkbox data in the database in django
I have created multiselect dropdown check in the UI part but only checkbox selection is saving in the database. For example: If user selects US, France, Germany in country dropdown checkbox only US is getting saved in the database. I don't know where I'm going wrong. views.py: def homeview(request): userb = Userbase.objects.all() table_data= requests.get('http://127.0.0.1:1500/api/').json() if request.method == 'POST': userb = Userbase() userb.company_code = request.POST.get('company_code') userb.Area = request.POST.get('area') userb.country = request.POST.get('country') # userb.Netdue_Date = request.POST.get('datefilter') userb.From_Date = request.POST.get('from_Date') userb.To_Date = request.POST.get('to_Date') userb.Predicted_Paid_days = request.POST.get('Predicted_Paid_days') userb.PBK_Desc = request.POST.get('PBK_Desc') userb.Vendor_Name = request.POST.get('Vendor_Name') userb.Reference = request.POST.get('Reference') userb.Payment_Term = request.POST.get('Payment_Term') userb.save() return render(request, 'home.html', {'userb':userb,'table_data':table_data}) html: <div class="form-group col-sm-9" style="margin-left: 19px; font-size: 17px;"> <label for="myMultiselect">Country</label> <div id="myMultiselect" class="multiselect"> <div id="mySelectLabel" class="selectBox" onclick="toggleCheckbox()"> <select class="form-select"> <!-- <select class="selectpicker"> --> <option>Select Country</option> </select> <div class="overSelect"></div> </div> <div id="mySelectOptions" name="country"> <label for="id_country_0"><input type="checkbox" name="country" id="id_country_0" onchange="checkboxStatusChange()" value="US" /> US</label> <label for="id_country_1"><input type="checkbox" name="country" id="id_country_1" onchange="checkboxStatusChange()" value="EMEA" /> EMEA</label> <label for="id_country_2"><input type="checkbox" name="country" id="id_country_2" onchange="checkboxStatusChange()" value="ASIA" /> ASIA</label> <label for="id_country_3"><input type="checkbox" name="country" id="id_country_3" onchange="checkboxStatusChange()" value="LATAM" /> LATAM</label> <label for="id_country_4"><input type="checkbox" name="country" id="id_country_4" onchange="checkboxStatusChange()" value="UK" /> UK</label> <label for="id_country_5"><input type="checkbox" name="country" id="id_country_5" onchange="checkboxStatusChange()" value="Ireland" /> Ireland</label> </div> </div> -
Display Charts based on year select in django
I am using django=3.0.0 as my backend. I have years in my database as a datetimefield and I want to put it as an option for my select button which will change the charts dynamically in chartjs. Do I have to make a filter for this or is there any other way to put my years in chartjs. Can anyone guide me how to do this? -
Django insert OTP code to display div on website
I am reading about Django otp framework and I've implemented it in my Django admin login panel. I was following steps from this site. However, I am wondering if it is possible to implement something like this directly on website. You have content that is visible for all logged in users but in order to show div[class="supercontent"] that is on the bottom of the page user has to click this div, provide phone nunmber and insert the code that will be sent on this number. -
Passing WSGI Request with eval()
I have functions to call that come in as string so I use def sayHi(parameterA, request): print("Hi") string_function_name = "sayHi" def call_dynamic_function(A, request): eval(string_function_name+"(parameterA='{}',request='{}')".format(A, request)) call_dynamic_function(A= string_function_name, request=request) The request I am trying to pass in is Http WSGI Request. However I get an error in trying to do so. SyntaxError: invalid syntax -
How to add pagination to search result page in Django?
Here is my code but it not working. I have added this code on m search result page for articles. i don't know whether i have done a mistake {% if all_searched_article.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ all_searched_article.previous_page_number }}" tabindex="-1"><i class="fa fa-angle-left"></i></a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1"><i class="fa fa-angle-left"></i></a> </li> {% endif %} {% for num in all_searched_article.paginator.page_range %} {% if all_searched_article.number == num %} <li class="page-item active"><a class="page-link" href="#">{{ num }}</a></li> {% elif num > all_searched_article.number|add:"-3" and num < all_searched_article.number|add:"3" %} <li class="page-item"><a class="page-link" href="?page={{ num }}">{{ num }}</a></li> {% endif %} {% endfor %} {% if all_searched_article.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ all_searched_article.next_page_number }}"><i class="fa fa-angle-right"></i></a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" ><i class="fa fa-angle-right"></i></a> </li> {% endif %} </ul> </div> -
Django looses session data
This is a very strange phenomenon which i have. My site works properly most of the time. But, from time to time (in the same session), some session info is not saved. i've added at the end of my view: request.session.modified = True and in my settings, added: SESSION_SAVE_EVERY_REQUEST = True Also tried in the view: request.session.save() Still - nothing helps. From time to time, session information is not stored. i look at the Dbase and i see that it is indeed not saved. im using django session with cached_db and PickleSerializer. Any idea? -
Async Django Rest Framework Examples
Does anyone have any examples on how I can make my DRF modelviews async? Reading the Django docs there is talk of making the views call() method async but I cannot find any examples of how I would do that. Also is there any examples of unit testing my async api call? I've been using unittest to run my tests, which doesn't support testing a coroutine? -
No file was submitted. Django Rest Framework React js
I have this model in django where it have a imageField and it works when I tested it on Postman but when I try to integrate it on React the payload message is that there's no file submitted. Here is my code: models.py class File(models.Model): ... def upload_to(instance, filename): return "posts/{filename}".format(filename=filename) class UploadedFile(File): file = models.ImageField(_("Image"), upload_to=upload_to) views.py class FileUploadedCreate(APIView): permission_classes = [permissions.IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): print(request.data) serializer = FileUploadSerializer(data=request.data) if serializer.is_valid(): serializer.save() return response.Response(serializer.data, status=status.HTTP_200_OK) else: return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class FileUploadSerializer(serializers.ModelSerializer): class Meta: model = UploadedFile fields = "__all__" react code ... const [uploadFile, setUploadFile] = useState(null); const onChange = (e) => { if ([e.target.name] == 'image') { setUploadFile({ file: e.target.files[0] }); } console.log(e.target.files); }; useEffect(() => {}, [uploadFile]); const handleUpload = () => { if (uploadFile) { if (selectedFolder !== 0) { let formData = new FormData(); formData.append('image', uploadFile); let url = 'http://localhost:8000/classroom/resources-file/upload'; axios .post(url, formData, { headers: { 'content-type': 'multipart/form-data', }, }) .then((res) => { console.log(res.data); }) .catch((err) => console.log(err)); console.log(uploadFile.file, uploadFile.file.name, selectedFolder); } else { alert('Please select folder for your file'); } } }; .... return ( <input accept='image/*' name='image' onChange={onChange} id='upload-file-button' type='file' /> <button onClick={handleUpload}> Submit </button> Please help … -
Show multiselectfield value in Bootstrap 4 multiselect dropdown in Django template
I am following this answer for the multi-selecting dropdown. I am using django-multiselectfield to collect data in the DB model. I want to show value in bootstrap multi-selecting dropdown but getting the below result I am seeking this result These are my code snippet model.py from django.db import models from multiselectfield import MultiSelectField class Country(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Person(models.Model): obj=Country.objects.all() TEAM=tuple((ob,ob) for ob in obj) name = models.CharField(max_length=124) southasia=MultiSelectField(max_length=200, choices=TEAM) def __str__(self): return self.name views.py from django.http import JsonResponse from django.shortcuts import render, redirect, get_object_or_404 from .forms import PersonCreationForm from .models import Person def person_create_view(request): form = PersonCreationForm() if request.method == 'POST': form = PersonCreationForm(request.POST) if form.is_valid(): form.save() return redirect('person_add') return render(request, 'miracle/index.html', {'form': form}) forms.py from django import forms from .models import Person class PersonCreationForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) template {% load crispy_forms_tags %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <title>Dependent Dropdown in Django</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script> </head> <body> <h2>Person Form</h2> <form method="post"> {% csrf_token %} {{ … -
How to call another websocket function in django channels consumer functions?
I have following code in consumers.py def websocket_receive(self,event): print(f'[{self.channel_name}] - Recieved message - {event["text"]}') async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'text': event.get('text') } ) def websocket_message(self,event): print(f'[{self.channel_name}] - message Sent - {event["text"]}') self.send({ 'type':'websocket.send', 'text':event.get('text') }) I want to call the message function whenever a message is recieved so in websocket_recieve function I have addes 'type': 'websocket.message', but I don't know why websocket_message function is not being called? I am new to django channels. any help will be appreciated. -
How to configure multiple language in my django model?
Here I want to give users to select languages while creating model objects. For this I tried like this. Is this way there will be any problems ? And I think I should have to migrate MyModel each time if new language option gets added in the project setting ? What any other options would be better for this scenario ? note: I don't want to use third party packages. settings import os gettext = lambda s: s LANGUAGES = [ ("en-us", gettext("English")), ('de', gettext('German')),] models def get_project_languages(): languages = settings.LANGUAGES languages_choices = [] for lang in languages: languages_choices.append((lang[0], lang[1])) return languages_choices language_choices = get_project_languages() class MyModel(models.Model): language = models.CharField(choices=languages_choices) content = models.TextField()