Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF protection to a view with a download api request
I have this view in my application that calls an api to download a pdf: @login_required def generateContractPdf(request): file_id = request.POST.get('contract') contract_id = request.POST.get('contract') payload = {"file_id": file_id} data = {"data": json.dumps(payload, default=str)} headers = {'content-type': 'application/json'} brokkr = os.environ.get("BROKKR_ADDRESS", default='localhost') response = requests.post('http://'+brokkr+':5000/contract', params=data, headers=headers) filename=str(contract_id)+".pdf" response = HttpResponse(response.content, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="'+filename+'"' return response But I just realiced that if I dont use render() the csrf doens't work, so this view could be exploited. How can i transforme it to keep that protection? -
how to display a list of colleges based on the percentage in Django-FormWizardView
I have a three-page form-list coming out of a single model and I want to display Colleges depending on percentage selection in the second step but it displays a list of all colleges from the database in the third step. how to display a list of colleges based on the percentage in Django-FormWizardView Here is my models.py class Percentage(models.Model): number = models.CharField(max_length=100) def __str__(self): return self.number class College(models.Model): percentage = models.ForeignKey(Percentage, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Student(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) firstname = models.CharField(max_length=100,validators=[alphanumeric]) lastname = models.CharField(max_length=100,validators=[alphanumeric]) image=models.ImageField(upload_to='files/%Y/%m/%d', blank=True) percentage = models.ForeignKey(Percentage, on_delete=models.SET_NULL, null=True) college = models.ForeignKey(College, on_delete=models.SET_NULL, null=True) description=models.TextField(blank=True) def __str__(self): return self.firstname forms.py class FirstForm(forms.ModelForm): id = forms.IntegerField(widget=forms.HiddenInput, required=False) firstname = models.CharField(max_length=100,validators=[alphanumeric]) class Meta: model = Student fields = ('firstname',) class SecondForm(forms.ModelForm): lastname = models.CharField(max_length=100,validators=[alphanumeric]) image = forms.ImageField(required=False) class Meta: model=Student fields=('lastname','image','percentage') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['percentage'].widget.attrs={ 'id': 'percentage', 'label':'percentage', 'name': 'percentage'} def save(self, commit=True): user = super(SecondForm, self).save(commit=False) user.percentage = self.cleaned_data['percentage'] if commit: user.save() return user class ThirdForm(forms.ModelForm): description = forms.CharField(widget=forms.Textarea) class Meta: model = Student fields = ('college','description',) def __init__(self, *args, **kwargs): super(ThirdForm, self).__init__(*args, **kwargs) self.fields['description'].widget.attrs={ 'id': 'id_description', 'class': 'myDescriptionClass', 'name': 'myDescriptionName', 'placeholder': 'myDescriptionholder'} self.fields['college'].widget.attrs = {'id': 'college', 'label': 'college'} if 'percentage' in … -
When do you need to use iri_to_uri after using url_has_allowed_host_and_scheme in Django?
In the Django 3.0 release notes, this comment is made about url_has_allowed_host_and_scheme: To avoid possible confusion as to effective scope, the private internal utility is_safe_url() is renamed to url_has_allowed_host_and_scheme(). That a URL has an allowed host and scheme doesn’t in general imply that it’s “safe”. It may still be quoted incorrectly, for example. Ensure to also use iri_to_uri() on the path component of untrusted URLs. I understand what the purpose of url_has_allowed_host_and_scheme is. Take the common use-case of providing a next query parameter, for example: http://example.com/foobar?next=http%3A%2F%2Fexample2.com%2Fhello . You could program the view that handles this path to redirect to the URL provided by the next parameter, in this case: http://example2.com/hello . If the URL is not validated, then this is an "open redirect" vulnerability. Malicious actors could take advantage of an open redirect to hide malicious URLs behind a URL that looks trustworthy. You can use url_has_allowed_host_and_scheme to ensure that the URL has the expected hostnames and scheme. My question is concerning iri_to_uri. The documentation implies that you also need to use this function as well. When would I need to use it? -
How to prevent your free tier heroku app from idling(python/django)
Is there any way, through code, to prevent your app from idling? I'm thinking something like what is being done here. How to do this through code, but in python/django as that is what my app is done in, i.e. what is the equivalent in python to Node's setInterval. What are the disadvantages of using a pinging service over doing it through code(other than if the site goes down your app wont get pinged). Can you recommend a good pinging service? Thanks in advance. -
Models not ready when using import-export ModelResource in tasks,py
I am trying to use a celery job to import data. As my data structure is rather complicated I can't really use import-export-celery by timthelion. When I import my ModelResource into tasks.py I get django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. due to File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 747, in __new__ readonly=False) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 895, in field_from_django_field FieldWidget = cls.widget_from_django_field(django_field) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 861, in widget_from_django_field result = getattr(cls, result)(f) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 841, in get_fk_widget model=get_related_model(field)) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 47, in get_related_model if hasattr(field, 'related_model'): File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/django/db/models/fields/related.py", line 95, in related_model apps.check_models_ready() Resource: from import_export import resources from bewertung.models import Optimierungsergebnis class testResoruce(resources.ModelResource): class Meta: model = TestModel Edit: The issue only arises if TestModel has a ForeignKey if have double checked celery.py and tried to use django.setup() as other posts on similar errors had suggested. -
How to connect iphone to a local server running on mac?
I am running a django server at localhost:8000 to accces it from iPhone i had connected the iphone and mac to the same network. ifconfig |grep inet inet 127.0.0.1 netmask 0xff000000 inet6 ::1 prefixlen 128 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 inet 127.94.0.1 netmask 0xff000000 inet 127.94.0.2 netmask 0xff000000 inet6 fe80::aede:48ff:fe00:1122%en5 prefixlen 64 scopeid 0x4 inet6 fe80::10a0:e008:9d34:5f7e%en0 prefixlen 64 secured scopeid 0x6 inet 192.168.43.234 netmask 0xffffff00 broadcast 192.168.43.255 inet6 2401:4900:2320:f3e9:10a0:ab34:c773:1104 prefixlen 64 autoconf secured inet6 2401:4900:2320:f3e9:b444:77e0:94f:8ccc prefixlen 64 autoconf temporary inet6 fe80::b4ed:bff:feba:10c2%awdl0 prefixlen 64 scopeid 0x8 inet6 fe80::b4ed:bff:feba:10c2%llw0 prefixlen 64 scopeid 0x9 inet6 fe80::54e:e417:7879:b351%utun0 prefixlen 64 scopeid 0xf inet6 fe80::203b:4e44:1f36:a04c%utun1 prefixlen 64 scopeid 0x10 inet6 fe80::eaa6:a7d3:cf35:3fe1%utun2 prefixlen 64 scopeid 0x11 inet6 fe80::7604:df44:d8c4:65be%utun3 prefixlen 64 scopeid 0x12 inet6 fe80::3e0f:e8c3:e7a:f96c%utun4 prefixlen 64 scopeid 0x13 inet6 fe80::3719:2c00:294b:88be%utun5 prefixlen 64 scopeid 0x16 After running the ifconfig command i took out the ip adress of the mac i.e. 192.168.43.234. And using this address in safari i am not able to access the server from iphone. -
How to limit the inline ForeignKey queryset to the instance itself in Django admin
I have 5 models and their relations are as follows: class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A) class C(models.Model): b = models.ManyToManyField(B) class D(models.Model): pass class I(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) c = models.ForeignKey(C) d = models.ForeignKey(D) I decide to use the django admin class IAdminInline(admin.TabularInline): pass class DAdmin(admin.ModelAdmin): inlines = [IAdminInline, ] The admin page makes a lot queries,if too many I instances are related to D, which is time consuming. So I disable the Django default actions by setting the formfield_for_foreignkey: def formfield_for_foreignkey(self, db_field, request, **kwargs): field = super().formfield_for_foreignkey(db_field, request, **kwargs) field.choices = [] # django will not make any queries if set choices Instead, I use ajax to get the corresponding data, and use javascript to render the select widgets and bind actions , which make it easier to add data since these widgets are related to each other. Page loads faster but problem is that, the above code would clear I instances initial values that are apparently already existing in the change view page. I want to ask how can I render the existing inline object select widgets to their own values? I haven't find any solutions yet... -
What's CART_SESSION_ID holding?
I am following Django by example book. In settings.py CART_SESSION_ID = 'cart' in cart.py in cart app class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart``` if its a string then if not cart: block will never execute. i am unable to understand how CART_SESSION_ID is working here? -
How to display certain group users in template with generic views?
I am gradually learning class based views in django. Now I am trying django generic views. I can do this easily with function based views. Here I got confused on which methods(get_queryset or get_object or get_context_data) to override while using generic views for this task . class UserGroupDetail(generic.DetailView): model = Group context_object_name = 'group' template_name = 'user_groups/group_detail.html' # how to query the group's users template I can do like this for permissions. {% for permission in group.permissions.all %} .... {% endfor %} For users ?? -
ModuleNotFoundError in tkinter heroku
I'm getting the error and Im using heroku in my Proc-file i specified the app path is where is my wsgi file located i don't know why and another problem is im getting the error (import _tkinter # If this fails your Python may not be configured for Tk 2020-02-24T07:14:05.594389+00:00 app[web.1]: ModuleNotFoundError: No module named '_tkinter') - [ ] my error page -
DRY validation of query params for djangorestframework view
I want to create a view in django-rest-framework. This view would accept several custom query parameters, so it wouldn’t be based on any existing view. I want the query parameters to be available in the OpenAPI 3 schema for the purpose of type-checking in the TypeScript client. My questions are: How can I perform the validation of these parameters declaratively? Is using Serializer a good way to perform validation of a query string? How can I generate the corresponding part of the OpenAPI 3 schema in a DRY way? I see that the existing drf views don’t use a DRY pattern here (they just return a static directory for schema). Also, the method that generates schema for Serializers is underscore-prefixed, so it might not be a good idea to use it directly (although I don’t know the rationale for this). So what are my options here? -
Alternative for drf-expander
I am using drf-expander for in-line expansions using expandable_fields. However, I have observed that for huge databases, the performance of drf-expander is limitied. Is there an alternative to drf-expander that can help me perform inline expansions more optimally (faster)? -
Django : AttributeError: module 'profiles_api.views' has no attribute 'HelloViewSet'
AttributeError: module 'profiles_api.views' has no attribute 'HelloViewSet' Git Repo urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from profiles_api import views router = DefaultRouter() router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset') urlpatterns = [ path('hello-view/',views.HelloApiView.as_view()), path('', include(router.urls)), ] Please give your suggestion -
Apache/mod_wsgi ModuleNotFoundError
I am trying to host a Django website on an Ubuntu VPS with Apache/mod_wsgi. If I run it in embedded mode, the site loads. WSGIScriptAlias / /home/admin/web/mywebsite/myproject/wsgi.py WSGIPythonHome /home/admin/web/mywebsite/venv WSGIPythonPath /home/admin/web/mywebsite <Directory /home/admin/web/mywebsite/myproject> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> However, if I try to run it in daemon mode, I get an error: "ModuleNotFoundError: No module named 'myproject'". WSGIDaemonProcess myproject python-home=/home/admin/web/mywebsite/venv python-path=/home/admin/web/mywebsite socket-user=#1001 WSGIProcessGroup myproject WSGIScriptAlias / /home/admin/web/mywebsite/myproject/wsgi.py My WSGI file: import os from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' application = get_wsgi_application() If I run a manage.py command, it shows the same ModuleNotFoundError error in both embedded and daemon mode. What could possibly be wrong? -
invalid literal for int() with base 10: with Django
My model : I am getting invalid literal for int() with base 10 in Django it is working in perfectly in the shell class Category(models.Model): cat_id = models.IntegerField(primary_key=True) category_name = models.CharField(max_length=1000) created_at = models.DateField(auto_now=True ,max_length=30) def __str__(self): return self.category_name class Content(models.Model): content_id = models.AutoField(primary_key=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) content = models.CharField(max_length=5000) created_at = models.DateField(auto_now=True) def __str__(self): return self.content ** my view ** def create_blog(request): if request.method == 'POST': title = request.POST['title'] content = request.POST['content'] category = request.POST['category'] object_of_category = Category.objects.get(cat_id = (category)) save_post = Content(category = object_of_category, content =content) save_post.save() return redirect(create_blog,{'message':'Post created Successfully!'}) categories = Category.objects.all() return render(request ,'admin/create_blog.html', {'categories' : categories}) -
Django how to map LDAP group to django grup and automatically assign to user
I am wondering if there is possibility to map LDAP group with Django group and assign it automatically to user from LDAP group, OR if there is at least possibility that every new user logged and authenticated on via LDAP can be assign by default to specific group? I have 3 groups created via admin django page: ADMIN ENGINEER READER and i have 3 groups in LDAP: DSAPB2T_PASSED_ADMIN GSAFU3T_PASSED_ENGINEER GSAFU3T_PASSED_READER is there any possibility that when user from GSAFU3T_PASSED_ENGINEER group log in for the first time, will automatically be assign to ENGINEER django group? (same for ADMIN and READER) or if this is not possible or good solution, is there a possibility that every new user (authenticated form any of these 3 LDAP groups) will be automatically assigned to READER group? -
Django Writable fields and serializers error with foreign keys
Not sure what's going on here, but I can't seem to POST as expected. Here's the error I get: TypeError: Got a `TypeError` when calling `Upload.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Upload.objects.create()`. You may need to make the field read-only, or override the UploadSerializer.create() method to handle this correctly. My models.py: class Project(SoftDeletableModel, TimeStampedModel): id = models.AutoField(primary_key=True) name = models.CharField(max_length=511, blank=True) def __str__(self): return str(self.id) class Upload(TimeStampedModel): id = models.AutoField(primary_key=True) file = models.FileField(upload_to=random_filename("uploads-%Y%m%d")) upload_type = models.CharField(choices=AVAILABLE_UPLOAD_TYPES, max_length=127) project = models.ForeignKey(Project, on_delete=models.PROTECT, related_name="uploads") def __str__(self): return str(self.id) serializers.py: class UploadSerializer(serializers.ModelSerializer): class Meta: model = models.Upload # fields = ("file", "upload_type", "project") fields = "__all__" class ProjectSerializer(serializers.ModelSerializer): uploads = UploadSerializer(many=True, read_only=True) class Meta: model = models.Project # fields = "uploads" fields = "__all__" viewsets: class UploadViews(viewsets.ModelViewSet): serializer_class = UploadSerializer queryset = Upload.objects.all() class ProjectViews(viewsets.ModelViewSet): serializer_class = ProjectSerializer queryset = Project.objects.all() I can create projects as expected, but when I try to create uploads, I get the error as described before. Does this have to do with the foreign key? I'm confused what is/isn't writable here. I'm doing this through the django web UI -
What websites mostly used while working on python, django(drf, templates) and angular(typescript, html, css, boostrap, javascript)
what are the useful websites mostly used while working on python, django(drf, templates) and angular(typescript, html, css, boostrap, javascript). I have listed out few websites those are i commonly used. https://www.primefaces.org https://stackoverflow.com/ https://angular.io/ https://docs.python.org https://docs.djangoproject.com/ https://www.geeksforgeeks.org/ https://github.com/ https://dzone.com/ https://tortoisesvn.net/ https://www.django-rest-framework.org/ -
How can I combine two of them and create a new serializer with new fields
I am facing one issue with formating the response of DRF I am sharing my model Details here class Plan(AuditFields, Model): id = models.AutoField(primary_key=True) object_id = models.UUIDField( unique=True, editable=False, verbose_name='Public identifier') plan_name = models.CharField(max_length=255, blank=True) team = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name="%(app_label)s_%(class)s_team") class PlanDetail(AuditFields, Model): plan = models.ForeignKey( Plan, on_delete=models.CASCADE, blank=True, null=True) plan_stage = models.CharField(max_length=255, blank=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) status_of_plan = models.CharField(max_length=255, blank=True) Using the Above models I need to create a response like this . But I am facing some issues with this plan details : [ { "plan_stage": "Sample1", "status_of_plan": "Completed", "start_date": "2019-07-01", "end_date": "2019-07-01", }, { "plan_stage": "Sample2", "status_of_plan": "Not Commenced", "start_date": "2019-08-01", "end_date": "2019-08-31", }, { "plan_stage": "Sample3", "status_of_plan": "Not Commenced", "start_date": "2019-09-01", "end_date": "2019-09-30", }, { "plan_stage": "Sample4", "status_of_plan": "Not Commenced", "start_date": "2019-10-01", "end_date": "2019-10-31", }, { "plan_stage": "Sample 5", "status_of_plan": "Completed", "start_date": "2019-11-01", "end_date": "2019-11-30", }, { "plan_stage": "End Date (Final Report)", "status_of_plan": "Completed", "start_date": "2019-12-01", "end_date": "2019-12-31", } ] plan :{ "id" : 1. "object_id": 456789023456546, "plan_name" : "Sample", "team":['Sachin','Dravid'] } I am using two serializers and trying it ..... But its not works in this case class PlanningSerializer(ModelSerializer): '''THis is for Model Plan ''' team = TeamSerializer(many=True, read_only=True) … -
Intellj python test running Django environment separately
I have Django application inside IntelliJ IDE. I can run all Django tests by calling the Django Tests runner. But: This is a time consuming and not ideal for development, where you would like to rerun one test that fail, and not run all 1000 others that are ok. IntelliJ has options (UI) to run one test quickly, but this run python tests runner. I add DJANGO_SETTINGS_MODULE=... inside, but now I get other errors: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I was looking to solve this error and I only found : import django django.setup() inside Settings.py My problem with this is: I think this breaks normal behaviour of the app. App works normal for different environments. It doesn't call code after this setup inside settings, so secret_key and others are not installed This doesn't seam to be really related to tests, but is changing the whole app. So, I am looking for some settings, how to set the normal python tests, so that they will run as django tests. -
list_display rows in a table conditionally django
I have two tables Employee ----- username organisation_id email Organisation ------------ organisation_id company_name User_A->organisation_1 User_B->organisation_1 User_C->organisation_2 User_D->organisation_2 when user_A login he should only see User_A and User_B This code should be like below, logic is first we need to find the current user organization and conditionally display the results in admin page Django admin code admin.site.register(Employee, CustomUserAdmin) admin.site.register(Organization) class CustomUserAdmin(UserAdmin): def filter_view(request): current_user = request.user organization_id =employees.objects.get(id=current_user.id).organization_id List_display = ('username', 'email','Organizations.objects.filter(id=organization_id)') -
Single checkbox form not being submitted.Also getting a MultiValueDictKeyError while submission
<body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <h6><u>Please Fill up the details below (Note that required field are marked by '*' )</u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-show="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="bname" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="form-group"> <label for="phone">Aadhaar Number(Enclose copy of Aadhaar Card)*:</label> <input name="aadharno" class="form-control" id="aadhar" name="aadhar" pattern="^\d{4}\s\d{4}\s\d{4}$" placeholder="Enter Aadhar Card number with proper spacing" required> </div> </div> <!--logic for no--> <div ng-show="showHideTest=='false'"> <div class="form-group"> <label for="formGroupDistrict">Please provide any of the following Identity Card*:</label> <select name="idcard" id="formGroupDistrict" required> <option>Bank or Post Office photo passbook</option> <option>Voter ID Card</option> <option>Ration Card</option> <option>Kishan Photo Passbook</option> <option>Passport</option> <option>Driving License</option> <option>PAN Card</option> <option>MGNREGS Job Card</option> <option>Her husband's Employee Photo Identity Card issued by the government or any Public Sector Undertaking</option> <option>Any other Photo Identity Card issued by State Government or Union Territory Administrations</option> <option>Certificate of Identity with photograph issued by a Gazetted … -
Django shell not able to execute ORM query
I am using Django shell for debug purpose of my project by using command 'python manage.py shell'. I have found that I am not able to execute ORM queries from shell & getting below kind of error. from base.models import Template_Form, Template_Form_Field Template_Form_Field.objects.all() After executing above code in shell I am getting below error. Traceback (most recent call last): File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "base_template_form_field" does not exist LINE 1: ...ions", "base_template_form_field"."sequence" FROM "base_temp... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\query.py", line 250, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1100, in execute_sql cursor.execute(sql, params) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\production\siralo\siralo_py3\venv\lib\site-packages\django\db\backends\utils.py", … -
Filter is not working in Django Rest Framework
I would like to filter my data like assumes I have one model => User UserID UserName UserDescription What I want is=> If i select like => api/user/?userid=1 , It should return only userid == 1 result. If I select like => api/user/?username=test, It should return only username == test result. What I have done? I installed django-filter and add this REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } to setting.py and I test like that but why I get all of my records? even URL is select only userid = 1 api/user/?userid=1 and If I test with the wrong URL parameter and I got all records even the wrong parameter. I do the exact same way with this => https://www.django-rest-framework.org/api-guide/filtering/#generic-filtering -
how to display django form validation error message with ajax?
Here I want to display form validation error message with the help of ajax.For this I tried like this but there are some problems with this code. Here It displays the error message if not group is unique which is fine(works as I wanted) but I want to disappear this message after the user clears the name from input field(which is not happening now.) and if the user writes the unique group name I want to display some other message like "Ok" or something else. How can I do it ? def validate_group_name(request): group = request.GET.get('name') data = {'is_taken': Group.objects.filter(name__iexact=group).exists()} return JsonResponse(data) ajax <script> $("#id_group").change(function () { var form = $(this).closest("form"); $.ajax({ url: form.attr("data-validate-group-url"), data: form.serialize(), dataType: 'json', success: function (data) { if (data.is_taken) { $(".error").text("This group name already exists").show(); } } }); }); </script>