Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not render the home page template in DJango mini project,
views.py: from django.shortcuts import render from django.shortcuts import HttpResponseRedirect from myapp.form import LoginForm from myapp.models import Login # Create your views here. def index(request): myForm=LoginForm() if request.method=="POST": name=request.POST['name'] password=request.POST['password'] new_data=Login(Name=name,Password=password) new_data.save() form=LoginForm(request.POST) if form.is_valid(): return HttpResponseRedirect("thanks") return render(request,'index.html',{'form':myForm}) def thankyou(request): return render(request,'thanks.html') and this is my urls.py: from django.contrib import admin from django.urls import path from myapp import views urlpatterns = [ path('',views.index), path('thanks',views.thankyou), path('admin/', admin.site.urls), ] i have created a model template view for sample login form, except home page, everything is fine, even superuser also created. form.py: from dataclasses import field from pyexpat import model from django import forms from myapp.models import Login class LoginForm(forms.Form): class Data: model=Login, field=[ 'Name','Password' ] admin.py: from django.contrib import admin # Register your models here. from myapp.models import Login admin.site.register(Login) models.py: from django.db import models # Create your models here. class Login(models.Model): Name=models.CharField(max_length=20) password=models.CharField(max_length=20) base.html: <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% block content %} {% endblock content %} </body> </html> index.html: {% extends 'base.html' %} {% block content %} <h1>Application Form</h1> <form action="" method="post"> Name: <input type="text" name="name"><br> Password:<input type="password" name="password"><br> <input type="submit"> </fomr> {% endblock content %} thanks.html: {% extends 'base.html' %} {% block content %} <h1>Thankyou</h1> {% endblock … -
Django-single user with multiple employee account for each organization flow
Im creating an application where user is having multiple employee account with each organization. When i login with user credential it has redirect to choose organization page and after choosing organization i has to redirect to dashboard page where all details related to the organization should be displayed. My doubt is when im doing multiple api calls in dashboard page whether i need to pass organization id in all requests? ex: organization//team//members/ if this goes like this means url will grow long.Please help on this. Thanks in Advance. -
local variable 'zip' referenced before assignment in django
when i am running this code in django its throwing error UnboundLocalError: local variable 'zip' referenced before assignment. what to do i dont know can anyone please help me out. import matplotlib.pyplot as plt plt.figure(figsize=(10,8)) # Black removed and is used for noise instead. unique_labels = set(labels) colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))] for k, col in zip(unique_labels,colors): if k == -1: # Black used for noise. col = [0, 0, 0, 1] class_member_mask = labels == k xy = embedding[class_member_mask & core_samples_mask] plt.plot( xy[:, 0], xy[:, 1], "o", markerfacecolor=tuple(col), markeredgecolor="k", markersize=14, ) xy = embedding[class_member_mask & ~core_samples_mask] plt.plot( xy[:, 0], xy[:, 1], "o", markerfacecolor=tuple(col), markeredgecolor="k", markersize=6, ) plt.title("Estimated number of clusters: %d" % n_clusters_) -
What is the use of .changed() in django celery. : PeriodicTasks.objects.changed(self)?
This code has been written by someone else and i just don't know what does .changed do? class PeriodicAlarm(PeriodicTask): title = models.CharField( ) user = models.ForeignKey( ) severity = models.IntegerField() notify = models.BooleanField( ) emails = ArrayField() category = models.IntegerField() periodicity = models.CharField() def save(self, *args, **kwargs): if self.id is None: create = True else: create = False if create and self.user.get_account().has_alarm_limit_reached(): raise ValidationError({'non_field_error': 'Alarm limit reached'}) self.name = uuid.uuid4().hex # self.name = self.user.email + '|' + self.title super(PeriodicAlarm, self).save(*args, **kwargs) if create: self.args = json.dumps([ str(self.id), str(self.analytics.id), str(self.user.id), ]) self.task = 'sample_path.tasks.execute_event_query' super(PeriodicAlarm, self).save(*args, **kwargs) PeriodicTasks.changed(self) What does .changed() do??? -
Django filter charfield by greater than X principle
Possible duplicate, but no answers so far got any close to the solution. Imagine you have a charfield like this: 1.1.1.1 arriving in the request. I.e. basic semantic version. You need to filter all the objects in the queryset, where their version charfield is greater than this. For example we have such records in the DB: 0.0.0.0 0.0.0.1 1.0.0.0 1.1.1.1 1.1.1.2 2.2.2.2 And in the example provided I gave the version number as 1.1.1.1. So filtering by "greater than this" principle we will get only [1.1.1.2, 2.2.2.2]. Right now I'm filtering just by using regex. But how to do this using django ORM? -
Simulate CSRF attack in Django Rest Framework
I'm trying to get an understanding of how CSRF tokens work, currently my goal is to create a situation where the CSRF attack is possible. I'm hosting two Django apps locally on different ports. I access one by localhost:8000, the other by 127.0.0.1:5000 -- that ensures cookies are not shared between apps. There's an API view class ModifyDB(APIView): def post(self,request,format=None): if request.user.is_authenticated: return Response({'db modified'}) else: return Response({'you need to be authenticated'}) which shouldn't be accessed by unauthenticated users. The "malicious" site has a button that's supposed to trigger the attack when a user is logged on the target site: const Modify = () => { const onClick = async e => { e.preventDefault(); const instance = axios.create({ withCredentials: true, baseURL: 'http://localhost:8000', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) const res = await instance.post('/api/modifydb'); return res.data } return ( <button class = 'btn' onClick = {onClick}> send request </button> ) } My authentication settings are as follows: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'my_proj.settings.CsrfExemptSessionAuthentication', ], } where CsrfExemptSessionAuthentication is a custom class that disables csrf protection for my educational purposes: class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return django.middleware.csrf.CsrfViewMiddleware is also disabled. Both CORS_ALLOW_ALL_ORIGINS and CORS_ALLOW_CREDENTIALS are set to true. My question … -
How to get top 5 records in django dict data
I m having two tables 1) Visit 2) disease. visit table having a column for disease. I m trying to get top 5 disease from visit table. dis=disease.objects.all() for d in dis: v=visits.objects.filter(disease=d.disease_name).count() data={ d.disease_name : v } print (data) This print all disease with respective count. as below: {'Headache': 2} {'Cold': 1} {'Cough': 4} {'Dog Bite': 0} {'Fever': 2} {'Piles': 3} {'Thyroid': 4} {'Others': 9} I want to get top 5 from this list based on count. How to do it? -
Further filter QuerySet when moving from one URL to another
I'm learning Python Django. I'm trying to create an Expense Tracker App. I record an expense transaction and attach it against a Category and a Subcategory. E.g. Category would be Travel, Sub category would be Hotel. I then record a transaction on a specific date providing Category/Subcategory. My Model is as below. class Categories(models.Model): category_text = models.CharField(max_length=50) def __str__(self): return self.category_text class SubCategories(models.Model): category = models.ForeignKey(Categories, related_name="category", on_delete=models.CASCADE) subcategory_text = models.CharField(max_length=50) def __str__(self): return self.subcategory_text class Transaction(models.Model): card_source = models.ForeignKey(CardSource, on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategories, related_name="subcategory", on_delete=models.CASCADE) amount = models.DecimalField(max_digits=9, decimal_places=2) description = models.CharField(max_length=100) transaction_date = models.DateField('Date') def __str__(self): return self.description + ' on ' + str(self.transaction_date) + ' via ' + str(self.card_source) My index.html view shows all sum of all expenses per category for last 30 days. # /expenses/<x>days/ def last_xdays(request, num_of_days): last_xdays_date = date.today() - timedelta(days=num_of_days) transaction_list = Transaction.objects.filter(transaction_date__gte=last_xdays_date).filter( transaction_date__lte=date.today()) if not transaction_list: raise Http404("No transactions found.") category_list = Categories.objects.annotate(category_sum=Sum('category__subcategory__amount', filter=Q( category__subcategory__id__in=transaction_list))).filter(category_sum__gt=0) return render(request, 'expenses/index.html', {'category_list': category_list, 'transaction_list': transaction_list}) Requirement: When I click on a Category, it should navigate to url [/expenses/30days/Travel][1] showing sum of all expenses per subcategory under that category. Template: {% for category in category_list %} <tr> <td><a href="{% url 'expenses:category' category.id %}">{{ category.category_text }}</a></td> <td>{{ … -
Django, problem with render request: "The view main.views.licz didn't return an HttpResponse object. It returned None instead."
I'am trying to do a website and I have problem with uploading the file. On admin site I can upload and import any file but when I create view, I get this: "The view main.views.licz didn't return an HttpResponse object. It returned None instead." Here is the code from main.models: class Plik(models.Model): file = models.FileField(upload_to='uploads/') Code from forms.py: class upload(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() And code from views.py: def licz(request): if request.method == "POST": form = upload(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect("main/licz.html", {"form":form}) else: form = Plik() return render(request, "main/licz.html", {"form":form}) Plz I am trying to solve this like 5 days... -
How to print an API reponse value in a table column without the values being overidden?
I am working on a website using django, django-filter ,django-crispy-forms, and datatables for easy pagination and filtering. I have been able to successfully implement the required view and datatable in order to pull data from the django database and print it in a table how I want it presented. The issue I am running in to, is that I need to fill one of the column items on each row of the table with a value that comes from an API call to a separate website to get the status of an individual player in current time. As you can see from the below snippet, my most recent attempt was using ajax to pull the require api data (Note: I have also tried using fetch, and some javascript). But no matter what I am trying I am unable to get and print the data as required. In the below using ajax, I run into an issue, where when the for loop runs (2 iterations), if I leave async as true it runs and fills out the first row of the column in question, but does not put data in any other row. When I check the console I can see … -
How to print the output from StreamingHttpResponse to an html template in django?
I have realtime printed the output of my subprocess command onto an an html page using the below code in my views.py . However i want to print this output onto my html template (results.html). how do i do that ? from django.shortcuts import redirect, render from django.http import HttpResponse,HttpResponseRedirect,request import subprocess # Create your views here. def home(request): return render(request,"home.html") def about(request): return render (request,"About.html") def contact(request): return render (request,"Contact.html") def process(request): ip=request.POST.get('ip') with subprocess.Popen(['ping', '-c5',ip], stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) as p: for line in p.stdout: yield("<html><title>Fetcher Results</title><body><div style='background-color:black;padding:10px'><pre style='font-size:1.0rem;color:#9bee9b;text-align: center;'><center>"+line+"<center></div></html> ") # process line here if p.returncode != 0: raise subprocess.CalledProcessError(p.returncode, p.args) def busy(request): from django.http import StreamingHttpResponse return StreamingHttpResponse(process(request)) -
'type' object is not iterable django-rest-framework
I am new to mobile app development and I am trying to make my first app with react-native and Django rest-framework as the backend. When I try to run the server and access any model through the django-rest-framework I get "TypeError: 'type' object is not iterable." I have tried to look up a way to solve it but every way I found online did not help. Here is my code: models.py- from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator class Movie(models.Model): title = models.CharField(max_length=32) description = models.TextField() def no_of_ratings(self): ratings = Rating.objects.filter(movie=self) return len(ratings) def avg_rating(self): sum = 0 ratings = Rating.objects.filter(movie=self) for rating in ratings: sum += rating.stars if len(ratings) > 0: return sum / len(ratings) else: return 0 class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) class Meta: unique_together = (('user', 'movie')) index_together = (('user', 'movie')) serializers.py- from rest_framework import serializer from .models import Movie, Rating from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields =('id', 'title', 'description', 'no_of_ratings', 'avg_rating') class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields =('id', 'stars', 'user', 'movie') class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields … -
Functionalities of Django CMS
What type of CMS website can Django-CMS be built with? Is it DXP, headless or traditional CMS? -
Django not rendering background images used in url <style> tag
I am trying to render static image files with Django and this is the first time I have encountered images referenced with the <div class="img" style="background-image: url;"></div> style tag. I will upload the code and the site as is showing when I run the server. <div class="founder d-flex align-items-center mt-5"> <div class="img" style="background-image: url('/static/images/doc-1.jpg');"></div> <div class="text pl-3"> <h3 class="mb-0">Dr. Zen Goode</h3> <span class="position">CEO, Founder</span> </div> </div> This is what the output shows when I run the server. (Of course, it shows other image files here but I assume its just the same): [22/Jul/2022 06:04:36] "GET /static/images/person_2.jpg HTTP/1.1" 404 1816 django.core.exceptions.SuspiciousFileOperation: The joined path (S:\maps.googleapis.com\maps\api\js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false) is located outside of the base path component (C:\Wor\dentistt\dentist\static) [22/Jul/2022 06:04:36] "GET /static/images/doc-4.jpg HTTP/1.1" 404 1807 [22/Jul/2022 06:04:36] "GET /static/images/person_1.jpg HTTP/1.1" 404 1816 [22/Jul/2022 06:04:36] "GET /static/images/person_3.jpg HTTP/1.1" 404 1816 [22/Jul/2022 06:04:36] "GET /static/website/https%3A/maps.googleapis.com/maps/api/js%3Fkey%3DAIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s%26sensor%3Dfalse HTTP/1.1" 500 59 [22/Jul/2022 06:04:36] "GET /static/images/person_4.jpg HTTP/1.1" 404 1816 [22/Jul/2022 06:04:36] "GET /static/images/image_3.jpg HTTP/1.1" 404 1813 [22/Jul/2022 06:04:36] "GET /static/images/image_1.jpg HTTP/1.1" 404 1813 [22/Jul/2022 06:04:36] "GET /static/images/image_2.jpg HTTP/1.1" 404 1813 And this is the site: I know that with the 404 error, the files are not being found so how I can render the image correctly here? -
CORS, HttpOnly, CSRFCookie; Django; ReactJS
I have a question. I am developing a webApp. My backend is on xxxx.xxxx.xxxx.xxxx:8000 and my frontend is on xxxx.xxxx.xxxx.xxxx:3000. I am using Django and ReactJS. I have configured my CORS policies on the backend to allow only my fronted to make requests. So. Whenever I have to get CSRF cookies from my backend they come in a response under Set-Cookie with HttpOnly flag. My question is if we are not supposed to extract HttpOnly cookies with the JS how come I still can do that with my ReactJS app. However, whenever I remove that flag I cannot set or retrieve those cookies from the header anymore. Whta is wrong? Or what is right? Help me to understand that please. my django CORS setup: # CSRF Cookie Settings CSRF_COOKIE_AGE: Optional[int] = None CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', 'http://xxxx.xxxx.xxxx.xxxx:3000' ] CSRF_COOKIE_HTTPONLY = True # CORS(cross origin resource sharing) settings CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://xxxx.xxxx.xxxx.xxxx:3000', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'PATCH', 'POST', 'PUT', ] my reactjs request: fetch("http://xxxx.xxxx.xxxx.xxxx:8000/get_csrf",{ method: 'GET', mode: 'cors', credentials:'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then(response => { console.log(...response.headers) response.json() }) .then( (result) => { console.log(this.getCookie('csrftoken')) }, (error) => { … -
How do I get super() to work in python? I keep getting an error message and the only way to get it to go away is to have something inside the ()
How do I get super to work? I'm taking a DJANGO class, everything is working great, but I keep getting an error message and the only way to get it to go away is to have something inside the (). like super(self). Everything I find online has the super() please help me figure out why it isn't working!!! def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context ['my_thing'] = "this is a new headline" return context -
How to Annotate Expense Sum From Another Table Through Fields That Aren't Date or DateTime Field
I am trying to annotate the sum of Interest Expense on Loans that got some Interest Expense during a day. My Data looks like this. Loan id, number type ..., InterestExpense (This is Many to One Model) id, loan_id (FK to Loan) amount day (positive small integer with Validator). (Unfortunately, doesn't respect DD format) month (positive small integer with Validator) (Unfortunately, doesn't respect MM format) year (positive small integer with Validator)(Respects YY format) So given start and end date I need to get sum of amount of InterestExpense for loans grouped by Loan Type. Dilemma I am having is I can't seem to create or annotate a date field out of those day, month, year small integer values. I tried Concat with to_date. But it doesn't like it has 1 digit months. initial_report_data = self.primary_report_model.objects.filter( ... (SOME FILTER) ).select_related('interestexpense').annotate( interest_date=Func( Concat('interestexpense__month', Value('-'), 'interestexpense__year', Value('-'), 'interestexpense__day', output_field=CharField()), Value('MM-YYYY-DD'), function='to_date', output_field=DateField() ) ) I am getting errors of Date Being Out Of Range Because For Month And Day Values, the digits from 1-9 aren't 0 padded. Is there a way I can get any date/datetime/timestamp value from those (Month, Day, Year) Fields So I can see if it is in range of … -
I have this error delete_post() missing 1 required positional argument: 'id' when I click on the delete link
I am trying to develop a function in django to delete a user's own post that he/she uploads to the website but I keep getting the following error. Can someone help me please? I am still relatively new to using Djangoenter image description here urls.py path('delete-post/int:id/',views.delete_post,name='delete-post'), views.py def delete_post(request, id): user = request.user.username user = get_object_or_404(User, id=id) if request.method == 'POST': user.delete() return redirect('home') return render(request, 'index.html') html <a href="delete-post/int:id/{{p_filter.id}}" class="flex items-center px-5 py-4 text-blue-500 hover:bg-lime-600 hover:text-red-500 rounded-md "> <i class="uil-trash-alt mr-1"></i> delete models.py class DeletePost(models.Model): p_id=models.CharField(max_length=500) username =models.CharField(max_length=100) def __str__(self): return self.username I would really appreciate a step by step explanation since my aim is to learn how to delete a post off a website. Thanks! -
How to test Django reusable templates?
In one of my templates for detailed view of a device assignment I had logic pertaining to if buttons should appear depending on the user's permission. I wrote tests for these buttons and they work as expected. Today I wanted to reuse these buttons elsewhere in another template so I extracted it into its own template file and put it in a "partials" folder. |-templates | |-assignments | | |-deviceassignment_form.html | | |-deviceassignment_detail.html | | |-deviceassignment_confirm_delete.html | | |-deviceassignment_list.html | | |-partials | | | |-deviceassignment_control_buttons.html | | | |-deviceassignment_infobox.html Obviously I can continue testing deviceassignment_detail.html which includes the control buttons and checks to make sure they work (appearing or not based on permissions). But then when I include control buttons elsewhere I might be tempted to test them again... Instead couldn't I write a test ONLY for the deviceassignment_control_buttons.html template? I want to render the template directly with a basic view context and check that everything works as expected. Is this possible? -
I am finding it difficult to do relative Import in Django application
I am relatively new to django and am finding it difficult to do basic module referencing. Even thou I have searched through couple of links I still don't get it. I have been here: Relative Import For the Billionth Time and I still don't get it Here is my folder structure main main/main main/main/urls.py main/sub_main main/sub_main/views.py In my urls module I have a line from ..sub_main import views However, I keep getting the error: ImportError: attempted relative import beyond top-level package Is there something am missing? -
How to prevent Django view to mix up data of two different users
Hy, I'm working on a Django project, and in my view of the app, I'm declaring some variables according to each individual's unique ID from database. Like this: def chat(request): if request.POST: global curCombo, curComboAlternate, firstSender # Getting the user ID of the user clicked toChatUserID = request.POST.get("userID") # Getting user ID of the login user from another function: try: # Looking if it is already defined in the "everyone" function curUserID = curUserID #Getting from another function except: # If not defined, then define it here curUserID = request.session.get("curUserId") # Combination of person itself and the person to talk curCombo = f"{curUserID}&{toChatUserID}" # Declaring this to use in case if the logined user is not the one on who's name the message combination is created in database curComboAlternate =f"{toChatUserID}&{curUserID}" # making this variable global to use it in the addMsgToDB function to determine the cur combo variable # If messages exist with opposite combination for "combo" if Message.objects.filter(combo=curComboAlternate).exists(): firstSender = "other"Message.objects.filter(combo=curComboAlternate) # If messages exist in normal combination for "combo" else: firstSender = "me" print("now the firsender is set to ----->me") curComboMsg = Message.objects.filter(combo=curCombo) # Getting the name of the person to whom message has to be sent to … -
How do I send a django model to javascipt?
How do I pass a django model to javascript? Specifically, I want to pass a django Movie model to javascript. In javascript, I would like to display the id something in the movie model at the time of score with an if statement. def index(request): if Movie.objects.order_by('-stars').exists(): movie = list(Movie.objects.order_by('-stars')) if TV.objects.order_by('-stars').exists(): tv = TV.objects.order_by('-stars') print(tv) context = { 'movie':movie, } return render(request, 'Movie/index.html',context) fetchTrendingResults("all", "week") var mediaType = document.getElementById("media_type") mediaType.addEventListener("change", function(event) { fetchTrendingResults(mediaType.options[mediaType.selectedIndex].value, "day") }) function fetchTrendingResults(media_type, time_window) { var trendingDiv = document.getElementById("trendings") trendingDiv.innerHTML = "" if (media_type == "score"){ var js_list = {{movie}}; } else{ fetch(`/api/trendings?media_type=${media_type}&time_window=${time_window}`, { method: "GET", headers: { "Content-Type": "application/json" }} // todo:movieとTVのIDをもらってこれをURLにFethして映画とTVの情報をそれぞれでスターが高い順に表示する。 ) .then(res => res.json()) .then(data => { for (let i=0; i<data.results.length; i++) { var mainDiv = document.createElement("div"); mainDiv.setAttribute("class", "card"); mainDiv.setAttribute("style", "width: 18rem;"); var img = document.createElement("img"); img.setAttribute("src", "https://image.tmdb.org/t/p/w200" + data.results[i].poster_path); img.setAttribute("class", "card-img-top"); img.setAttribute("alt", "..."); var body = document.createElement("div"); body.setAttribute("class", "card-body"); var title = document.createElement("h5"); title.setAttribute("class", "card-title"); if (data.results[i].name) { title.innerHTML = data.results[i].name; } else { title.innerHTML = data.results[i].title; } //var text = document.createElement("p"); //text.setAttribute("class", "card-text"); //text.innerHTML = data.results[i].overview; var link = document.createElement("a"); link.setAttribute("href", "/" + data.results[i].media_type + "/" + data.results[i].id + "/"); link.setAttribute("class", "btn btn-primary"); link.innerHTML = "View Details"; body.appendChild(title); //body.appendChild(text); body.appendChild(link); … -
Set the background of the body to an image while using Bootstrap 5
I am curious how to set the whole webpage background (the body) to an image. Ideally I would like to fade the image a bit so it isn't overpowering. <style> body { background-image:url("{% static 'portfolio/cherry_blossoms.jpg' %}"), } </style> I attempted to add this within the html body however it returned no result. Note I am using Bootstrap 5. -
Vue not displaying Django Rest API data
I am working on a brand new project using Vue and Django Rest Framework. I got the API set up and I am getting the data back as needed, as confirmed by network in dev tools. However, I am having an issue with the v-for loop displaying the results. Any reasons or ideas on why I am not getting the results displayed? Here is vue.js code (GetTasks.vue) <template> <div class="tasks"> <BaseNavbar /> </div> <div v-for="tasks in APIData" :key="tasks.id" class="container"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{tasks.task}}</h5> <p class="card-text">{{tasks.details}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> </template> <script> import { getAPI } from '../axios-api' import BaseNavbar from '../components/BaseNavbar.vue' export default { name: 'GetTasks', data () { return { APIData: [] } }, components: { BaseNavbar, }, created () { getAPI.get('/tasks/',) .then(response => { console.log('Task API has recieved data') this.APIData = response.APIData }) .catch(err => { console.log(err) }) } } </script> Django model class Tasks(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=200) details = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) -
Django_rq, jobs fails due to missing positional arguments
I've been trying to solve an issue with integrating Django_rq into my app. I have several .csv data imports that I have created which take quite a bit of time to process. All data imports are similar in nature, but vary in the amount of code being preformed. I have updated two of the data imports so far to use Django_rq and they run successfully. No issues with them. Little backstory, all these functions where using python threading module originally. The problem came when I went to update the 3rd data import function. In addition to updating it just like the first two, I reduced the amount of positional arguments from 5 down to just 1. When I run the data import and add the job to a queue, it fails immediately. When I check the failed job registry to review the trace back, it says Traceback (most recent call last): File "/srv/cannondj/venv/lib/python3.8/site-packages/rq/worker.py", line 1061, in perform_job rv = job.perform() File "/srv/cannondj/venv/lib/python3.8/site-packages/rq/job.py", line 821, in perform self._result = self._execute() File "/srv/cannondj/venv/lib/python3.8/site-packages/rq/job.py", line 844, in _execute result = self.func(*self.args, **self.kwargs) TypeError: process_task_data() missing 5 required positional arguments: 'all_jobs', 'all_tasks', 'all_assignment_types', 'all_assignment_statuses', and 'db_que' I find this odd, because those are the …