Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how i can delete multiple record or objects in django?
I want to delete multiple records using html checkbox but i don't get any idea how i perform this task. At this time in my project I implement the single delete record or object through generic views as you can see in below code. How i can delete multiple records using checkbox? what changes i need to do in my code? views.py class DeleteProduct(SuccessMessageMixin, DeleteView): model = Product success_url = reverse_lazy('stock:stock') success_message = "Product is deleted successfully." def delete(self, request, *args, **kwargs): messages.success(self.request, self.success_message, extra_tags='alert-danger') return super(DeleteProduct, self).delete(request, *args, **kwargs) urls.py path('<int:pk>/delete', login_required(DeleteProduct.as_view(), login_url='login'), name='deleteproduct'), template.html {% extends 'base.html' %} {% block content %} <div> <h2 class="text-center" ><i>Stock!</i></h2> {% if messages %} {%for message in messages%} <div class="alert {{ message.tags }}" role="alert"> {{ message }} </div> {% endfor %} {% endif %} <hr/> <form method="POST"> {% csrf_token %} {% for product in page_obj %} <div class="row" > <input type="checkbox" name="products" value="{{ product.id }}"> <div class="col-sm-2" > <h5>{{ product.id }}</h5> <img src="{{ product.Picture.url }}" height="120px" /> </div> <div class="col-sm-4" > <h5><u>Product Name</u>: {{ product.pro_name }}</h5> <h6><u>Company Name</u>: {{product.companyName}}</h6> <div class="row" > <div class="col-sm" > <p>Purchase Price: <b>{{product.Purchase_Price}}</b></p> </div> <div class="col-sm" > <p class="pt-0">Sale Price: <b>{{product.Sale_Price}}</b> </p> </div> </div> <div class="row" > … -
Importing javascript from node modules in a django project
I am so sorry to ask such a simple question. I have spent hours looking for an answer but I just can't figure this out. I am trying to import a javascript library from node_modules in my django project. For whatever reason, I keep getting a 404. I'm testing with a dummy javascript file, so right now my import statement is just <script src="/node_modules/test.js"></script> (As a sanity test I've also tried ../node_modules/ and node_modules/ as well as using the django static files system) Here is a picture with the file + file structure: site/node_modules/test and site/portfolio/templates/portfolio/test.html I'm wondering if this error has something to do with how Django serves static files in development? is there something that I'm missing? -
PythonAnywhere dotenv Import error when following `How to set environment variables for your web apps` guide
I want to set up environment variables for my Django project. I have followed the PythonAnywhere guide on How to set environment variables for your web apps, including this step: from dotenv import load_dotenv This is my code in the wsgi.py file: wsgi.py I receive the following import error for dotenv when trying to run the webapp: dotenv import error log I do have the dependency installed: enter image description here I'm not sure what's going on here. It seems my project_folder path is correct, so I don't think that's the issue. I'm not sure what's going on. Thanks for the help in advance :) -
Django from django.core.wsgi import get_wsgi_application
An error POPs up that wsgi does not see django(when placing it on hosting). Although there is django in the virtual environment(I read that the path of the virtual environment can be incorrectly recognized, this is probably the problem, but it did not work out): [Fri Apr 03 23:34:20 2020] [error] [client 5.18.99.123] from wsgi import application [Fri Apr 03 23:34:20 2020] [error] [client 5.18.99.123] File "/home/users/m/marselabdullin/caparol_center_spb_decision/caparol_center_spb_decision/wsgi.py", line 12, in <module> [Fri Apr 03 23:34:20 2020] [error] [client 5.18.99.123] from django.core.wsgi import get_wsgi_application [Fri Apr 03 23:34:20 2020] [error] [client 5.18.99.123] ModuleNotFoundError: No module named 'django' Код django.wsgi на хостинге import os, sys virtual_env = os.path.expanduser('~/caparol_center_spb_decision/env') home='~/caparol_center_spb_decision/env' activate_this = os.path.join(virtual_env, 'bin/activate_this.py') exec(open(activate_this).read(), dict(__file__=activate_this)) sys.path.insert(0, os.path.expanduser('~/caparol_center_spb_decision/caparol_center_spb_decision')) from wsgi import application -
Django REST Framework FileParser error while making a request through postman
I have a model in Django for holding the details of the user's profile like: class UserDetails(models.Model): def getFileName(self, filename): return 'profile_pics/'+str(self.user.id)+'/'+filename user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) profile_picture = models.ImageField(blank = True, upload_to=getFileName) country = models.CharField(max_length = 50, default='India') gender = models.CharField(max_length=10, default='NA') birthday = models.DateField(default=datetime.now()) phone = models.CharField(max_length=15) verified = models.BooleanField(default=False) def __str__(self): return self.user.username Then, I wrote a REST API that would handle POST requests to create a user profile like: from django.shortcuts import render from rest_framework import status from rest_framework.decorators import api_view, authentication_classes, permission_classes, parser_classes from rest_framework.parsers import FormParser, MultiPartParser, FileUploadParser from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from datetime import datetime from django.contrib import messages, auth from django.contrib.auth.models import User from userMgmt.models import UserDetails @api_view(['POST']) @parser_classes(['FormParser', 'MultiPartParser', 'FileUploadParser']) def signUp(request): if request.method == 'POST': data = request.data ## Creating a basic user user = User.objects.create_user(data['first_name'], data['email'], data['password']) user['last_name'] = data['last_name'] user.save() ## Creating a profile for the user user_details = UserDetails() user_details.user = user user_details.profile_picture = data['profile_picture'] user_details.country = data['country'] user_details.gender = data['gender'] user_details.birthday = datetime.strptime(data['birthday'], '%m/%d/%y') user_details.phone = data['phone'] user_details.verified = False user_details.save() return Response({'message': 'Profile created Successfully'}) Then, I made a request to this REST API using Postman like: After that, I got … -
my class-based view in django does not work how to fix it
Guys i am learning how to make class-based views and my code does not work. would appreciate your help. In models.py class Student(models.Model): name = models.CharField(max_length=150) class Class10(models.Model): stud_name=models.CharField(max_length=200) surname=models.CharField(max_length=500) class Meta: managed=False db_table='background' in forms.py: class StudentForm(forms.ModelForm): name = forms.CharField(max_length=150, label='',widget= forms.TextInput (attrs={'placeholder':'Search'})) class Meta: model = Student fields = ['name',] def clean_name(self): name=self.cleaned_data.get("name") if not Class10.objects.filter(stud_name=name).exists(): raise forms.ValidationError ( "No such student") return name In views.py : from django.shortcuts import render from .forms import * from django.urls import reverse_lazy from .models import * from django.views.generic import CreateView,TemplateView class Searchr(CreateView): form_class = StudentForm success_url = reverse_lazy('bla') template_name = 'vasa/index.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST or None) if request.method == "POST": if form.is_valid(): form1 = form.save(commit=False) name = form1.name student_info=Class10.objects.get(stud_name=name) context={'profile':student_info ,'form': SymbolForm(),} return render(request, self.success_url, context) return render(request, self.template_name, {'form': form}) in app vasa/urls.py: from django.contrib import admin from django.urls import path, include from vasa import views from django.conf.urls import url app_name = 'vasa' urlpatterns = [ path('searchr/',views.Searchr.as_view(),name='searchr')] in main urls.py: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('vasa/',include('vasa.urls',namespace='vasa')),] in index.html: <form method="POST" > {% csrf_token %} {{ form}} <button class = "button" type="submit">OK</button></form> in bla.html: <form method="POST" > {% … -
Edit the template of admin top page
I am editing the template of admins I successfully override the each model's edit page. /myapp/template/admin/modelA/change_list_results /myapp/template/admin/modelB/change_list_results However how can I override the top of admin?? After login, there is a application and table lists. I tried to override these below from /django/contrib/admin/templates/admin/ folder /myapp/template/admin/app_index /myapp/template/admin/index /myapp/template/admin/base However , still in vain. -
Hiding the one certain row of tables in admin
I want to hiding the one certain row of tables in admin. I have these tables. id name 1 main // hide this row in admin. 2 John 3 Lisa At first, I try to override template change_list_result.html and edit here, but still no success. <tr class="{% cycle 'row1' 'row2' %}"> {% for item in result %} {{ item }}{% endfor %} </tr> Is there any good way or my plan is basically ok? -
Django formset not JSON serializable
I am trying to pass a formset as JSON data but i am getting Object of type HabitFormFormSet is not JSON serializable. Why is that ? my view: def modal_view(request): HabitFormSet = modelformset_factory( Habit, extra=0, form=HabitModelForm) formset = HabitFormSet( request.POST, queryset=Habit.objects.filter(user=request.user), ) new_habit = HabitModelForm(request.POST) if formset.is_valid(): formset.save() data = {"formset": formset} return JsonResponse(data) return HttpResponseRedirect(reverse('home')) -
How to handle user authentication in django without relying on user models?
I'm working on an assignment. I'm using Django as the front end. The course is focused on databases and I cannot rely on Django's ORM features(including models). I have to write raw SQL queries for everything I do. I know that Django has a user model but I cannot rely on it for querying user info. The problem is that I still need to authenticate users. I could get away with storing user credentials on user models and add a field to store the SQL primary key for the info in there and use that for the queries but that is not a full solution. The rest of the framework seems to be coupled with the user model so I'm unsure as to whether it is even possible to do it without user models. -
Serving a django model containing objects
I have following django model: class Weather(models.Model): lat_lng = gis_models.PointField() raw_data = psql_fields.JSONField(null=True) I have following view: def weather(request): data = WeatherModel.objects.all() js_data = serializers.serialize('json', data) return HttpResponse(js_data, content_type='application/json') It throws error saying 'Point object is not json serializable.' I want this function to return json. Please help. -
How to integrate django with react and webpack to create a multipage webapp?
I have a django project, now I want to integrate react with it in such a way that routes or urls should be handled by django and other stuff inside the body should be handled by react and its components. For example: /profile/ is route which is served by django and after it has loaded everything all the crud operation could be done by react. One more thing I want all the static files should be generated by webpack, which will served by django -
Generate different checkboxes inside a loop html
Right now i'm working in my first python - django project's front end, and i'm having some trouble with the table i'm using to show data from my db. The thing is that i wanted to put a checkbox at the first column of the table at every row, but since i don't know how many registers will there be, i created a checkbox on the first column inside the loop that i'm using to show the registers. And every checkbox of the table that i click makes reference to the checkbox thats on the first register of the table. (If i click the 3rd's row checkbox, it would check the first row's one, and if i click the 5th's row table, it would uncheck the first row's one.) here is my code. HTML: {% for dominios in dominios %} <tr style="height: -2px;"> <td style="text-align:center;"> <div class name="checkboxWrapper"> <input type="checkbox" id="check" hidden="true" style="margin-top: 10px;"/> <label for="check" class="checkmark" ></label> </div> </td> <td style="color:#A9A9A9;">{{dominios.id_dom}}</td> <td style="color:#A9A9A9;">{{dominios.nombre_activo}}</td> <td style="color:#A9A9A9;">{{dominios.desc_act}}</td> <td style="color:#A9A9A9;">{{dominios.dat_cont_arch}}</td> <td style="color:#A9A9A9;">{{dominios.resp_dom}}</td> <td style="color:#A9A9A9;">{{dominios.estado}}</td> {% endfor %} So what i want to do is every checkbox unique, so i can select the register with the checkbox. I hope someone can help me … -
How do I read all the images with a specific prefix in django?
I am building a Face Recognition system. All the detected faces are stored in a directory. (Its stores both known and unknown) I want to create a log of all the unknown faces. The unknown faces are stored with a prefix unknown_2203.png My Question how do I fetch the unknown.pngs from that directory and show them on a django template? Any help would be great! -
How to replace python 2.7.16 to python 3?
MacBook-Pro:~ bsr$ pip install django DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django in ./Library/Python/2.7/lib/python/site-packages (1.11.29) Requirement already satisfied: pytz in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from django) (2013.7) Due this error unable to install the djengo. pip install django -
Django keeps on putting quotes around table name in mysql query and the query wont work
Table name in MySql is usercreds and the query that django generates works without the quotes around the table name. The model is created using inspectdb command from django, Im trying to django admin panel as a db manager. models.py: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models class Usercreds(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20, blank=True, null=True) password = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'usercreds' settings.py: """ Django settings for admindb project. Generated by 'django-admin startproject' using Django 2.2.11. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
What is the correct solution for uploading images to s3 asynchronously using zappa? (aws serverless)
env django zappa boto3 (s3) The flow what i envisioned is as next User append images by website(input file html) and submit. zappa lambda receive the images and toss to s3 upload function asyncly. website waiting uploaded image and show image url. Two ways to upload images save image to local -> upload(saved_img) encode to byte -> stream as byte problem In the case of the Async function, the / tmp folder seems to point to a different physical location. Save is possible, but cannot be recalled. There is a limit to the number of characters in sns when streaming in bytes. Long files such as images cannot be put in arg. Is there any other good way to upload images to Async? -
how to create a main vue component to communicate with page related components with no npm (with django and django rest framework)
I have coded an IMDB clone website with django and vue via cdn. The vue ui is enhanced with vuetify and the json rest api created by django rest framework is get, put, post or delete by axios. There is no npm or webpack depency and configuration. The repo is installed as a usual django application. I have uploaded the repository with dummy data to github, the link is below. the requirements.txt file has all the django related versions. vue and vuetify versions are 2.x The reason of using vue is to enable inteactive ui. The ultimate aim is to create an alternative admin interface using vue like plain old jquery via cdn. For now, the project runs quite well. However, I have to write all vue component code to all pages. I copy & paste, then change some state related stuff (data) and add or remove some methods. Those components change according to model fields and relation with other models. The main skeleton is same. I have experienced zillions of trials and errors, but I couldn't achieve the way to interact many page related components communicate with one main component. All vue codes exist in templates folder and there … -
I AM GETTING CONFUSED WHEN TO USE ONE TO MANY AND FOREIGN KEY RELATIONSHIP IN DJANGO
Imagine i have a student who can have many academic details,so in this case which one should i use between foreign key and one to many relationship -
Pip shows web socket error and I cannot install any packages
I tried installing django but didn't work. Instead it gave me this error... WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions')': /simple/django/ ERROR: Could not find a version that satisfies the requirement django (from versions: none) ERROR: No matching distribution found for django I tried to install other packages and modules but none of them could be installed. I reinstalled python and while doing that I lose all my previous packages. I had a project with PyQt5 which I could install successfully two weeks ago but after I reinstalled python my packages, modules, etc. where gone and now pip won't work I don't know why. I tried changing my network and tried using my phone's hotspot but it didnt solve the problem. I tried giving the version name of the packages but that didn't work either. My network doesn't have a proxy or is not connected to a vpn. I can download any other stuff but I just cannot download stuff with pip. Thanks in advance! -
Django--complex context or complex template?
I'm rather new to the Django world and am converting an existing Java/Javascript app to Django. The existing app has many complex queries and conditionals. I can solve most of those in the template, but it is starting to get ridiculous. Generally, is it better to put the database hits in the view and have a more complex context to pass to the template or simplify the context and burden the template? Or does it matter? Some quick figures--the database has 44 tables 16 of which are M2M join tables. There are four report templates--the only one I've tackled hits seven different tables. So far, I've found testing things in the template is quicker and more reliable than testing in the view class. But I'm inclined to push more of the logic back to the view and pass a more complex context to the template. Just wondering which way more experienced Django hands go.... -
Page not found (404) Request Method: GET
I keep getting this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/home Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ home/ The current path, home, didn't match any of these. This is my urls.py for the overall project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('hello_world.urls')), ] this is my code for hello_world urls.py from django.urls import path from hello_world import views urlpatterns = [ path('home/', views.hello_world, name='hello_world'), ] this is my code for hello_world views.py from django.shortcuts import render def hello_world(request): return render(request, 'hello_world.html') -
Unable to install django, i get JWT error
When I try to install django (on Google cloud) I get this message: File "/root/lplatform/back/lplatform_api/urls.py", line 3, in <module> from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView ModuleNotFoundError: No module named 'rest_framework_simplejwt' this is my url.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('lplatform_api.urls')) ] and this is my setting.py: REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ), "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", 'rest_framework.authentication.BasicAuthentication' , 'rest_framework.authentication.SessionAuthentication', ), } -
Django: non primary-key auto incremented field
is there a possible way to create a non primary-key auto incremented field like a AutoField/BigAutoField that is not prone to failure(duplicated ids, ...) ? -
Django : Difference between django-admin.py and django-admin
Okay here's the catch. When I create a django project with django-admin.py startproject myproject and starts server like python3 manage.py runserver, it all works fine. However, when I create project with django-admin startproject myproject and starts server like python3 manage.py runserver, it gives me tonnes of system check errors like : django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. or django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application.