Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add new function to jquery.formset django
i want to know total price for each row input i make a script for that purpose , but it only write first row result , i've used inlineformset_factory with jquery.formset.js jquery.formset.js this is the script <script> $('tr').on('keyup','.qnt','.price',()=>{ totalPrice(); }) function totalPrice(){ let qnt=$(".qnt").val(); let price=$(".price").val(); $(".cash").val(qnt * price); } $(function(){ $('.tb1 tr:last').formset({ prefix:'{{items.prefix}}', addText:'add', addCssClass:'btn btn-info ', deleteText:'delete', deleteCssClass:' hide', added:function($row){ $('.item').select2(); } }) $(".item").select2(); }) </script> <tbody class="tbody tb1 "> {% for item in items.forms %} {{item.errors}} <tr class="p-0 col-12 tr"> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.quantity | add_class:'col-12 text-center qnt'}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.price | add_class:'col-12 text-center price'}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.cash | add_class:'col-12 text-center cash'}} </div> </td> </tr> {% endfor %} </tbody> i need to price * quantity and write the result into cash field , it works only for he first row , for the rest doesnt work ?! i appreciate your helps please -
Django Foreign key on Modelform
I'm working on the project that Django tutorial provides. I'm just trying to expand functionality like: login, registration, poll CRUD and so on. I have two models: class Question(models.Model): question_text = models.CharField(max_length=70) describtion = models.TextField(null=True, max_length=200) pub_date = models.DateTimeField(auto_now=True) def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Thet connected via foreignkey. So, each choice has it's own question. And set up in admin dashboard,so if i try to create new question i can add as many choices i want. I just configured it in admin.py. Problem is this I want to have a form that user can submit a question and its choices. I've done first part that user can create poll question, but cannot handle to add choices while creating question itself. Choices should automatically connected to Question. Please help me solve this problem. My ModelForm looks like this class QuestionForm(ModelForm): class Meta: model = Question fields = ['question_text','describtion'] widgets = { 'question_text': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter name for poll','id':'title'}), 'describtion': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter name for poll','id':'describtion'}) } -
Using PyTorch with Celery
I'm trying to run a PyTorch model in a Django app. As it is not recommended to execute the models (or any long-running task) in the views, I decided to run it in a Celery task. My model is quite big and it takes about 12 seconds to load and about 3 seconds to infer. That's why I decided that I couldn't afford to load it at every request. So I tried to load it at settings and save it there for the app to use it. So my final scheme is: When the Django app starts, in the settings the PyTorch model is load and it's accessible from the app. When views.py receives a request, it delays a celery task The celery task uses the settings.model to infer the result The problem here is that the celery task throws the following error when trying to use the model [2020-08-29 09:03:04,015: ERROR/ForkPoolWorker-1] Task app.tasks.task[458934d4-ea03-4bc9-8dcd-77e4c3a9caec] raised unexpected: RuntimeError("Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method") Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/tensor/lib/python3.7/site-packages/celery/app/trace.py", line 412, in trace_task R = retval = fun(*args, **kwargs) File "/home/ubuntu/anaconda3/envs/tensor/lib/python3.7/site-packages/celery/app/trace.py", line 704, in __protected_call__ return self.run(*args, **kwargs) … -
Create new user with Django Rest Framework JSON Web Token
I am using Django REST framework, with Simple JWT. I am trying to create a user registration page. Currently, I am getting this error Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. Full error message here: Under settings.py, I have added this: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',), } My project urls folder: urlpatterns = [ path('admin/', admin.site.urls), path("", include("my_api.urls")), path('api-auth/', include('rest_framework.urls')), path('api/token', TokenObtainPairView.as_view()), path('api/token/refresh', TokenRefreshView.as_view()), ] And this is my app's view for my registration endpoint. def register(request): if request.method == "POST": email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "my_api/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: # Creates a hashed password. #password = make_password(password) user = User.objects.create_user(username=email, email=email, password=password) user.save() except IntegrityError as e: print(e) return render(request, "my_api/register.html", { "message": "Email address already taken." }) login(request, user) return HttpResponse("Successfully created account.") else: return render(request, "my_api/register.html") -
Django model - making db value as dependent from others values from db
i have models as follow: models.py class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=30) cat = models.IntegerField() read_pages = models.IntegerField() total_pages = models.IntegerField() read_pages_of_book = models.FloatField(default=round(read_pages/total_pages, 2)) status = models.BooleanField(default=(False if read_of_book < 1 else True)) Please consider read_pages_of_book variable. Is this possible to have value like that as dependent from other values? Or maybe I shouldn't keep this value in db and just use both 'read_pages' and 'total_pages' on my views.py and the send it as a context? I'm really trying to understand this concept and to use it well so for any help i will be gratefull. -
How to handle uploaded excel file in Django
I try to display some data in console during the file upload. I have tested that I can convert uploaded excle files thrue a PANDAS script that way but error occureed. I used: in settings.py: FILE_UPLOAD_HANDLERS = [ 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ] view: def excle_upload(request): if request.method =='POST': form = ExcleForm(request.POST, request.FILES) if form.is_valid(): filehandle = request.FILES['file'] path = filehandle.temporary_file_path df = pd.read_excel(path) print(df.head()) form.save() return redirect('excle_list') else: form = ExcleForm() return render(request, 'odo_correction/excle_upload.html', {'form':form}) Error: Django Version: 3.1 Exception Type: ValueError Exception Value: Invalid file path or buffer object type: <class 'method'> -
heroku django/react deployment not working correctly
I have deployed my django/react app to heroku but only the home page gets rendered but my data that I have in my sqlite database does not get rendered. If I were to go to /api then django shows me this HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "todos": "https://this-todo.herokuapp.com/api/todos/" } but when I go to that actual route with api/todos it still doesn't not show me my todos. What might I be doing wrong. I followed this tutorial to deploy https://librenepal.com/article/django-and-create-react-app-together-on-heroku/ -
URL redirect issue in python using Django framework
here we have redirect code return HttpResponseRedirect('/{}-meters-to-{}/'.format(value, unit)). value is not appending to URL some time but the output is showing. path('meters-to-centimeters/', views.functon1, name='convert_m_cm'),# landing page url path('meters-to-millimeters/', views.function1, name='convert_m_mm'),# landing page url path('<str:data>-meters-to-<str:to_units>/', views.function1_views, name='m_conversion_views'),# details page /output page url [i gave input as 5 and slect inches unit but URL is not related to that.] -
Can't get logged out
views.py file I can register and login but once logged in , the logout functionality doesn't work. To log out i must go to admin page and log out which is also only possible if the user is superuser to admin page def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user= auth.authenticate(username= username, password= password) if user is not None: auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('dashboard') else: messages.error(request, 'Invalid Credentials') return redirect('login') else: return render(request, 'accounts/login.html') def logout(request): auth.logout(request) messages.success(request, 'You are now logged out') return redirect('login') urls.py file urlpatterns= [ path('login/', views.login, name= 'login'), path('register/', views.register, name= 'register'), path('dashboard/', views.dashboard, name= 'dashboard'), path('logout/', views.logout, name= 'logout'), ] html content {% if user.is_authenticated %} <li class="dropdown mega-dropdown"> <a href="{% url 'dashboard' %}" role="button"><i class="fa fa-sign-in" aria-hidden="true"></i>Dashboard</a> </li> <li class="dropdown mega-dropdown"> <a href="{% url 'login' %}" role="button"><i class="fa fa-sign-in" aria-hidden="true"></i>Logout</a> </li> {% else %} <li class="dropdown mega-dropdown"> <a href="{% url 'login' %}" role="button"><i class="fa fa-sign-in" aria-hidden="true"></i>Register/Login </a> </li> {% endif %} -
Unhandled Rejection (TypeError): Cannot read property 'error' of undefined in Reactjs
plz help solving this err here is the image of the error -
Django unable to find page
For some reason, Django is not picking up a certain template and I am unsure why. Link in navbar.html <a class="dropdown-item" href="/course/posts/{{ course.slug }}">{{ course.title }}</a> views.py def posts(request, course_slug, *args, **kwargs): course = Course.objects.get(slug=course_slug) posts = Post.objects.filter(course__id=course.id) courses = Course.objects.all() context = { 'posts' : posts, 'courses' : courses, } return render(request, "course/posts.html", context) urls.py from django.conf.urls import url from . import views from . import admin_views app_name = 'course' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^posts/(?P<course_slug>\w+)$', views.posts, name='posts'), url(r'^admin/course/create$', admin_views.create, name='create'), url(r'^admin/course/update/(?P<post_id>[0-9]+)$', admin_views.update, name='update') ] Not sure where my problem is. -
How can I register a custom filter in Django
I want to register a simple filter in Django in order to concat two strings in a template. I found many questions about this here, but seemingly no answer solves my problem. settings.py 'MedAbrDirk.apps.MedabrdirkConfig', 'MedAbrDirk.templatetags', MedAbrDirk/templatetags/my_tags.py from django import template register = template.Library() @register.filter() def kette(arg1,arg2): return str(arg1) + str(arg2) MedAbrDirk/templates/MedAbrDirk/base.html {% load my_tags %} <div class="container-fluid"> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul class="nav nav-sidebar"> <li class="dropdown"> <a href="#" class="dropdown-toggle-menu" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Rechnungen<span class="caret"></span></a> <ul class="dropdown-menu"> {{'test'|kette:'test2'}} <li><a href="{% url app_var|kette:'eingabe' %}">Rechnung eingeben<span class="sr-only">(current)</span></a></li> Still, in the browser I get: "Invalid filter: 'kette'" I have no idea what causes this. I have deleted the pychache folder, I have restarted my gunicorn several times. Any advice? -
Getting the following error: Could not find a version that satisfies the requirement command-not-found==0.3
I am deploying a Django app using Heroku. When I called "git push heroku master" in cmd, I got the following error: "Could not find a version that satisfies the requirement command-not-found==0.3". When I run "sudo apt-get install command-not-found", I find that command-not-found is version 20.04.2. However, pip freeze tells me command-not-found is version 0.3. -
Suggestion on Django, mySQL and charts
I will be starting a new project which will include Django, mySQL and the output of the DB tables would show some line and bar graphs. I need suggestion on which could the right tool to do so. The project will be an replacing Grafana (since its loading data very slowly and not reliable to me.) I never worked on Django mySQL to output on charts, I google a few like Chartjs, anychart, d3 which look to be good options. Are there any tools suggested to look after before giving them a green flag? -
I am getting objects in column to which I have applied foreignkey rather the actual string name.How to solve this error
I am having two tables one is myprofile and second is mypost .I am trying to user the username from my profile table into mypost table to keep in as the value of uploadedby but rather than getting the name of the user I am get objects like myprofile object(2) in my uploadeby column ,how to solve it. My models.py looks like: class MyProfile(models.Model): objects = None name = models.CharField(max_length = 100) user = models.OneToOneField(to=User, on_delete=CASCADE) age = models.IntegerField(default=18,validators=[MinValueValidator(18)]) email = models.EmailField(null=True, blank=True) address = models.TextField(null=True , blank=True) status = models.CharField(max_length= 20, default= "single", choices=(("single","single"),("married","married"),("commited","commited"))) gender = models.CharField(max_length= 20, default="female", choices=(("female","female"),("male","male"))) phone_no = models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")],max_length=15,null=True, blank=True) description = models.TextField(null=True,blank=True) pic = models.ImageField(upload_to="images\\", null=True) def _str_(self): return "%s" % self.user class MyPost(models.Model): pic = models.ImageField(upload_to="images\\", null=True) subject = models.CharField(max_length = 200) msg = models.TextField(null=True, blank=True) cr_date = models.DateTimeField(auto_now_add=True) uploaded_by = models.ForeignKey(to=MyProfile, on_delete=CASCADE, null=True, blank=True) def _str_(self): return "%s" % self.subject my views.py looks like: @method_decorator(login_required, name="dispatch") class MyPostCreate(CreateView): model = MyPost fields = ["subject", "msg", "pic"] def form_valid(self, form): self.object = form.save() self.object.uploaded_by = self.request.user.myprofile self.object.save() return HttpResponseRedirect(self.get_success_url()) Please help me to figure out my mistake and how to solve it -
How to add the appointment data from Angular Scheduler app to a local database?
I am using the syncfusion ej2 Angular Scheduler App, I want to know that how can i add the appointment data that i provided in it to my local database. What should be the correct approach to do it in django if i want to add the data to mongodb? -
Ajax pagination with class based view
I am trying apply ajax with pagination on my app .Using Class based Listview #views.py class HomePage(ListView): model = Video template_name = 'index.html' def get_context_data(self, **kwargs): context = super(HomePage, self).get_context_data(**kwargs) videos = Video.objects.filter(category='sub') paginator = Paginator(videos, 5) page = self.request.GET.get('page2') try: videos = paginator.page(page) except PageNotAnInteger: videos = paginator.page(1) except EmptyPage: videos = paginator.page(paginator.num_pages) context['videos'] = videos if self.request.is_ajax(): html = render_to_string('videos/index.html', context, request=self.request) print(html) return JsonResponse({'form' : html }) The Home template script <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '.page-link', function(event){ event.preventDefault(); var page = $(this).attr('href'); console.log(page) $.ajax({ type: 'GET', url: , data: {'page':'{{ page.number }}'}, dataType: 'json', success: function(response){ $('#ajax_page_template').html(response['form']) console.log("success") }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> 1.The current error is in views.py local variable 'html' referenced before assignment 2.And what should I put in ajax --url: I tried to put url:page but that return url to 127.0.0.1:8000/?page=2/?page=2. -
environment variables not accessible to gunicorn
I have a django project and linux server. On the server, i have set my secret key in bash_profile as - export SECRET_KEY=<SECRET_KEY> Now, I am able to use this env variable in my django project as - SECRET_KEY=os.environ.get('SECRET_KEY') I use "python manage.py runserver" to run the project and everything works fine. Same project when I am trying to run using gunicorn server, SECRET_KEY=os.environ.get('SECRET_KEY') gives error. How can I use linux environment variables through gunicorn also? -
How to connect two objects of two models together in Django
This is my models.py from django.db import models class Movie(models.Model): title = models.CharField(max_length=50) release_time = models.DateTimeField() def __str__(self): return self.title class Ticket(models.Model): username = models.CharField(max_length=50) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) #movie_time = models.ForeignKey(Movie.release_time, on_delete=models.CASCADE) In class Ticket, I want to get get two objects from the Movie class, which are the title and the release_time. I managed to get one of them using __str__(self) function, I want Movie.title in the movie variable and also I need the selected Movie objects's release_time in the movie_time variable(I've written the pseudocode of what I want in the commented line). How can I do the same? Any help will be Appreciated! -
Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4
I am learning django and creating a todo app using it. while setting up the django rest framework api. I am getting an unusual error. I am using django for some time, but never got the same error before. I don't know why is this error coming The error is as below -
Django with Postgresql update object, prevent order re-ordering
in django production mode with postgreSQL, When I got an still existing object/row from the database, edit/update it and store it back, the row is moved to the end of the table. object 1 object 2 object 3 after done editing object 1 object 2 object 3 object 1 models.py class itemModels(models.Model): name = models.CharField(max_length=50) photo = models.ImageField(max_length=200, blank=True, default="default.png") photo2 = models.ImageField(max_length=200, blank=True, default="default2.png") price = models.DecimalField(max_digits=6, decimal_places=2) sku = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=255) def __self__(self): return self.name views.py class itemViewSet(viewsets.ModelViewSet): queryset = itemModels.objects.all() serializer = itemSerializers() renderer_classes = [TemplateHTMLRenderer] template_name = 'product-list.html' lookup_field = 'pk' # list all item def list(self, request): queryset = itemModels.objects.all() context = {'posts': queryset} return Response(context) # serializer form def serializer_list(self, request): serializer = itemSerializers() return Response({'serializer': serializer}, template_name='product-create.html') def retrieve(self, request, pk): profile = get_object_or_404(itemModels, pk=pk) serializer = itemSerializers(profile) return Response({'serializer': serializer}, template_name='product-edit.html') def update(self, request, pk): profile = get_object_or_404(itemModels, pk=pk) serializer = itemSerializers(profile, data=request.data) if serializer.is_valid(): serializer.save() print('status: status.Item Update') return redirect('item') else: print('status: status.Item Bad Update') i want to prevent this re-ordering happen, is there something i miss out ? thanks guys -
Exception Value: Cannot use None as a query value Django Framework
Help required, please. I'm doing a level 6 Diploma in Software Development. Right now I'm doing a project that requires a gym app to be built. We've decided on using Python/Django as our language/framework. I have my models, urls, views, and templates working thus far. (Videos display and its own page) However, I need to implement a search bar to search both video content and text context within the app. I have the video model set up in /admin. migrations are done. Do I need another model to search for normal content in my app? The search bar is in my base.html template. I want to use the search bar to do a query and pass the results onto a results template page which extends base.html. The error I get is the below; Exception Type: ValueError Exception Value: Cannot use None as a query value Can someone point me in the right direction? photos of code attached. base.html <!-- Navbar Right Side --> <div class="navbar-nav"> <form class="form-inline my-1 my-lg-0" action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search" aria-label="Search"> <a class="btn btn-secondary my-2 my-sm-0" href='/gymapp/videos/' type=submit>Search</a> </form> <a class="nav-item nav-link" href="#">Login</a> <a class="nav-item nav-link" href="/register">Register</a> </div> search_results.html {% extends "gymapp/base.html" … -
How to save and display data in same view in functions in DJANGO
I have two functions in my applications in which i am using one to save data in database and one to display data from database at the same time. I don't know how this will work. My Url is for the two functions path('new_paper', views.newpaper_request, views.All_NewPaper), Function to get data from database In views def All_NewPaper(request): newpapers = AnswerStudent.objects.all() return render(request, 'attempted.html', {'newpapers':newpapers}) In Template .html {% for newpaper in newpaper %} {{ newpaper.Teacher_Name}} {% endfor %} Function to Save data into database. def newpaper_request(request): newpapers = NewPaper.objects.order_by('-id') if request.method == 'POST': form = NewPaperForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Saved") return redirect('/new_paper') else: form = NewPaperForm() return render(request, 'new_paper.html', { 'form': form, 'newpapers': newpapers, }) The code is correct for both functions if i pass only one of them.. But i want when someone open the page both of the functions should work.. -
Django, PIL: No such file or directory
I am working on a django project with the face-recognition library, but I get this error: Traceback (most recent call last): ... File "/.../site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/.../views.py", line 51, in post test_1 = face_recognition.load_image_file(path_) File "/.../site-packages/face_recognition/api.py", line 86, in load_image_file im = PIL.Image.open(file) File "/.../site-packages/PIL/Image.py", line 2878, in open fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 2] No such file or directory: 'http://127.0.0.1:8000/media/profile_pics/me.jpg' This is what I have: req_user = Profile.objects.all().filter(user__username=user_) req_img = req_user.values('image')[0]['image'] #.partition("/")[2] path_ = 'http://127.0.0.1:8000/media/'+req_img test_1 = face_recognition.load_image_file(path_) test_1_enc = face_recognition.face_encodings(test_1)[0] test_2 = face_recognition.load_image_file(newimage) test_2_enc = face_recognition.face_encodings(test_2)[0] results = face_recognition.compare_faces([test_1_enc],test_2_enc) if results[0]: print('Match') else: print('Please login with your password') The image is located at path_ Thank you for any suggestions -
How can I serialize ManyToManyField in django?
I want to make a post model and show the person who clicked like. So after creating models and serializers, the server runs and the following error occurs. TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use liker.set() instead. I think the error occurred during the serialization of ManyToManyField, but I don't know the solution. How can I implement the features I want? Here is my code. models.py class post (models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='authorName', null=True) title = models.CharField(max_length=40) text = models.TextField(max_length=300) image1 = models.ImageField(blank=True, null=True) image2 = models.ImageField(blank=True, null=True) image3 = models.ImageField(blank=True, null=True) image4 = models.ImageField(blank=True, null=True) image5 = models.ImageField(blank=True, null=True) like = models.IntegerField(default=0) liker = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='liker', blank=True) tag1 = models.CharField(max_length=20, null=True) tag2 = models.CharField(max_length=20, null=True) tag3 = models.CharField(max_length=20, null=True) tag4 = models.CharField(max_length=20, null=True) tag5 = models.CharField(max_length=20, null=True) class comment (models.Model) : author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) post = models.ForeignKey(post, on_delete=models.CASCADE) text = models.TextField(max_length=200) class view (models.Model) : post = models.ForeignKey(post, on_delete=models.CASCADE) viewCnt = models.IntegerField(default=0) serializers.py class commentSerializer (serializers.ModelSerializer) : class Meta : model = comment fields = ['author', 'text'] class viewSerializer (serializers.ModelSerializer) : class Meta : model = view field = ['viewCnt'] class postSerializer (serializers.ModelSerializer) : author = serializers.CharField(source='author.username', read_only=True) image1 …