Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To get Values of One View Function into Another View Function In django
def index_view(request): emp_data2 = {'eno':101,'ename':'john','esal':3000,'eadd':'uk'} return render(request,'TestApp/index.html',{'emp_data2':emp_data2}) trying to add above emp_Data2 to below view but its returning None def some_view(request): data = request.GET.get('emp_data2') render(request,'TestApp/some.html',{'data':data}) -
Last index value in Python Django View html
How to retrieve the last value of any array/dict/tuple? arr = [1,6,7,9,22] arr[-1] = 22 In Django view arr.0 gives the value 1 but cannot do arr.-1 or arr[-1] django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '-1.start' from 'vmd.-1.dstart' django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[-1].start' from 'vmd[-1].dstart' I am looking to get the last value. -
Django SuspiciousFileOpretation at /admin/
I know many people asked this question. I have two laptops, one uses python 3.7 another one uses python 3.6. The code is the same, the second laptop raises this error. here is my file in admin: admin.site.register(File) in models class File(models.Model): files = models.FileField() settings BASE_DIR = os.path.dirname(os.path.abspath(__file__)) MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') any idea why I get this error when using python 3.6? -
Celery what happen to running tasks when using app.control.purge()?
Currently i have a celery batch running with django like so: Celery.py: from __future__ import absolute_import, unicode_literals import os import celery from celery import Celery from celery.schedules import crontab import django load_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings') django.setup() app = Celery('base') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): app.control.purge() sender.add_periodic_task(30.0, check_loop.s()) recursion_function.delay() print("setup_periodic_tasks") My aim is whenever the celery file get edited then it would restart all the task -remove queued task that not yet execute(i'm doing this because recursion_function will run itself again if it finished it's job of checking each record of a table in my database so i'm not worry about it stopping mid way). The check_loop function will call to an api that has paging to return a list of objects and i will compare it to by record in a table , if match then create a new custom record of another model My question is when i purge all messages, will the current running task get stop midway or it gonna keep running ? because if the check_loop function stop midway looping through the api list then it will run the loop again and i will create new duplicate record which i don't want -
Running python manage.py test results in "Unittest.loader.__FailedTest"
I am trying to run test cases in my Django project using python manage.py test and I am getting Unittest.loader.__FailedTest. Here is project structure:- myproject/ myprojectservice/ __init__.py manage.py myprojectservice/ __init__.py tests/ __init__.py testmyproject.py None of the init files have anything in it. Is it because of same package and sub-package name? How do I resolve this? -
Not able to install Django on Mac OS. Not sure what to do
Im Super lost and frustrated. Not sure what to do next. Please someone help me, this si the last question I asked. I tried all of the options an none worked. Django Start project not working after install fatgezimbela@MacBook-Pro-2 ~ % pip3 install django==3.0.3 WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue. To avoid this problem you can invoke Python with '-m pip' instead of running pip directly. Requirement already satisfied: django==3.0.3 in ./Library/Python/3.8/lib/python/site-packages (3.0.3) Requirement already satisfied: sqlparse>=0.2.2 in ./Library/Python/3.8/lib/python/site-packages (from django==3.0.3) (0.3.1) Requirement already satisfied: asgiref~=3.2 in ./Library/Python/3.8/lib/python/site-packages (from django==3.0.3) (3.2.3) Requirement already satisfied: pytz in ./Library/Python/3.8/lib/python/site-packages (from django==3.0.3) (2019.3) fatgezimbela@MacBook-Pro-2 ~ % python3 django-admin startproject wisdompets /Library/Frameworks/Python.framework/Versions/3.8/bin/python3: can't open file 'django-admin': [Errno 2] No such file or directory fatgezimbela@MacBook-Pro-2 ~ % python3 django-admin.py startproject wisdompets /Library/Frameworks/Python.framework/Versions/3.8/bin/python3: can't open file 'django-admin.py': [Errno 2] No such file or directory fatgezimbela@MacBook-Pro-2 ~ % django-admin startproject wisdompets zsh: command not found: django-admin fatgezimbela@MacBook-Pro-2 ~ % django-admin startproject foo zsh: command not found: django-admin fatgezimbela@MacBook-Pro-2 ~ % python3 django-admin startproject winsdompets /Library/Frameworks/Python.framework/Versions/3.8/bin/python3: can't open file 'django-admin': [Errno 2] No such file … -
Django-simple-captcha Play Captcha Audio In Browser Not In Downloaded .wav File
By default, django-simple-captcha uses the flite linux command line program to convert the captcha text into a downloadable .wav file when a user clicks on the captcha image. Instead of downloading .wav files, a better user experience would be to play the audio directly in the browser by clicking a play button. How would one go about changing the default behavior of django-simple-captcha to do this? Is there a way to get it to universally work across many different forms such as template forms, allauth forms, etc? -
Django Models Custom user admin
I have a business model that will have a primary admin and multiple other admins/editors. Initially I was thinking about a manytomany field but I'm afraid this will not resolve the complexity of who's the primary admin or their level of administrative permissions such as an admin or just an editor. Any suggestions on resolving this schema design? class Business(models.Model): username = models.CharField() name = models.CharField(max_length=250) address = models.CharField(max_length=250) location = models.PointField(srid=4326) -
Django 3 loan management system problem with monthly payment table and profit calculations
sorry if the title is not good but I don't know how to ask it, suggest a better one if possible :) I am requested to make a loan management system that the owner can add clients, there are 4 problems are literally making me a headache 😅 1) it's a monthly payment that it must show who haven't paid at the first of every month 2) calculate the money paid and remaining in the models + months paid and months remaining 3) I am requested to make like a calendar for the owner that he can choose a month and see who has paid and who haven't .. how can I save something like that ?" the models part " 4)how can I make a yearly profit divided on months in models? sorry if I'm not very accurate in my question but couldn't find another way to ask 🤦♂️😅 , I have searched a lot but couldn't find anything helpful 😔 My Model: class Agent(models.Model): name = models.CharField(max_length=120) id = models.DecimalField(max_digits=14) tel = models.DecimalField(max_digits=11) guarantor = models.CharField(max_length=120) guarantorId = models.DecimalField(max_digits=14) guarantorTel = models.DecimalField(max_digits=11) amount = models.DecimalField(max_digits=10,decimal_places=5) paid = ?? remaining = ?? LoanStartDate = models.DateTimeField(default=timezone.now) LoanEndDate = models.DateTimeField(default=timezone.now) MonthsPaid … -
How do I get the string value of the tuple in Django
This sounds like a noob question, I just want to ask how do I get the string value of this tuple. USER_TYPE_CHOICES = ( (1, 'PQA'), (2, 'Tester'), (3, 'Test Lead'), (4, 'Test manager'), (5, 'Senior Test Manager'), (6, 'admin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) When I call the value as: <h1> {{ user.user_type }} </h1> It shows up as the int value and not the string. It sounds very simple but I can't seem to find it on the python documentation. -
Django Inserting data
I have this code in my html <form method="post" id="DogForm" action="/studentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="hidden" value="{{teacher}}" name="teacher"> <tr> <td rowspan="2" colspan="2">Core Values</td> {% for core in corevalues %} <td colspan="8"><input type="hidden" value="{{core.id}}" name="core">{{core.Description}}</td> {% endfor %} </tr> <tr> {% for corevalues in corevaluesperiod %} <td colspan="4" style="font-size: 12px"><input type="hidden" value="{{corevalues.id}}" name="coredescription">{{corevalues.Description}}</td> {% endfor %} </tr> <tr> <td colspan="2">Student's Name</td> {% for corevalues in period %} <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> {% endfor %} </tr> {% for students in student %} <tr> <td colspan="2" class="names"><input type="hidden" value="{{students.id}}" name="student">{{students.Students_Enrollment_Records.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <td colspan="4"> <select name="marking"> <option>--------</option> {% for m in marking %} <option value="{{m.Marking}}" >{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="4"> <select name="marking"> <option >--------</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="4"> <select name="marking"> <option>--------</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} </select> </td> … -
Wagtail: How can I access 'request' in a Page class in models.py
This is home/models.py: class HomePage(RoutablePageMixin, Page): template = "home/home_page.html" components = {'key1': ['alias1', 'ref1'], 'key2': ['alias2', 'ref2'], 'key3': ['alias3', 'ref3'], 'key4': ['alias4', 'ref4'], 'key5': ['alias5', 'ref5']} def get_comps(self): comps_list = [] for name in self.components.keys(): alias = self.components.get(name)[0] current_page_url = request.build_absolute_uri sub_url_index = current_page_url.find(".") ref = "http://" + self.components.get(name)[1] + "." + current_page_url[sub_url_index+1:] the_comp = comp(name, alias, ref) comps_list.append(the_comp) return comps_list class comp(models.Model): comp_name = "" comp_alias = "" comp_ref = "" def __init__(self, name, alias, ref): self.comp_name = name self.comp_alias = alias self.comp_ref = ref Wagtail displays an error at the line: current_page_url = request.build_absolute_uri This is because the request object cannot be found which is correct. How can I access the request object in get_comps()? I do not want to replace this with page.get_full_url or any page methods since that does not give me the absolute URL. -
Why I can't call multiple stored procedures consecutively with Django and Postgres
I have a class in python, the class has the following methods self.__evaluateAmenityBuffers() self.__evaluateTransitBuffers() self.__evaluateRoadsBuffers() self.__evaluateRiskBuffers() self.__EvaluateJobsBuffer() in each method I call a stored procedure with Django, the code is similar to the next one cur = connection.cursor() cur.callproc("urbper_buffer_amenities", [self.scenario]) the issue I am facing with is that only the first method writes its changes in the data base, If I comment the first method, the second one works but the next methods are executed but their chages are not stored in the database. ¿could you help to find out what am I doing wrong? -
django message displaying time not working
I am trying to make the django messages tags disappear after like 5 second but it not working! I followed other stackoverflow topic about that, but still not working! views.py messages.success(request, "Your list has been created!") html <div class="container"> <div class="col-md-8"> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} <a href="#" class="del-msg">&times;</a> </div> {% endfor %} {% endif %} </div> <script> $(document).ready(function() { setTimeout(function() { $('.message').fadeOut('slow'); }, 5); $('.del-msg').live('click',function(){ $('.del-msg').parent().attr('style', 'display:none;'); }) }); </script> -
How to match the current path to URL patterns?
I am doing a Django tutorial in writing my Django App, part 3. So far, running the server brings up an error: a screenshot of what the error displays These are the python scripts I've entered so far; polls/views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import Question from django.template import loader from .models import Question def index(request): return HttpResponse("Hello, world. You're at the polls index. Too bright") def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) # Latest Questions List def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) # Leave the rest of the views (detail, results, vote) unchanged def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) from django.shortcuts import render from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) from django.http import Http404 from django.shortcuts import … -
Run pytest for Django project on Jenkins
I am trying to run pytest on my Django application via a Jenkins job. But when I run it the following way: cd workspace pytest I see the following error: ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. !!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!! I tried exporting it : export DJANGO_SETTINGS_MODULE=myproj.settings And then I see the following error: ImportError: No module named myproj.settings even though my settings file exists in that location. Has anyone tried this before ? -
Importing existing blog posts into django-cms-blog
I am integrating an existing web-application into django-cms. So far, my application had a blog application not from django-cms, which currently contains several thousand blog-posts. Im trying to import them into the django-cms-blog application. Until now, I have imported all fields successfully, such as title, category, ... into the django-cms-blogpost model except for the Placeholder fields, where the content of blogs is saved in. I know that I can access it from the frontend, but this way I would have to copy all the content of the previous blog-posts manually into the current. So my question is: Is it possible to add content to placeholders from the backend? -
How to reference allauth user as foreign key in Django
If I use normal user provided django default, my model will be like this. from django.db import models from django.contrib.auth.models import Users class Photo(models.Model): photographer=models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') # 5 # other fields If I want to implement allauth, what should I have to pass for the first argument in line#5, instead of User? -
What context this error refers to, error in django app crashed heroku deployment?
2020-03-06T00:10:28.582720+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ancient-savannah-79009.herokuapp.com request_id=745a73ec-d3fd-41f7-b1d8-d4b1adf017cb fwd="111.119.35.198" dyno= connect= service= status=503 bytes= protocol=https 2020-03-06T00:10:28.978551+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ancient-savannah-79009.herokuapp.com request_id=bc0e33ce-4ae7-42bb-aef7-4aa05741ea7e fwd="111.119.35.198" dyno= connect= service= status=503 bytes= protocol=https -
Django query record with largest version in group
I have a very simple Django model which represents a versioned Product: class Product(models.Model): name = models.CharField(max_length=50) version = models.PositiveSmallIntegerField(null=True) class Meta: unique_together = ("name", "version") def __str__(self): return f"{self.name} ({f'v{self.version}' if self.version else 'DRAFT'})" I can create some products in the database using the following script: p1_v1, _ = Product.objects.get_or_create(name="One", version=1) p1_v2, _ = Product.objects.get_or_create(name="One", version=2) p1_v3, _ = Product.objects.get_or_create(name="One", version=3) p1_draft, _ = Product.objects.get_or_create(name="One", version=None) p2_v1, _ = Product.objects.get_or_create(name="Two", version=1) p2_v2, _ = Product.objects.get_or_create(name="Two", version=2) p3_draft, _ = Product.objects.get_or_create(name="Three", version=None) I need to perform a query that returns the latest version of each Product (excluding Products with no version). That is, the target result is the following Queryset: <QuerySet [<Product: One (v3)>, <Product: Two (v2)>]> The following works with PostgreSQL but fails with SQLite: Product.objects.exclude(version__isnull=True).order_by("name", "-version").distinct("name") # <QuerySet [<Product: One (v3)>, <Product: Two (v2)>]> I'm able to get the max version per name here but I'm not sure how to get the actual objects from the db: Product.objects.values("name").annotate(max_code_version=Max("version")) # <QuerySet [{'name': 'One', 'max_code_version': 3}, {'name': 'Two', 'max_code_version': 2}]> How can I execute this query? -
How to get url of images hosted in dropbox, to use it in debug mode (django)
I will try to be as clear as possible since there are some things I do not fully understand how they work. I am developing a page in which an administrator can modify the image of one or any product that he wants, therefore I am storing the images in my dropbox developer account, there is no problem uploading the image on the page that is hosted with heroku but, I want to get the url of the image that the user uploaded and pass it to the html to specifically load that image hosted in dropbox. Here is the method that I used from my model to get the url: class TProducto(models.Model): id = models.AutoField( primary_key=True) Nombre = models.CharField(max_length=255, blank=True, null=True) Descripcion = models.CharField(max_length=255, blank=True, null=True) Costo = models.FloatField(default=0) Descuento = models.IntegerField(default=0) Coleccion = models.ForeignKey(TColeccione, on_delete=models.SET_NULL, blank=True, null=True) Foto_Producto = models.ImageField(upload_to="productos", blank=True, null=True); def get_img(self): return self.Foto_Producto.url This is part of my settings: # <=================== CONFIGURACION DE DROPBOX =============> DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = '_i8nHpnMhuAAAAAAAAAADQGug3M9WeXGHsr0sW2ciJzHg9gIbDw8lpMNqK1XN6Kn' DROPBOX_ROOT_PATH = 'media' # <=================== CONFIGURACION DE DROPBOX =============> And in this part i want to get the url from dropbox to dynamically obtain the url of the image that the client uploaded to … -
How To Fix Users has no user in Django Python
Error: RelatedObjectDoesNotExist at /account/register/ Users has no user. I'm Making A Blog But I'm Getting This Error On Register And I Spend My 3 Hours to fix this error but i can't fix that error I Want To Register My User But When User Click on Register Button I Get That Error Here is my Code: views.py def reg(request): punctuations = '''{,?!'":`[]|\,;()#&!~+/*-+}$%^&*()+=/*''' form = RegForm(request.POST or None) profile = RegExtraDetail(request.POST or None) success = False error = False if form.is_valid() and profile.is_valid(): #...... user = form.save() user.set_password(user.password) user.save() extra = profile.save(commit=False) if request.FILES.get('profile_img') in extra.profile_img: extra.profile_img = request.FILES.get('profile_img') id = user.id extra.user(id) extra.profile_views = 0 extra.save() success = 'You Are SuccessFully Registered' return redirect(index) context= {'form':form,'error':error,'success':success,'profile':profile,} return render(request,'account/reg.html',context) Models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.urls import reverse import random import string from django.utils.text import slugify class Users(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_img = models.ImageField(upload_to='profile/img',default='profile/img/default_pup.png',null=False,blank=False) profile_views = models.IntegerField(default=0,null=False,blank=False) def __str__(self): return self.user.username Forms.py from django.contrib.auth.models import User from django import forms from .models import Users class RegForm(forms.ModelForm): class Meta: model = User widgets = { 'username':forms.TextInput(attrs={'class':'form-control mb-4','required':True,'placeholder':'Username'}), 'email':forms.EmailInput(attrs={'class':'form-control mb-4','required':True,'placeholder':'Email'}), 'password':forms.PasswordInput(attrs={'class':'form-control mb-4','required':True,'placeholder':'Password'}), } fields = ('username','email','password',) class RegExtraDetail(forms.ModelForm): class Meta: model = Users fields = … -
Django Start project not working after install
The django project will not create. I keep getting this same error, please help. I am not sure what else can be doen -
Django Rest Framework JWT Refresh Token One Time Use
I'm using jwt for authentication and I want refresh tokens allowed, but it seems that the refresh tokens are still valid indefinitely. Is there an implementation that limits the amount of use of the refresh token? I know the field JWT_REFRESH_EXPIRATION_DELTA can determine the how long the token is valid but that doesn't solve this current issue. from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token urlpatterns = [ url(r"^jwt/create/?", obtain_jwt_token, name="jwt-create"), url(r"^jwt/refresh/?", refresh_jwt_token, name="jwt-refresh"), url(r"^jwt/verify/?", verify_jwt_token, name="jwt-verify"), ] -
How do i remove friend from manytomany field
I am working on a dating website using Django, where i can add and remove friend. I have a little complication on how i can remove/unfriend a user i added. With the code i tried, i get this erro "Cannot query "oghomwenoguns": Must be "Profile" instance." class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) bio = models.CharField(max_length=350, null=True,blank=True) profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/user-img.png", blank=True) friends = models.ManyToManyField('Profile', blank=True) date = models.DateTimeField(auto_now_add=True, null= True) def delete_friend_request(request, id): my_friend = get_object_or_404(User,id=id) frequest = Profile.objects.filter(friends=my_friend) frequest.delete() return HttpResponseRedirect('/') <a href="{% url 'site:delete_friend_request' u.id %}" class="btn btn-primary btn-lg waves-effect font-weight-bold text-capitalize ml-0 mt-2" style="font-size:14px;padding:10px;width:40%;">Unfriend</a>