Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Main dask task with subtask stuck when finished if runned from django view
I have a django view that should submit a task in dask. This scope of this task to unzip a filefield of a model and then run some other tasks that require the unzipped filepath as argument. The following code is not the real one, but I have same issue also on this minimalist example. The code to run the main task in django view is quite simple because is just a fire and forget: dask_client = Client("tcp://scheduler:8786") fire_and_forget(dask_client.submit(unzip_then_run, object)) The unzip_then_run code is made following instructions def unzip_then_run_basic(dump, es_url): dask_client = get_client() secede() tasks = [] for i in range(10): task = dask_client.submit(run_basic, i) tasks.append(task) results = dask_client.gather(taks) rejoin() The final subtask code is: def run_basic(random): time.sleep(random * 2) return 0 Everything works until the rejoin(), the subtasks end successfully but then nothing happen. Everything seems to be waiting and I don't have information or issues on my worker logs: The reason why I need to wait for subtasks is that I want to update the model with a completed status. If I use fire_and_forget also in the main task everything works fine but then I don't easily know when the task is completed. All the code is running … -
Django Attribute Error: 'NoneType' object has no attribute 'videofile'
I am following this tutorial to create a video uploader in my Django project and have run into this error: ..src/video/views.py", line 9, in showvideo videofile= lastvideo.videofile AttributeError: 'NoneType' object has no attribute 'videofile' I'm sure I am missing something obvious and have been looking for the answer for a while now. Would be grateful for any help. views.py from django.shortcuts import render from .models import VideoUpload from .forms import VideoForm def showvideo(request): lastvideo= VideoUpload.objects.last() videofile= lastvideo.videofile form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context= {'videofile': videofile, 'form': form } return render(request, 'video.html', context) forms.py from django import forms from .models import VideoUpload class VideoForm(forms.ModelForm): class Meta: model = VideoUpload fields = ["name", "videofile"] models.py from django.db import models class VideoUpload(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) from django.conf import settings from django.contrib import admin from django.urls import path from django.conf.urls.static import static from video.views import ( showvideo, ) urlpatterns = [ path('showvideo', showvideo, name='showvideo'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) FYI I updated the name of the model to 'VideoUpload' vs the tutorial. -
The best way to inject social auth to django oauth toolkit
i want to use django-oauth-toolkit and i need to use both social auth (e.g google) and regular django-oauth-toolkit token at the same time. but i do not have idea for handle these two at the same time. -
automatic refreshing <div> with django
I have a form that when it is posted the content of console.html gets changed. for refreshing the page I used the following code but this does not refresh console.html javascript function autorefresh() { // auto refresh page after 1 second setInterval('refreshPage()', 1000); } function refreshPage() { var container = document.getElementById("console"); container.innerHTML= '<object type="text/html" data="../../templates/snippets/console.html" ></object>'; //this line is to watch the result in console , you can remove it later console.log("Refreshed"); } index.html <script>autorefresh()</script> <div id="console" > {% include 'snippets/console.html' %} </div> view.py def index(request): if request.method == "GET": return render(request, 'index.html') if request.method == "POST": # If the form has been submitted... form=InputForm(request) form.do_function() return render(request, 'index.html') -
AttributeError: 'ModelChoiceField' object has no attribute 'specification'
I have looked at previous questions posted and have not found an issue or a response that is applicable to my current situation. So I am hoping that someone will read my post and help me with my specific issue. A description of my issue: I currently have a form named TestCaseStepForm. It has a field "Requirements". What I am trying to do is have this field only display results based on this query: requirement = forms.ModelChoiceField( queryset=Requirement.objects.filter(specification=test_case.specification.id ).filter(process=test_case.process.id).filter(status='Approved'), widget=forms.Select(attrs={'class': 'form-control'}), required=False, empty_label='') enter image description here I know that the query works since I am using it to render data in an unlated table. It is just not filtering the data in the select field. Any help to tell me what is wrong with my field would be greatly appreciated. -
Need to show icon with boolean field in django admin
I would like to know how to show the icons along with the True, False on editable boolean field. Please check the below image. The same icons which we see on list page (Red, Green). The objective is to easily visualize the values. Please help me with that. -
Django - Check if arrayfield element is in a string
So I want to write a query to find objects with ArrayField where the one of the element in ArrayField is in another string For example a Book Model, containing ArrayField named 'Synonyms', Book1 Synonyms : ['very good','awesome'] Book2 Synonyms : ['good','okay'] So what I am trying to do is, I want to do some kind of search, let say if user search for 'It was very good', so it result in Book1. I tried to split the user search string into array, and do a loop like for x in user_string.split(): Book.objects.filter(synonyms__icontains = x) It works but, IF the one of the synonyms is "Haha", and then the user search string is "Ha", it will still return that object. What is want is the query to return object with exact element in the string. For example, if the user search containing word "good", it will return book2, but if the search containing word "very good", it will return book1 -
How to resolve 'User' object is not callable error in Django?
I am trying to serialize my user permissions, including the associated group permissions, and access them via an API endpoint. The goal is to create something like this: { "permissions": { "auth.add_user" : True, "auth.add_group" : True, "auth.add_userproxy" : False, } } But somehow I get the following error message when I call my API:TypeError: 'User' object is not callable. The error message is refering to line all_permissions = self.request.user(is_superuser=True).get_all_permissions() # Get User Permission API class UserPermissionAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserPermissionSerializer def get(self, request): #permissions = self.request.user.get_all_permissions() all_permissions = self.request.user(is_superuser=True).get_all_permissions() # Line Error Message is refering to user_permissions = self.request.user.get_all_permissions() permissions = {p: p in user_permissions for p in all_permissions} data = { 'permissions': permissions } serializer = UserPermissionSerializer(data) return Response(serializer.data) I work with a custom user model class User(AbstractUser):. Im happy for any clarification. Why can i not call the user? -
Python and Django ,<built-in function id> error function, where is the issue
I have the following class: class Income(models.Model): income=models.DecimalField() date=models.DateField() In my views I have created an algo that give me the possibility to collect all date monthly, like the following: now=datetime.datetime.now() now=now.year income=dict() for year, month, totals in(Income.objects.values_list( 'date__year', 'date__month'). annotate(totals=ExpressionWrapper(Sum(F('income')), output_field=FloatField())).values_list('date__year', 'date__month', 'totals')): if id not in income.keys() and year == now: income[id]=list(defaults) index=month-1 income[id][index]=totals If I set now in the following manner, it works perfectly: now=datetime.datetime.now() now=now.year But If I set a form in the following manner: #models class Timing(models.Model): reference_year=models.DateField() #views nows=[] form = TimingForm(request.POST or None) if request.method == 'POST': if form.is_valid(): nows = form.cleaned_data['reference_year'] nows=nows.year Python give me the following errors: <built-in function id> Why?? -
Python Django Edit HTML rows and update database
I have a table and I wish to add an edit button that updates the certain record both visually and in the database. The HTML I have. {% for work_entry in work_entries %} {% if work_entry.date == date.date %} <form action="{% url 'work_entries:object_edit' work_entry.id %}" method="post"> {% csrf_token %} <tr> <td> <button onclick="return confirm('Are you sure you want this edit?')">Edit </button> </td> <td> <form action="{% url 'work_entries:object_delete' work_entry.id %}" method="post"> {% csrf_token %} <button onclick="return confirm('Are you sure you want to delete this record?')">Delete </button> </form> </td> <td>{{ work_entry.id }}</td> <td><input type="text" value="{{ work_entry.description }}" name="description"></td> <td><input type="number" value="{{ work_entry.num_hours }}" name="hours"></td> </tr> </form> {% endif %} {% endfor %} The views.py def object_edit(request, object_id): record = get_object_or_404(WorkEntry, pk=object_id) if request.method == "POST": record.description = request.POST["description"] record.num_hours = request.POST["hours"] record.save() return redirect("/employeePage") return render(request, "employeePage.html") And urls.py app_name = "work_entries" urlpatterns = [ path("", views.employee_view, name="employeePage"), url(r"^delete/(?P<object_id>[0-9]+)/$", views.object_delete, name="object_delete"), url(r"^edit/(?P<object_id>[0-9]+)/$", views.object_edit, name="object_edit"), ] I used an input tag in the as I thought that would allow me to change data and save it. However this is giving me MultiValueDictKeyError at /employeePage/edit/14/ 'description' error. I am not too experienced with jquery which from research I saw that could work but I … -
why pk_range method of Django not working?
views.py from django.shortcuts import render from .models import images def next_img(request,pk): if request.method == "GET": images_data = images.objects.filter(pk_range=(int(pk)+1,int(pk)+8)) return render(request,"images.html",{'image':images_data}) I just want to retrieve the images list objects from the given range by using their primary keys and pk_range=(int(pk)+1,int(pk)+8) giving below error. FieldError at /images/next/8/ Cannot resolve keyword 'pk_range' into field. Choices are: id, image, name, type, user, user_id -
How to test/simulate broken database connection
I have written logic to return custom errors when my application cannot connect to the database (why that can happen is out of the scope for this question). I wish to write unit tests for this, specifically to see the response status codes when: there is a valid connection to the database. This is easy as Django automatically creates a "test" database whenever I run any tests. there isn't a valid connection to the database. Unfortunately, I cannot find any documentation about this. Is it possible to run that test by somehow simulating that something has gone wrong with the database connection? -
django invalid form in user field
views.py def view_form(request, template_name='form.html'): user = request.user if request.method == "POST": form = my_Form(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.user_mytable = request.user instance.save() else: print('invalid') else: form = my_Form() return render(request, template_name,{'form':form}) forms.py class my_Form(forms.ModelForm): class Meta: model = my_table fields = ('__all__') models.py class my_table(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) user_mytable = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) field1 = models.FloatField(blank=True, null=True) field2 = models.FloatField(blank=True, null=True) field3 = models.TextField(max_length=150,blank=True, null=True) time = models.TextField(blank=True, null=True) i get invalid form in user_mytable This field is required. any idea how to fix it ?because i use request.user -
Deploying Django API to Heroku fails because of pkg-resources
I'm trying to deploy to Heroku a Django API. I've set everything up but when I run git push heroku master while installing the requirements.txt file the following error comes up: remote: ERROR: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_7907c86d507c2a1ffc4ecbbc0e82799b/requirements.txt (line 25)) (from versions: none) remote: ERROR: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_7907c86d507c2a1ffc4ecbbc0e82799b/requirements.txt (line 25)) remote: ! Push rejected, failed to compile Python app. and the push fails. I've deleted this package from the requirements file but if you notice it seems the Heroku is trying to install from some tmp/build file and the one in my project. How can I fix this? -
Sometimes I am unable to see printed string (print()) in console or terminal (CLI) in django.Iam using powershell
Suppose while debugging I print something (using print()), inorder to get some idea regarding bug.But all of a sudden the print sops working.Iam using Django 2.2. -
Distance function requires a geometric argument in position 2
I have two model shop and customer shop class Shop(models.Model): distance = models.PositiveIntegerField(null=True) shop_location = models.PointField(null=True, default=Point(28.49, 77.33)) customer class Customer(models.Model): customer_location = models.PointField(null=True, default=Point(28.49, 77.33)) I want to set the filter on the shop. The shop will show to the customer if the distance between shop and customer under the distance given by the shop and my views.py from django.contrib.gis.db.models.functions import Distance Shop_list = Shop.objects.filter( distance_gte=Distance('shop_location', Customer.customer_location) ) I am getting the error Distance function requires a geometric argument in position 2 -
Does Sequelize have a way to find or select a subset of fields?
Say I have the following Django code using .only(): Person.objects.only("name") Is there a similar way in Sequelize to generate SQL (preferably not using Raw Queries) which returns only a subset of all the fields stored in my DB? -
django-admin sum multiple columns
I have a model with several fields. And I wanted to add another field in django-admin (list_display), where it is the sum of all fields. Model's class Model1(models.Model): field1 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) field2 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) field4 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) def __str__(self): return str(self.id) Model's Admin class Model1Admin(admin.ModelAdmin): model = Model1 list_display = ('field1','field2',<!--Sum of (field1,field2,field3,field4,field5-->) admin.site.register(Modell,Model1Admin) i am using the last version of django. -
How to properly import list of functions with import * and __all__?
I have this simplified structure of files: utils/ |- __init__.py |- script1.py |- script2.py |- script_report.py /views.py script_report.py has lots of classes and functions and I want to import some of them in other scripts. On my views.py (and also other scripts) which are outside utils/ I want to import a specific list of functions from script_report.py (this list is always the same) but I don't want to list them all in every script I use, also because I keep adding more functions that need to be imported, so I would like to use from .utils.script_report import * and only add the new functions to one place only. In my __init__.py file I have: from .utils.script_report import (function1, function2) __all__ = ['function1', 'function2'] So in views.py I tried from .utils import * but that doesn't seem to work. What is the correct way to do it? I know that if I define __all__ inside script_report.py then from .utils.script_report import * works fine. Note: I have gone through this but can't find the correct way to adapt it. -
Infinite Scroll Django does not work proprely
Note: Intro: I am using this https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html to add infinite scroll with django. Just in case anyone wants the detailed code its on Github.It is a very simple code The Problem: Rather than having infinite scroll I only get more link so it does not work properly In my static folder. I made a folder called js and added 3 files in it infinite.min.js, jquery-3.1.1.min.js, jquery.waypoints.min.js I copied the code exactly from the github in my files BELOW IS MY VIEW from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.models import User from .models import Post from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import HttpResponse def home(request): numbers_list = range(1, 1000) page = request.GET.get('page', 1) paginator = Paginator(numbers_list, 20) try: numbers = paginator.page(page) except PageNotAnInteger: numbers = paginator.page(1) except EmptyPage: numbers = paginator.page(paginator.num_pages) return render(request, 'blog/home.html', {'numbers': numbers}) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') MY base.html <!DOCTYPE html> {% load static %} <html> <head> <!-- … -
Choosing between makefile and setup.py for a django project
I have a Django project with backend(Djangorest) and frontend(React) as two apps in the same project. I want to create a script to activate the virtual environment and install requirements. How do I choose between using a makefile or setup.py? -
Condition not working for 2 different apps in a Django template
I have created a project with 2 apps: 1.Core for items model to be viewed in home page 2. Score with posts model The home.html is mainly for listing items by designers, the designers/users might have posts as well so I am trying to show buttons for designers/userswho have posts and hide them if the users don't have posts. I have added the code but the button for the designers/usersposts is still showing. App No. 1 CORE Core Models.py class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Core views.py class HomeView(ListView): model = Item paginate_by = 12 template_name = "home.html" ordering = ['-timestamp'] # context_object_name = 'posts' (I have commented this part as it is from Score Models when included the home page become 404 error) Here is the Core URL urlpatterns = [ path('', HomeView.as_view(), name='home'), App No.2 Score Score Models.py: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to=upload_design_to) Home.html template {% if post.designer %} <a href="{% url 'score:user-posts' item.designer.username %}"> <button style="margin-top: 10px;text-transform: none;" button type="button" class="btn btn-success btn-sm btn-block"> Check my posts</button> </a> {% else %} Show Nothing {% endif %} I dont know what might the reason for now working … -
Django how to create dynamic dropdown filter to the queryset
I have created an app that give me the possibility to collect and store all daily income. In this case I have created the following model: class Income(models.Model): income=models.DecimalField() date=models.DateField() In my views I have created an algo that give me the possibility to collect all date monthly, like the following: now=datetime.datetime.now() now=now.year income=dict() for year, month, totals in(Income.objects.values_list( 'date__year', 'date__month'). annotate(totals=ExpressionWrapper(Sum(F('income')), output_field=FloatField())).values_list('date__year', 'date__month', 'totals')): if id not in income.keys() and year == now: income[id]=list(defaults) index=month-1 income[id][index]=totals All works perfectly. But now I want to give the possibility to be able to choose the year manage the now variable. So for this aim I have tried to create a new model, as the following: class Timing(models.Model): TYPE=[ ('2020','2020'), ('2021', '2021'), ] reference_year=models.CharField('Azienda/Privato', max_length=30, choices=TYPE, default="") Now I want to create a dropdown menu in my templates to choose the year and subsequently to update the views updating the now variable. Do you have any ideas to implement this function? -
Django table model
I am relatively new to Django and would like to use it to build the back end of my app. I am using Django.DB models and Django rest-framework. I am trying to make a system where each company in my DB has a table that stores 3 records. Item, Price, and Description but I have no idea what type of field that would be or how one would do that. I was assuming that you would use a one-to-many field but there doesn't seem to something like that. Thank You in advance. -
dj-rest-auth: get access_token/code for facebook social media authentication
I was trying to implement Social Media Authentication with Facebook using dj-rest-auth. I am following the instructions in the docs Where could I get the access_token/code that's mentioned in the docs when calling the API endpoint /dj-rest-auth/facebook/ (POST) Thank you