Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error during run the program runtime error
These are apps installed in my django project , the apps with vip_number.* are inside the innerproject folder... but i got the issue here that my apps are not installed in seetings.py where as they are already there INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'jet', 'jet.dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'vip_number.users', 'vip_admin', 'vip_number.base', 'vip_number.categories', 'vip_number.category_tag', 'vip_number.category_numbers', 'vip_number.number', 'vip_number.paytm', 'vip_number.subscribers', 'vip_number.homeimages', 'vip_number.testimonial', 'vip_number.faq', 'tagconstants', 'sekizai', 'vip_number.wawebplus', 'contact', ] error :*********************************************************************************** (djangoenv) PS E:\download\VIP number\vip_number> python manage.py runserver Exception in thread django-main-thread: Traceback (most recent call last): File "E:\download\VIP number\djangoenv\lib\site-packages\django\apps\config.py", line 244, in create app_module = import_module(app_name) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'base' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "E:\download\VIP number\djangoenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "E:\download\VIP number\djangoenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "E:\download\VIP number\djangoenv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "E:\download\VIP number\djangoenv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "E:\download\VIP number\djangoenv\lib\site-packages\django\utils\autoreload.py", … -
How can I set a logic like, "If a user order any product then the user will be able to give feedback just on that product"?
My motive is to set a logic like, a user only will be able to give a product review on that product he/she bought. I tried this below way but didn't work. Please give a relevant solution models.py class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_title = models.CharField(blank=True, null=True, max_length = 250) def __str__(self): return str(self.pk) + "." + str(self.product_title) class ProductOrder(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='UserOrderRelatedName',on_delete=models.CASCADE) CustomerName = models.CharField(max_length=250, blank=True, null=True) Product = models.ForeignKey(Products, related_name='ProductOrderRelatedName',on_delete=models.CASCADE) ProductTitle = models.CharField(max_length=250, blank=True, null=True) def __str__(self): return f'{self.pk}.{self.User}({self.Product})' views.py: def quick_view(request, quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) context = { "quick_view":quick_view, } return render(request, 'quickVIEW_item.html', context) urls.py: path('quick_view/<int:quick_view_id>/', views.quick_view, name="quick_view"), template: {% if quick_view in request.user.UserOrderRelatedName.all %} <form action="{% url 'feedBack' quick_view_id=quick_view.id %}" method="POST" class="needs-validation mt-3" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} <textarea id="email" placeholder="Share your experiencs..." rows="10" style="font-size: 13px;" type="email" class="form-control" name="feedBACK" value="" required></textarea> <button type="submit" class="btn btn-outline-dark ms-auto" style="font-size: 13px;"> Submit </button> </form> {% endif %} -
table post_post has no column named publishing_date
im just a beginner in web coding and i got this error while i was adding my first app to the my first website i couldn't find a solution to this i thought it was something related to language of my website but it didn't worked and here is my codes that i just wrote like i said i just started to coding so i dont know anything to solve this issue enter image description hereenter image description here -
django show me "django.db.models.query_utils.DeferredAttribute object at"
Im trie to get a values from an object of my DB on a form in html to edit him but when i call the current "value" from the attribute i get this: Form HTML <form enctype="multipart/form-data" method="post"> {% csrf_token %} {% for campo in formulario %} <div class="mb-3"> <label for="" class="form-label">{{ campo.label }}:</label> {% if campo.field.widget.input_type == 'file' and campo.value %} <br/> <img src="{{MEDIA_URL}}/imagenes/{{campo.value}}" width="100"srcset=""> {% endif %} <input type="{{ campo.field.widget.input_type}}" class="form-control" name="{{ campo.name }}" id="" aria-describedby="helpId" placeholder="{{campo.label}}" value="{{campo.value | default:''}}" /> </div> <div class="col-12 help-text"> {{campo.errors}}</div> {% endfor %} <input name="" id="" class="btn btn-success" type="submit" value="Enviar informacion"> </form> Views Models -
Django Rest Framework permissions class doesn't work properly
I'm trying to implement view with rest-framework, here it is: class IsOwnerOnlyPermissions(BasePermission): def has_object_permission(self, request, view, obj): print(obj.user_profile.user, request.user, obj.user_profile.user == request.user) print(request.user.groups, request.user.get_group_permissions()) return obj.user_profile.user == request.user class DjangoModelPermissionsWithRead(DjangoModelPermissions): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } class DocumentsDetails(generics.RetrieveAPIView): queryset = Documents.objects.all() serializer_class = DocumentsSerializer # Can access only owner OR administrator/moderator permission_classes = [IsOwnerOnlyPermissions | DjangoModelPermissionsWithRead] But it doesn't work properly. I'm accessing it via Postman with user which doesn't have any permissions or groups (it's printing auth.Group.None set()) and it doesn't block access for me. I know, that I can check user permissions in my IsOwnerOnlyPermissions, but I want to use DjangoModelPermissions class for this. Are there any possibility to do this? -
column does not exist at.... programmeable error
i have carried out all my migrations but still receiving this error. To my understanding the error means that the product table does not have the entities like name, price etc yet they are there. I need some help understanding this error more. from audioop import add from termios import TIOCGWINSZ from django.db.models.deletion import CASCADE from django.urls import reverse from django.conf import settings from django.db import models from django.conf import settings CATEGORY_CHOICES = ( ('F', 'Fashion'), ('El', 'Electronics'), ('HB', 'Health & Beauty'), ('G', 'Gardening'), ('SP', 'Sports'), ('HO', 'Home & Office'), ) LABEL_CHOICES = ( ('P', 'Primary'), ('S', 'Secondary'), ('D', 'Danger'), ) class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) seller = models.CharField(max_length=200, blank=True, null=True) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2, null=True) label = models.CharField(choices=LABEL_CHOICES, max_length=2, null=True) image1 = models.ImageField(null=True, blank=True) image2 = models.ImageField(null=True, blank=True) image3 = models.ImageField(null=True, blank=True) image4 = models.ImageField(null=True, blank=True) slug = models.SlugField(null=True, blank=True) characteristics = models.TextField(max_length=3000, null=True) description = models.TextField(max_length=3000, null=True) specifications = models.TextField(max_length=3000, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("homeapp:product", kwargs={'slug': self.slug}) def get_add_to_cart_url(self): return reverse("homeapp:add-to-cart", kwargs={'slug': self.slug}) def get_remove_from_cart_url(self): return reverse("homeapp:remove-from-cart", kwargs={'slug': self.slug}) @property def image1URL(self): try: url = self.image1.url except: url = '' return url @property def image2URL(self): … -
Save large CSV data into Django database fast way
I am trying to upload extensive CSV data like 100k+ into the Django database table, I have created the model below and then made a save function to insert the data into the table. It takes a long time so I have written celery code to run this in the background so it doesn't timeout, But the saving data into the table is slower. Is there any way to make the saving faster? class Film(models.Model): title = models.CharField(max_length=200) year = models.PositiveIntegerField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) def save_csv_to_db(): with open('films/films.csv') as file: reader = csv.reader(file) next(reader) for row in reader: print(row) genre, _ = Genre.objects.get_or_create(name=row[-1]) film = Film(title=row[0], year=row[2], genre=genre) film.save() -
Problem trying validate django form field while typing
I'm trying validate a field while typing based on another question ( How to validate django form field while it is typing? ). the js don't cal validation view and i get this error in browser: Uncaught ReferenceError: $ is not defined for line $('#id_num').on('input', function () { form {{ form.num }} <p id="validate_number" class="help is-danger is-hidden ">nome já utilizado</p> js <script> $('#id_num').on('input', function () { var id_number = $(this).val(); $.ajax({ url: '/validatenum/', data: { 'num': id_number }, dataType: 'json', success: function (data) { if (data.is_taken) { $("#validate_number").show(); document.getElementById('id_num').style.borderColor = "red"; document.getElementById("submit_change").disabled = true; } else { $("#validate_number").hide(); document.getElementById('id_num').style.borderColor = "#e7e7e7"; document.getElementById("submit_change").disabled = false; } } }); }); </script> view def validate_inventory_number(request): number = request.GET.get('num', None) data = { 'is_taken': InventoryNumber.objects.filter(num=number).exists() } return JsonResponse(data) -
Django pagination: EmptyPage: That page contains no results
When using Django CBV ListView with pagination, if I provide a page that is out of range, I get an error: I would like to have a different behaviour: to fallback to the last existing page if the provided page is out of range. I dug into Django source code paginator.py file and was surprised to find some code that does exactly this: def get_page(self, number): """ Return a valid page, even if the page argument isn't a number or isn't in range. """ try: number = self.validate_number(number) except PageNotAnInteger: number = 1 except EmptyPage: number = self.num_pages return self.page(number) However, it seems this code is never called by default using Pagination. What is the right way to deal with this? Should I make my own paginator by subclassing the Paginator class? Thanks. -
No Module named WhiteNoise
2022-08-05T17:47:45.758949+00:00 app[web.1]: ModuleNotFoundError: No module named 'whitenoise' 2022-08-05T17:47:45.759055+00:00 app[web.1]: [2022-08-05 17:47:45 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-08-05T17:47:45.817101+00:00 app[web.1]: [2022-08-05 17:47:45 +0000] [11] [ERROR] Exception in worker process ""hello, I am getting this error while uploading my Django to the heroku""" -
Field 'id' expected a number but got ' '. But I dont even have a field named 'id'
we are making a web app using Django, postgresql, and reactjs. I am creating two models and connecting them using one to one relationship in django. The view file is literally empty. This is models.py file I changed the primary key fields for each table to avoid the error but it isnot solving anything.I am new to Django. Please help. from django.db import models class userInfo(models.Model): Username=models.CharField(max_length=100,primary_key=True) Password=models.CharField(max_length=100) def __str__(self): return self.Username class rentDetails(models.Model): user=models.OneToOneField( userInfo, on_delete=models.CASCADE, primary_key=True ) floor_no=models.CharField(max_length=20,default=True) distance=models.IntegerField(default=True) location=models.CharField(max_length=200,default=True) area=models.IntegerField(default=True) no_of_rooms=models.IntegerField(default=True) price=models.IntegerField(default=True) property_choices=[ ('hostel','Hostel'), ('house','House') , ('room','Room'), ('flat','flat') ] property_type=models.CharField( max_length=10, choices=property_choices, ) images=models.ImageField(upload_to='uploads/',null=True) -
Docker Django 1.7 django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates:foo?
I know this question is similar to many prior cases, for example: [1]: How to resolve "django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: foo" in Django 1.7? , but my issue was happened while I was running my Docker images. The Django application compiled successfully while I was on locally, but after I built my docker image and tried to run it. It shows " Application labels aren't unique: foo". I guess it might related to "Cache". I thought on local, there might be a cache, but no cache in docker image, so the compiler doesn't recognize the name of the label? That's the issue came from? -
Is it a bad practice to write an interactive step on a unit test?
From what I understand the main purpose of unit testing is to automatize testing. But consider the following example: I have an application that needs the user to read a QR code. When the user reads the QR code, the user is connected to another application. My application then checks if the user is connected. So, the only way that I think to test this scenario, is to when running the test case, display a QR code in the console so that the developer read it. But I think it's a bad practice. So my question is: "Is it a bad practice to write an interactive step on a unit test ?" Can anybody give me another way to test this scenario? Maybe there is some kind of tool that I dont know? I'm using django in this application. Thank you. -
How to properly join two Django query sets
I have the following logic implemented in an endpoint. def get(self, request, branchName, stack, resultType, buildNumberMIN, buildNumberMAX, format=None): try: # use ONE query to pull all data relevant_notes = Notes.objects.filter( branchName=branchName, stack=stack, resultType=resultType) # filter on the endpoint parameters (range of numbers) requested_range = relevant_notes.filter( buildNumber__gte=buildNumberMIN, buildNumber__lte=buildNumberMAX) # also pull latest note -- regardless of requested range latest_note = relevant_notes.latest('buildNumber') # join the notes return_set = requested_range | latest_note #serialize the data serializer = serializers.NoteSerializerWithJiraData( return_set, many=True) return Response(serializer.data) except Notes.DoesNotExist: return Response({"message": f"No notes found"}, status=404) Context: the logic is put simply, fetch a range of notes, but also include the latest note based on the url parameters. If the range of notes contains no data, still return latest. The issue I am facing is AttributeError at /api/v2/notes/Test/Test/Test/1/2/ 'Notes' object has no attribute '_known_related_objects' It is possible that it does not like that I add attempting to combine a query set with a single object... -
Accessing an object based on foreign key link in Django template
I currently have some models linked using foreign keys (reduced) models.py: class Saga(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=1000) startChapter = models.PositiveIntegerField() endChapter = models.PositiveIntegerField() class Arc(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=1000) saga = models.ForeignKey(Saga,on_delete=models.SET_DEFAULT,default=Saga.get_default_pk) startChapter = models.PositiveIntegerField() endChapter = models.PositiveIntegerField() class Clip(models.Model): description = models.CharField(max_length=200) arc = models.ForeignKey(Arc,on_delete=models.SET_DEFAULT,default=Arc.get_default_pk) chapter = models.PositiveIntegerField() viewers = models.ManyToManyField(User, through='ClipViewer') author = models.ForeignKey(User,on_delete=models.SET_NULL,null=True, related_name='author_of') Basically all Sagas have a set of associated arcs and every arc has a list of associated clips. What I want to do is get my Sagas, Arcs and Clips through my API calls and then loop through each saga, getting the associated arcs for that saga and then loop through the arcs, getting the associated clips for that arcs, eg: Saga 1 has arcs 1,2,3 Arc 1 has clips 1 & 2 Arc 2 has clip 3 Arc 3 has clips 4 & 5 Saga 2 has arc 4,5.... But templates seem too limited to do this kind of querying, I can't do anything like get the list of associated arcs for a given saga or anything like that and being told: Because Django intentionally limits the amount of logic processing available in the template language, it is … -
Is there a way to add list in a django model class?
I'm a django beginner and trying to make a project from scratch. My models are : class Citizen(models.Model): name = models.CharField(max_length=64, unique=False) citizen_id = models.CharField(max_length=10, unique=True) def __str__(self): return '{} by {}'.format(self.name, self.citizen_id) class Manager(models.Model): name = models.CharField(max_length=64, unique=False) manager_id = models.CharField(max_length=10, unique=True) def __str__(self): return '{} by {}'.format(self.name, self.manager_id) class Message(models.Model): sender = models.ForeignKey(Citizen, Manager, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(Citizen, Manager, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=1200) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message class Meta: ordering = ('timestamp',) class Centre(models.Model): pass In Centre , there's gonna be one manager and then a lot of citizens. What should I do here? Should I add a list of citizens? Is that possible? -
Why aren't failed Django queries more descriptive?
A python dictionary will throw a keyerror that describes what key was searched for and failed. Why does running .objects.get() on a queryset not describe the parameters passed in that failed to return a model, or returned more than one? Is this something that could be added to Django.db? -
My custom save_user function in allauth does not work
I am trying to store the profile picture of the user when he is logging in with google. So, I have modified the save_user in following way: from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): print("called1") def save_user(self, request, user, form, commit=True): print("called2") user = super(MyAccountAdapter, self).save_user(request, user, form, commit=False) data = form.cleaned_data user.picture = data.get("picture") print("called3") user.save() print("called4") pass But for some reason my modified save_user doesn't work. It is to be noted that I used print to know if the code inside my modified function was called. But When I run the application I only get called1 and called4 printed in compiler but not called3 and called2. Note: I have already added ACCOUNT_ADAPTER in settings.py. -
How to pass a function with parameters from view to template in Django?
I am passing a function from views.py to a template in Django. This function takes a date argument and returns the difference between it and today's date views.py: def days_until(date1): td = datetime.date.today temp = date1 - td return temp.days def index(request): entries = Entry.objects.all() return render(request, 'index.html', {'entries' : entries, 'days_until' : days_until}) index.html: {% for entry in entries %} <div> {{ days_until(entry.date) }} </div> {% endfor %} This code doesn't work and returns this error: Could not parse the remainder: '(entry.pwExp)' from 'days_until(entry.pwExp)' I'm assuming that I am not calling days_until incorrectly. How should I be passing entry.date into this function? -
Django admin: Filter field by range
Hi i have a model called Person. Person has fields like name/surname and age. Now what I want to achieve is to have a filter in django admin that can filter age in some custom ranges so 10-15 after reading some posts my best shoot is class RangeFilter(SimpleListFilter): title = 'Age filter' parameter_name = 'age' def lookups(self, request, model_admin): return [ (1, '0-5'), (2, '5-10'), (3, '10-15'), (4, '15-20')] def queryset(self, request, queryset): filt_age = request.GET.get('age') return queryset.filter( age__range=self.age[filt_age] ) but this yields an error 'RangeFilter' object has no attribute 'age_dict' -
adding in get_context_data of a class-based view an external script
I have a python script in a page which I would like to exploit in a class-based view pages/textutile.py class Palindrome: def __init__(self, mot): self.mot = mot def getMot(self): i = 0 y = 0 while(i < len(self.mot)): envers = (len(self.mot)-1-i) c = envers+y-envers i = i+1 y = y+1 if(self.mot[envers] == self.mot[c]): return f"{self.mot} est un palindrome" else: return f"{self.mot} n'est pas un palindrome" I import it into pages/views and i have this class based view to which i would like to insert this code to display it in palind_detail view pages/views.py from .texteUtile import Palindrome class PalindDetailView(DetailView): model = Palind context_object_name = "palind" template_name = "pages/palind_detail.html" the code i would like to insert in get_context_data foo = Palind.objects.all() newClass = Palindrome(foo) selectmot = newClass.getMot() # i need get variable "selectmot" in context it's a simple test on words to insert in the database (the name of the field is "mot") it tests if the word is a palindrome. and displays it in palind_detail.html. but the main thing is to understand how get_context_dat works for class-based views Merci -
How to connect React Native app to Django REST API
I'm in the process of connecting my React Native UI to Python Django backend using REST framework and unsure of how to go about fetching the data from backend. I used the fetch(URL) as you can see in the SS below: The error I get: I also added my phone as an adb device and connected it through a USB cable before running the app, but same issue. Any suggestions as to how to go about React Native UI and Python Django REST API integration? -
Django crispy forms - bootstrap4 table_inline_formset template rendering extra row on top
I am using the bootstrap4/table_inline_formset.html template in a FormHelper from django-crispy-forms. The table is rendered correctly in the template, but an extra form always appears at the beginning of the table, which is not visible when submitting the form. forms.py: class MetricForm(forms.ModelForm): class Meta: model = Metric exclude = ['auto_value','occurrence'] class MetricFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(MetricFormSetHelper, self).__init__(*args, **kwargs) self.add_input(Submit('submit', 'Submit', css_class="btn btn-success")) self.template = 'bootstrap4/table_inline_formset.html' views.py: @login_required def create_occurrence(request, pk): try: site = Site.objects.get(id=pk) except Site.DoesNotExist: raise Http404("Site does not exist") form = OccurrenceForm(request.POST or None, initial={'site':site}) MetricFormset = modelformset_factory(Metric, form=MetricForm, extra=3) formset = MetricFormset(queryset=Metric.objects.none()) helper = MetricFormSetHelper() if form.is_valid(): occurrence = form.save(commit=False) occurrence.added_by = request.user occurrence.site = site occurrence.save() form.save_m2m() metric_formset = MetricFormset(request.POST) if metric_formset.is_valid(): for metric_form in metric_formset.forms: if all([metric_form.is_valid(), metric_form.cleaned_data != {}]): metric = metric_form.save(commit=False) metric.occurrence = occurrence metric.save() messages.success(request, "Occurrence created successfully.") execute_from_command_line(["../manage_dev.sh", "updatelayers", "-s", "archaeology"]) return redirect(occurrence.get_absolute_url()) context = { 'form': form, 'site':site, 'formset':formset, 'helper': helper, } return render(request, "archaeology/occurrence_form.html", context=context) template: ... <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <h4>Metrics</h4> {{ formset.management_form }} {% crispy formset helper %} {% if form.instance.pk != None %} <a class="btn btn-danger" href="{% url 'delete_occurrence' occurrence.id %}">{% trans "Delete" %}</a> {% endif %} </form> ... Any … -
Django NoModuleFoundError occurs only when adding a valid path to urls.py of my project folder
I have set up a Django project according to Victor Freitas' excellent post on production ready Django boilerplate here https://simpleisbetterthancomplex.com/tutorial/2021/06/27/how-to-start-a-production-ready-django-project.html It took me a day to refactor my whole project with 7 apps to fit into that boilerplate. All was fine and with everything working until I started developing my urls paths and templates. For some reason when adding a url path to main urls.py file within the main project folder Django fires me a NoModuleFoundError stating 'ModuleNotFoundError: No module named 'categories' . Categories is the name of my app and it is properly installed in base.py config file. Code below: # SIGP3A/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # path('categories/', include('categories.urls')), # <-- THIS LINE RIGHT HERE ] If I uncomment the above pointed line I get the error message. If I comment it out it passes Django checks. See bellow bits and pieces of the code that I believe are relevant to the question: # SIGP3A/Comps/categories/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.categories, name='categories'), ] See below my installed apps where categories is included. Note Comps is INSIDE main project folder and it is … -
In Django I use request.POST and return JSONResponse but the url shows HttpResponse error. I don't want to use render
I'm using Ajax to submit a POST. In views.py I have the following: def color(request): if(request.POST.get('result_data',False)): mylist= request.POST['mydata'] mylist= listt.split(",") request.session['var1'] = mylist[0] request.session['var2'] = mylist[1] return JsonResponse({'success':True}) In url I defined color/, so when I go to localhost:8000/color it shows error: "didn't return an HttpResponse". I should use instead return render(request,'app/color.html',{}) but I do not have a color.html file. I actually don't want to have one. All I want is to post a variable and use it as a session, so how can I avoid using render() and creating the html file? Thanks