Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ckeditor Automatically Save Data to Server / Backend
How would I go about automatically saving data from frontend ckeditor to the backend without reloading the page. I tried using ajax to make this work, but I am unable to send the updated content to the backend. Additionally, the javascript on change method is triggering 2x per single input. For example if I type "A" for a new input in ckeditor, it'll trigger twice for some unknown reason. Approach 1 - HTML / JS (Click "submit" button when change is detected) <form class="pt-2" action="#" method="POST" id="designer-form"> {% csrf_token %} {{ form.media }} {% for field in form %} {{ field }} {% endfor %} <div class="mt-4 flex justify-end space-x-4"> <button type="submit" id="submit"> Save Changes </button> </div> </form> <script> CKEDITOR.on('instanceCreated', function(event) { let editor = event.editor; editor.on('change', function() { setTimeout(function () { document.getElementById("submit").click(); }, 2500); }); }); </script> Approach 2 - HTML / JS (Serialize Data) <form class="pt-2" action="#" method="POST" id="designer-form"> {% csrf_token %} {{ form.media }} {% for field in form %} {{ field }} {% endfor %} <div class="mt-4 flex justify-end space-x-4"> <button type="submit" id="submit"> Save Changes </button> </div> </form> <script> CKEDITOR.on('instanceCreated', function(event) { let editor = event.editor; editor.on('change', function() { let data = editor.getData(); setTimeout(function (){ $.ajax({ … -
Check user doesn't already have this object before displaying CreateView - Prevent them from creating multiples
I've been slowly learning Django over the past few weeks, and applying it to a work prototype. I have a simple profile model called Applicant. This stores personal fields for the a customer. It contains a OnetoOne field linking to the Django Auth User model, as I'm using this to require login and control access to data. I'm struggling to figure out how to perform checks within View Classes (seemed easier within View Functions), I need a way to check if a user already has an Applicant entry before presenting them with the CreateView form. Previously to display this Applicant profile data (created via admin page), I used the get_object_or_404 within the DetailView.get_object to catch Http404 and return None if they didn't have a profile. This would then provide a link to the Create page. I need to implement the reversed logic on the CreateView, to protect them from creating multiple Applicant entries. Any suggestions would be great, even just to point me in the right direction. Code I used for DetailView: class ApplicantProfileDetailView(LoginRequiredMixin, generic.DetailView): model = Applicant template_name ='profile.html' def get_object(self, queryset=None): try: return get_object_or_404(Applicant, user=self.request.user) except Http404: return None <h1>Applicant Profile</h1> {% if applicant %} ... {% else … -
Letting the user Select a Font-Family in Django Web Application
I am in the process of building a Django Web Application that lets a user customize different CSS options for their webpage in the Django Admin Web Interface. Currently, the admin user has the option to change the color, background-color, and font-family. I used Django forms to create a Color Selector Widget so the user doesn't have to type in a hex color value and type in the name of a font. I am trying to create a widget to let the user select a font from a list of font-familys. I've looked into tkinter and listboxes but it appears it is best for GUIs. Should I just create a list of choices and populate it with a bunch of fonts? I have been having a hard time coming up with a viable efficient option. forms.py class cssForm(ModelForm): class Meta: model = styleEditor fields = "__all__" widgets = { "Link_Color": TextInput(attrs={"type": "color"}), "Link_Background_Color": TextInput(attrs={"type": "color"}), } models.py class styleEditor(models.Model): Link_Color = models.CharField(max_length=7, default="#000000") Link_Font_Style = models.CharField(max_length=15, default="Brush Script MT") Link_Background_Color = models.CharField(max_length=7, default="#F5F5F5") admin.py @admin.register(styleEditor) class styleEditor(admin.ModelAdmin): form = cssForm -
Django how to compere calculated fields in query
Is it possible to get data from another table in a query by comparing calculated values? Like for example, by calculating using the minimum and maximum price values and getting Url's to them from another table. My models look like this: class Product(models.Model): id = models.CharField(..) price = models.FloatField(..) url = models.CharField(..) ..... class ProductHistory(models.Model): ProductID = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='ProductID', db_column='ProductID') price = models.FloatField(..) date = models.DateTimeField(..) My request looks like this query = HistoryPrice.objects.filter(ProductID=products).filter(query_price) \ .annotate(dt=Trunc('StartDate', frequency)) \ .values('dt') \ .annotate(max_price=Max('Price'), min_price=Min('Price')) \ .order_by('dt') But i want to get Url from Product table for each max_price for given period. How can i achieve it -
How can I solve ValueError in django. Exception Value: ModelForm has no model class specified
This is my code; django.models. my model.py file from django.db import models class Product(models.Model):title = models.CharField(max_length=150) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=100000) summary = models.TextField(blank=True, null=False) featured = models.BooleanField(default=False) forms.py That's my full form.py file from django import forms from .models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = [ 'title', 'description', 'price', ] class RawProductForm(forms.ModelForm): title = forms.CharField() description = forms.CharField() price = forms.DecimalField() **django.views** my django.views file from django.shortcuts import render from .models import Product from .forms import ProductForm, RawProductForm def product_create_view(request): my_form = RawProductForm() if request.method == 'POST': my_form = RawProductForm(request.POST) if my_form.is_valid(): print(my_form.cleaned_data) Product.objects.create(**my_form.cleaned_data) else: print(my_form.errors) context = {'form': my_form} return render(request, "products/product_create.html", context) **products_create.html** #this is my html file {% extends 'base.html' %} {% block content %} <form action="." method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> {% endblock %} In his code I'm trying to make a form but when I run python manage.py runserver at http://127.0.0.1:8000/create/ I'm getting ValueError This is a screenshot of my full error messagae -
where is the data saved during Django stack development
Maybe this is a super silly question. I am new with Django stack web app development. I am following Django tutorial on MDN. I entered information to the backend database via the admin page. But some error happened later so I had to uninstall pyenv and restart. I wonder if I can find all the information I entered which is not on any project documents. Thanks. -
Django Debug Toolbar causes 404 error in DEBUG mode
After installing Django Debug Toolbar and adding all setting, I'm getting 404 error. I did command collectstatic, but that did not help. Here is my files: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) .... INSTALLED_APPS = [ ... 'debug_toolbar', ... ] MIDDLEWARE = [ ... 'debug_toolbar.middleware.DebugToolbarMiddleware', ] ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'spare_part/static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('mileage.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) What to do? -
how to present donut type percentages using django and chart.js
how to present donut type percentages using django and chart.js. with the code below I just got the text of the title. The percentages being calculated and displayed in the terminal when I add the print instruction, for example print(data1). i use filter and count for the percentage of evens by type. Voici mon code views.py a #Views.py def even_percentage_chart(request): labels = ["Science", "Sport", "Other"] data1 = [] data2 = [] data3 = [] data = Even.objects.all().count() dat1 = Even.objects.filter(typ__contains='Science').count()* 100/data data2 = Even.objects.filter(typ__contains='Sportif').count()* 100/data data3 = Even.objects.filter(typ__contains='Other').count()* 100/data try: return JsonResponse(data={ 'labels': labels, 'data1': data1, 'data2': data2, 'data3': data3, }) except (ValueError, ZeroDivisionError): return "" #script.js <script> $(document).ready(function(){ $.ajax({ url: "{% url 'even:even_percentage_chart' %}", dataType:"json", type:"GET", contentType:"application/json", success: function(response){ if(response){ var config = { type: 'doughnut', data: { //labels: ["Science", "Sport", "Other"], datasets: [{ data: response['data1'], backgroundColor: ['#4e73df'], hoverBackgroundColor: ['#2e59d9'], hoverBorderColor: "rgba(234, 236, 244, 1)", }, { data: response['data2'], backgroundColor: ['#1cc88a'], hoverBackgroundColor: ['#17a673'], hoverBorderColor: "rgba(234, 236, 244, 1)", }, { data: response['data3'], backgroundColor: ['#36b9cc'], hoverBackgroundColor: ['#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], }, options: { title: { display: true, text:'Percentage of evens by type:science,sport,...' }, maintainAspectRatio: false, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, … -
Django with Heroku
Having problems trying to set a secret key inside an .env instead of the settings.py file When I run the heroku config I get the secret key (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku config:get SECRET_KEY value When I run the following I get errors. (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 1:53:57 PM web.1 | Traceback (most recent call last): 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\manage.py", line 22, in <module> 1:53:57 PM web.1 | main() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\manage.py", line 18, in main 1:53:57 PM web.1 | execute_from_command_line(sys.argv) 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line 1:53:57 PM web.1 | utility.execute() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute 1:53:57 PM web.1 | django.setup() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\__init__.py", line 24, in setup 1:53:57 PM web.1 | apps.populate(settings.INSTALLED_APPS) 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\apps\registry.py", line 122, in populate 1:53:57 PM web.1 | app_config.ready() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready 1:53:57 PM web.1 | self.module.autodiscover() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover 1:53:57 PM web.1 | autodiscover_modules('admin', register_to=site) 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules 1:53:57 PM web.1 | import_module('%s.%s' … -
I want to make a button in django interactive when a product is free or premium
I want to make a button in django interactive in a case where a product category is free, i want the button to show “download” but if the product is premium, let the button be “Subscribe”. I don’t really know how to hook thing up yet using the ORM, any help would be appreciated Let me show some code models.py class Package_Category(models.Model): title = models.CharField(max_length=10000, verbose_name="Title") slug = models.SlugField(max_length=1000, unique=True) def get_absolute_url(self): return reverse("package-categories", args=[self.slug]) def __str__(self): return self.title class Vectors(models.Model): title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title") slug = models.SlugField(unique=True) image = models.ImageField(upload_to="vectors-images/%Y/%m/%d/", default="default.jpg", verbose_name="Image Cover") vec_file = models.FileField(upload_to='vector-uploads/%Y/%m/%d/', null=True, blank=True, verbose_name="Upload File") category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name="Category") package_category = models.ForeignKey(Package_Category, on_delete=models.DO_NOTHING, verbose_name="Package Category") file_format = models.ForeignKey(Format, on_delete=models.SET_NULL, null=True, blank=True) tags = models.ForeignKey(Tag, on_delete=models.DO_NOTHING, verbose_name="Tag") status = models.CharField(choices=STATUS_CHOICE, default="published", max_length=150, verbose_name='Status') creator = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name="Creator") # creator_image = models.ImageField(upload_to="creators-images/%Y/%m/%d/", default="default.jpg", verbose_name="Creator Image") # creator_bio = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Creator Bio", default="Graphics Designer") created = models.DateTimeField(auto_now_add=True, verbose_name="Created") class Meta: verbose_name = "Vector" verbose_name_plural = "Vectors" def get_absolute_url(self): return reverse("elements:vector-details", args=[self.slug]) def __str__(self): return self.title views.py if needed def VectorDetails(request, vectors_slug): vector = get_object_or_404(Vectors, slug=vectors_slug) vectors = Vectors.objects.filter(status='published').order_by('?')[:6] creators = Profile.objects.filter(creator=True) categories = Category.objects.all() info = Announcements.objects.all() # creator = Profile.get_object_or_404(pk=pk) … -
Uploading fixtures to django running within docker container in an AWS EC2 instance
So I have a a few operations I need to perform on a running instance - kind of a one-off thing. That involves uploading fixtures to it. The structure is an aws ec2 instance, on which runs a few docker container, including a django container. This the docker container in which I need to upload fixtures. This is all part of a ci/cd pipeline, with a postgres RDS database, nginx proxy, and the django container. I can scp the fixtures into the AWS EC2 instance. Then I can SSH into the EC2 instance, and from there log into the running container (using docker exec). That's all fine, but.... How can I access the fixtures that I uploaded to the ec2 instance (the docker host) from within the docker-container? Note: I'm aware I could commit the fixtures to git, then they would find their way into the docker image and be readily available there. I possible I'd rather scp them directly to ec2 & manage them in command lines (because small changes might be needed to the fixtures, which then means I have to run the whole pipeline and wait a few minutes each time...) -
Django Rest Framework Copeapi LinkLookupError
I am getting a LinkLookupError when trying to get a endpoint served by Django Rest Framework. This error only occurs after a single successfully request. My DRF view.py looks like: class RecordViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint that allows Records to be viewed or edited. """ filter_backends = (SimpleRecordFilterBackend,) serializer_class = RecordSerializer permission_classes = (IsAuthenticated,) @action(detail=False, url_path='tagsum/(?P<account>[^/.]+)/(?P<tag>[^/.]+)') def tagsum(self, request, account, tag): if not account or not tag: return Response({'status': "need accoutn and tag"}) sum = Records.objects.filter(linkedaccount_id=account).filter(user_project=tag).aggregate(total=Sum('unblendedcost')) return Response({'sum': sum['total']}) def get_queryset(self): q = Q() linkedaccount_id = self.request.query_params.get("linkedaccount_id") or '' user_project = self.request.query_params.get("user_project") or '' if linkedaccount_id: q &= Q(linkedaccount_id=linkedaccount_id) if user_project: q &= Q(user_project=user_project) return Records.objects.filter(q).annotate(Sum('unblendedcost')) After modifying the view file, I call $coreapi get http://localhost:8000/api/docs/ and see: ... records: { list([page], [linkedaccount_id], [productname], [user_project]) tagsum(account, tag) read(id, [linkedaccount_id], [productname], [user_project]) } ... and after one page load that calls that endpoint, when I run the same command I see this output: ... records: { tagsum: { read(account, tag) } list([page], [linkedaccount_id], [productname], [user_project]) read(id, [linkedaccount_id], [productname], [user_project]) } ... Note that the tagsum method now has the read method nested. Calls to the endpoint now return the following error. errors.js:10 Uncaught LinkLookupError: Invalid link lookup: ["records","tagsum"] at new LinkLookupError (errors.js:10) … -
How put css on django?
I have a big problem.Django dont see my css files.PHG My css file is located in polls.But django dont see it. My home.html <link rel="stylesheet" type="text/css" href="home.css"> <title>121212</title> <body> <div id="1212"> <li class="fafa">12112</li> </div> </body> my settings.py STATIC_URL = '/static/' STATIC_DIRS = [os.path.join(BASE_DIR, "static"),] STATIC_ROOT = os.path.join(BASE_DIR, 'static')``` -
Optimizing queries with Django ORM
I am using debug-toolbar to see the number of overall queries. The problem is that when I reload the page, I see different number of overall queries, given the same code and very short period of page reload intervals. I understand this is somehow related to caching. The question is, is there any shortcut to make Django at least in the debug mode always run all the queries so that I can see the real impact of my changes in the code ? -
Django: Apply filter for EACH element in Array-Field possible?
Hello Django community! I would like to filter my database using a contained_by operation on each element in a Array/JSONB field. Example: Instance has arrayfield: [[A, B],[C, D, E]] I would like to apply following filter to find this instance (written like python in-line loop): .filter(array_element contained by [A, B, C, D, E] for array_element in array) Because the arrayfield can have variable length I cannot index each contains operation explicitly. Is there a way in Django to do something like this? Thank you for you help! -
Its possible detect if the user use pwa in django backend
in javascript it is possible to check something like: (window.matchMedia('(display-mode: standalone)').matches) || (window.navigator.standalone) || document.referrer.includes('android-app://') will return true if using pwa/twa, but I need to check the Django backend for security reasons -
group articles by day in django
I'm trying to group articles in each day, image blow will show you how it looks like now I have 3 records that have their date on top right of them, but as you can see each one of them is separated, I want to show record on this date in one group and tomorrow if I added more records shows on that date group, my codes: Models.py: class Form(models.Model): food_type = models.ForeignKey(FoodTypes, blank=False, null=True, on_delete=CASCADE) calorie = models.CharField(max_length=50) protein = models.ForeignKey(Protein, blank=False, null=True, on_delete=CASCADE) carbohydrate = models.ForeignKey(Carbohydrate, blank=False, null=True, on_delete=CASCADE) drinks = models.ForeignKey(Drinks, blank=False, null=True, on_delete=CASCADE) fruits = models.CharField(max_length=50) note = models.CharField(max_length=200, blank=True) date = models.DateField(default=datetime.date.today) views.py: def requests(request): lists = Form.objects.all().order_by('-date') context = { 'lists': lists } return render(request, 'form/requests_list.html', context) template file: {% for lists in lists %} <div class="req-list"> <h6>{{ lists.date }}</h6> <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">نوع غذا</th> <th scope="col">کالری</th> <th scope="col">پروتئین</th> <th scope="col">کربوهیدرات</th> <th scope="col">نوشیدنی</th> <th scope="col">میوه</th> <th scope="col">توضیحات</th> </tr> </thead> <tbody> <tr> <th scope="row">{{ lists.id }}</th> <td>{{ lists.food_type }}</td> <td>{{ lists.calorie }}</td> <td>@{{ lists.protein }}</td> <td>@{{ lists.carbohydrate }}</td> <td>@{{ lists.drinks }}</td> <td>@{{ lists.fruits }}</td> <td>@{{ lists.note }}</td> </tr> </tbody> </table> </div> {% endfor %} -
TypeError at /admin/app/doctor/add/ __str__ returned non-string (type NoneType)
In my django project my models.py: class myCustomUser(AbstractUser): username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=200) isPatient = models.BooleanField(default=False) isDoctor = models.BooleanField(default=False) firstName = models.CharField(max_length=200, blank=True, null=True) lastName = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(unique=True) dateOfBirth = models.CharField(max_length=200, blank=True, null=True) address = models.CharField(max_length=200, blank=True, null=True) contactNo = models.IntegerField(null=True, unique=True) def __str__(self): return self.firstName class Doctor(models.Model): user = models.OneToOneField(myCustomUser, null=True, blank=True, on_delete=models.CASCADE, related_name='doctor_releted_user') degree = models.CharField(max_length=200, blank=True, null=True) speciality = models.CharField(max_length=200, blank=True, null=True) isApproved = models.BooleanField(default=False) def __str__(self): return self.user.firstName class Patient(models.Model): user = models.OneToOneField(myCustomUser, null=True, blank=True, on_delete=models.CASCADE, related_name='patient_releted_user') gender = models.CharField(max_length=200, blank=True, null=True) class Appointment(models.Model): pname = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='patient_releted_appointment', null=True, blank=True) doctor = models.ForeignKey(Doctor, null=True, blank=True, on_delete=models.CASCADE, related_name='doctor_releted_appornment') date = models.DateTimeField(null=True, blank=True) isConfiremed = models.BooleanField(default=False) After 1st migration when I trying to add any doctor object from admin pannel it says error like: TypeError at /admin/app/doctor/add/ __str__ returned non-string (type NoneType) Please suggest how can I fix it? -
Django rest framework use kwargs in serializer
I have a model Ingredient which has ForeignKey field. I use modelSerializer to pass data. I'm passing recipe_id in url like this recipes/{recipe.id}/ingredients. My current solution is to modify request.data in the view but I'm sure if it's corrent way for such a common case. What's the best way to pass Recipe to serializer? models.py class Ingredient(TimeStamp): name = models.CharField(max_length=50) quantity = models.PositiveSmallIntegerField() recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, related_name='ingredients', ) serializers.py class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = [ 'id', 'name', 'quantity', 'unit', 'recipe' ] views.py class IngredientViewSet(viewsets.ModelViewSet): serializer_class = IngredientSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) request.data['recipe'] = self.kwargs['pk'] serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) -
Problem when trying to import a template from a django directory
I have a django module called botmodules, for example, and I want to import a model from a django module into it. Look how I proceeded Traceback (most recent call last): File "/code/botmodules/bot.py", line 1, in <module> from events import general File "/code/botmodules/events/general.py", line 2, in <module> from ...botlogic.models import Server ImportError: attempted relative import beyond top-level package -
flutter urls.dart template file
i was following Building a Mobile App with Django & Flutter tutorial but in the tutorial they dont share the urls.dart file so my project giving errors because there is no code for urls so my project giving errors. is there a template for it? or how can i create a file from zero? in comments of the video it seems thats the only problem and huge one. thx -
Cannot get POST data from Django request.POST
I'm trying to verify that the required data was included in a POST request. I have a django backend and a vue3 frontend. Here is my django view: views.py # Sign user in and issue token @require_http_methods(['POST']) def login(request: HttpRequest): if request.method == 'POST': # check that required fields were send with POST print(request.body) if {'username', 'password'} >= set(request.POST): # <- evaluates as False print('missing required fields. INCLUDED: ' + str(request.POST)) return JsonResponse( data={'message': 'Please provide all required fields.'}, content_type='application/json', status=400) # check that username exists and password matches if (User.objects.filter(username=request.POST['username']).count() > 0): user = User.objects.get(username=request.POST['username']) if user.password == request.POST['password']: # Delete previously issued tokens Token.objects.filter(user_id=user.id).delete() token = Token(user_id=user.id) token.save() return JsonResponse(data={'userToken': token.to_json()}, content_type='application/json', status=200) else: return JsonResponse( data={'message': 'Incorrect username or password.'}, content_type='application/json', status=400) else: return HttpResponseNotAllowed(permitted_methods=['POST']) And my axios request Login.vue axios .post('http://localhost:8000/api/users/login', { 'username': form.get('username'), 'password': form.get('password'), }, { validateStatus: (status) => { return status !== 500 }, }) .then((response) => { console.log(response.data) if (response.data.success) { // Commit token value to store store.commit('setToken', response.data.token) // Request user data ... } else { alert.message = response.data.message alert.type = 'error' document.querySelector('#alert')?.scrollIntoView() } }) I can see that username and password are set in request.body but not request.POST as shown … -
custom filtering not working in django rest framework
i have tried to use custom filtering by defining a filter class and importing in my view but it is not working. My code: class ProductAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = ProductFilter pagination_class = CustomPagination My filter: class ProductFilter(filters.FilterSet): variants__price = filters.RangeFilter() class Meta: model = Product fields = ['brand__name','variants__price','availability','slug','category__name', 'services','featured','best_seller','top_rated'] My models: class Brand(models.Model): name = models.CharField(max_length=100, unique=True) featured = models.BooleanField(default=False) class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True) mini_category = models.ForeignKey(Minicategory, on_delete=models.SET_NULL, blank=True, null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? Now when I call localhost/api/products?brand___name__in=lg,sony it doenst filter and shows all the objects from the database. It only works when I dont put in like this localhost/api/products?brand___name=lg .But I need to query through multiple parameters. What is the issue here?? From the docs, it says i can multiple query using __in. -
Django DeleteView showing blank page when i click on delete button
I make a view with Django DeleteView CBV and when i click on delete button in delete page nothing happen and Django says: Method Not Allowed (POST): /post/delete_post/3 Method Not Allowed: /post/delete_post/3 Here is my code: views.py class DeletePostView(DetailView): model = Posts template_name = 'blog/delete_post.html' success_url = reverse_lazy('blog:all_posts') urls.py path('post/delete_post/<int:pk>', views.DeletePostView.as_view(), name='delete_post') my button: <p><a href="{% url 'blog:delete_post' object.id %}">delete post!</a></p> delete_post.html {% extends 'base.html' %} {% block title %}Delete post{% endblock %} {% block content %} <form action="" method="post"> {% csrf_token %} <p>Are you sure?</p> <input type="submit" value="Delete!"> <a href="{% url 'blog:post_detail' object.id %}">Cancel</a> </form> {% endblock %} -
How to get Django custom form validator to work?
I'm working on a custom valdator for my Django forms. Inexplicably, I can't get the result I want. Here is my code from django import forms from django.core import validators from django.core.exceptions import ValidationError from .models import Vote from django.core.validators import MaxValueValidator, MinValueValidator def use_one(value): if value != 1: raise forms.ValidationError("Value is not 1!") class MyForm(forms.Form): main_form = forms.IntegerField(validators = [use_one], label= 'Main', required = False, widget = forms.NumberInput( attrs={'id': 'mainInput', 'name': 'main, 'href': '#', 'value': '', 'class': "form-control"})) Any thoughts? views.py form = MyForm() main_result = request.GET.get(main_form) form.fields['main_form_result'].initial = main_result context = {form: form}