Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mezzanine project structure - virtual env in project folder?
So I'm attempting to deploy my mezzanine site, but I have run into some issues with settings not being installed properly on the digitalocean server. After checking some videos, like this one: https://www.youtube.com/watch?v=RIOUwi-1DCg I notice that he and others have their virtual env inside the project folder, next to the mezzanine project. Is this the correct way to structure the project? In my case, the virtual env is in a seperate Env folder with my other virtualenvs under my main directory on Windows 7. If someone could clarify what the structure should look like, and perhaps why, I would be grateful. -
How to configure wsgi for gunicorn?
Django version: 2.2.4 Python version: 3.6 When I try to run "gunicorn --bind 127.0.0.1:9000 config.wsgi:appname", I get following error: [2019-10-10 12:00:12 +0530] [9398] [INFO] Starting gunicorn 19.9.0 [2019-10-10 12:00:12 +0530] [9398] [INFO] Listening at: http://127.0.0.1:9000 (9398) [2019-10-10 12:00:12 +0530] [9398] [INFO] Using worker: sync [2019-10-10 12:00:12 +0530] [9401] [INFO] Booting worker with pid: 9401 Failed to find application object 'appname' in 'config.wsgi' [2019-10-10 12:00:12 +0530] [9401] [INFO] Worker exiting (pid: 9401) [2019-10-10 12:00:12 +0530] [9398] [INFO] Shutting down: Master [2019-10-10 12:00:12 +0530] [9398] [INFO] Reason: App failed to load. My WSGI file looks like this: import os import sys from django.core.wsgi import get_wsgi_application app_path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir) ) sys.path.append(os.path.join(app_path, "appname")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") application = get_wsgi_application() I set up this Django project using cookiecutter Django. As I am new to this kindly let me know of any newbie mistakes. -
Gunicorn not forwarding reason phrase from Django Response
I am hosting my Django app with Gunicorn. What happen is as follow A sample response from Django would be as follow @require_http_methods(['POST']) def register(request): body = json.loads(request.body.decode('utf-8')) try: email = body['email'] except: return HttpResponse(status=400, reason="Email must be provided.") During the development, the Django app are run with command python manage.py runserver and have no issue at all with it. It always response with 400 Email must be provided However, in the production environment, it is hosted as follow Procfile web: gunicorn app.wsgi release: python manage.py migrate wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_wsgi_application() Yet, when making a request, the response left as below. 400 What am I missing out to not letting the reason being forwarded properly? -
Django 'FloatField' is not callable
I keep getting these annoying highlights in my model field declarations When I hover mouse over it, it say 'FloatField' is no callable. This is happening for all field types except for CharField. The project runs fine and I'm able to migrate the model to DB but these highlights are annoying. Hoe can I get rid of them? Please advise. from django.db import models class ProjectModel(models.Model): name = models.CharField(max_length=50) project_id = models.IntegerField(blank=True) discipline_id = models.IntegerField(blank=True) demo_field = models.FloatField(verbose_name='flow(kg/s)', null=True, blank=True) def __str__(self): return str(self.id) -
"Album.singer" must be a "Singer" instance
Tracebck Please refer this link for trace back 2.Even I changed the lable name in forms.py it is taking default name I tried This code to make it fix but not solved.name = forms.CharField(label='Singer') forms.py class AlbumForm(forms.ModelForm): title = forms.CharField(max_length=50,label='Album title') class Meta: model=Album exclude = ['singer'] class SingerForm(forms.ModelForm): class Meta: model = Singer fields = ['name'] label = {'name':'Singer'} views.py class AlbumSinger(View): def get(self,request,pk=None): singer_form = SingerForm(instance=Singer()) album_form = AlbumForm(instance=Album()) context = { 'singer_form':singer_form, 'album_form':album_form } return render(request, 'album/multi_form.html', context) def post(self,request,pk=None): context = {} singer_form = SingerForm(request.POST,instance=Singer()) album_form = AlbumForm(request.POST,instance=Album()) if singer_form.is_valid and album_form.is_valid: singer_form.save() new_album = album_form.save(commit=False) new_album.singer = singer_form new_album.save() return HttpResponseRedirect('/album/') context = { 'singer_form' : singer_form, 'album_form' : album_form } return render(request, 'album/multi_form.html', context) -
How to have a redirection on a new tab when I click in a button in django?
Hi I have this line which is an instant redirection on a page, it’s HTML + Django link together <li><a href= "{{ OGC_SERVER.default.WEB_UI_LOCATION }}">GeoServer</a></li> My goal is to have a this page open on a new tab when I click on it, I tried to add a target= "_blank Like this <li><a href= "{{ OGC_SERVER.default.WEB_UI_LOCATION }}" target= "_blank">GeoServer</a></li> But it didn’t change anything. I would like to know if there’s a way to do this -
How can I fetch Apple Watch data into a Python project(Django) and any possibility to sync manually entered data into apple watch?
I need to Sync the manually entered data from the Python-Django project automatically with Apple Watch. Also, need to fetch data automatically from the apple watch. I am not sure the apple watch data can get from this API: GET https://api.appstoreconnect.apple.com/v1/devices/{id} -
python crash course chapter 18 why models, admin, urls not working
In python crash course chapter 18, I got the projects working, both learning_log and Pizzeria(page 412, exercise 18-4), I got both admin sites. But when I tried to run models.py, it says "ImproperlyConfigured", and admin.py it came out "ModuleNotFoundError: No module named 'learning_logs'". Also at the next section, the urls.py is not working, I finished to the page 416, couldn't get the Figure 18-3. I followed every steps in the book and went back double checked a few times, I also checked the update of the book from website, couldn't figure out why they are not working. please help! -
DJANGO AUTHENTICATION (SSO) WITH AZURE AD AND OAUTH2.0
I have built a Django application, and I am suppose to implement SSO for this app, because we have azure ad setup i am following this https://pypi.org/project/django-azure-ad-auth/ blog post to have sso enabled in my application. In the azure ad i have create the application, i have the client id tenant id, on configuring these parameters, the app doesnt work correctly. Please help. -
Login required decorator is not working Properly in the django?it will not redirect properly to the login page if user is not registered or logged in
So in my django frame work i made the login page other pages in the project.Now i want say if some other third party user try to run my any webpage on that specific time my website ask him/her for login before accessing my any website page,to resist that i used the login required decorator but when i logged in and copy my other webpage url and paste in the new window it will not show the login page just straight open that webpage in the new window.HOW DO I FIX IT????HELP ME OUT PLEASE....... URLS OF MY WEBPAGES:- path("loggedin/",views.loggedin,name="loggedin"), VIEW PAGE:- from django.contrib.auth.decorators import login_required This is my index page where user can register his/her self and after that they will login and go to the next page...... def index(request): return render(request,'userside/index.html') And this is the page which comes after the index(main dashboard) page @login_required(login_url='userside/loggedin') #@staff_member_required def mainpage(request): return render(request,"userside/mainpage.html") The other webpage of my project @login_required(login_url='/userside/loggedin') def criminalsinfo(request): crimins=Criminals.objects.all() return render(request,'userside/criminalsinfo.html',{'crimins':crimins}) -
forgot password with django and graphql?
I'm using django as the backed with graphql,im trying to implement forgot password,and change password,im using django-graphql-jwt for login ,everything's is works,but i didn't see any documentation about the forgot password with graphql. -
How to find the correct relationships between my tables?
I'm trying out a new django social media project which has User, Status and Comment. The relationship between them is such that, User has a relationship to Status, User has relationship to Comment and there also exists a relationship between Status and comment. So to achieve this I built four tables, i.e, User, Comment, Status and UCSModel. Where UCSModel is the table which has the foreign keys of the rest three tables. UCSModel is more like the relations table consisting of all ID's So here is my models.py from django.db import models class User(models.Model): username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=200) password = models.CharField() def __str__(self): return self.username class Comment(models.Model): comment = models.CharField() def __str__(self): return self.comment class Status(models.Model): status = models.CharField() def __str__(self): return self.status class USCRelation(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, null=True, on_delete=models.CASCADE) status = models.ForeignKey(Status, null=True, on_delete=models.CASCADE) Being new to Django, I wanted to know if there is any better way of building relationships between tables. Especially when all the three tables are interrelated to each other like in my case above. -
Django Test case for deleting a post returns Https 200 instead of 302
I am writing a test case for a Posts app in my Django project. I have defined views for adding a new post, listing the posts, view details of the post, edit a post and delete a post. Adding a new post redirects the page to the detailed view of that page and deleting a post redirects the page to the list view. While writing tests for the same, I am getting https response code 302 for the new post as expected, but for the delete post, I am only getting an https response 200 while it should be 302. Adding necessary code below. Please feel free to ask any more code related to this if needed. Is there any concept that I am missing? Any lead is welcome. Thanks in advance. Test.py from django.test import TestCase from .models import Post from django.urls import reverse, reverse_lazy class PostTest(TestCase): def setUp(self): '''This function inserts dummy data into database to check during testing''' self.post = Post.objects.create(title='Test', content='abcd', author='testauthor@testing.test') def test_post_content(self): post_object = Post.objects.get(pk=1) expected_object_title = f'{post_object.title}' expected_object_content = f'{post_object.content}' expected_object_author = f'{post_object.author}' self.assertEqual(expected_object_title,'Test') self.assertEqual(expected_object_content, 'abcd') return self.assertEqual(expected_object_author, 'testauthor@testing.test') def test_post_list_view(self): response = self.client.get(reverse('lists')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Test') self.assertTemplateUsed(response, 'index.html') def test_post_details(self): response … -
django keep populating Form data in table
I am pretty new to django I need to keep adding form data in to the html table in same page. I can populate one time but i need to keep adding each time. refer below gif: sample data What I need is i need to add the data i have added second time to populate in the table in second row. please help me on this Form.py from django import forms class vm_provisioning_form(forms.Form): name = forms.CharField() email = forms.EmailField( ) views.py from django.shortcuts import render from django.http import HttpResponse from Forms import forms def vm_provisioning(request): form_vm_provisoning_info = forms.vm_provisioning_form() hidden_values = [] if request.method == 'POST': values = [] form_vm_provisoning_info = forms.vm_provisioning_form(request.POST) if form_vm_provisoning_info.is_valid(): # DO SOMETHING CODE print("VALIDATION SUCCESS!") name = form_vm_provisoning_info.cleaned_data['name'] email = form_vm_provisoning_info.cleaned_data['email'] values.append([name, email]) return render(request, 'Forms_template/vm_provisioning/vm_provisioning_form.html', {'forms': form_vm_provisoning_info,'data': values }) return render(request, 'Forms_template/vm_provisioning/vm_provisioning_form.html', {'forms': form_vm_provisoning_info}) form_vm_provisoning_info.html <!-- templates/vm_provisoning/form_vm_provisoning_info.html --> <!DOCTYPE html> {% extends 'Forms_template/base.html' %} {% block title %}Login in registration{% endblock %} {% block content %} <h1> Vm provisoning form</h1> <div class="container"> <h1>Please Fill details here!</h1> <form method="POST"> {{ forms.as_p }} {% csrf_token %} <section> <!-- hidden_data= forms.CharField(widget=forms.HiddenInput(), required=False) --> {% if data %} <table border="1"> <tr> <th>Name</th> <th>email</th> </tr> <!-- <p>{{ data }}</p> … -
get last seven month list and last seven weeks list in python
I am new to python and django framework so please help me. if present week number is 41 (10/10/2019) so last seven weeks means 40, 39,38,37,36,35,34 etc if present week number is 1 then need last year weeks numbers and also for months. This all for me to get the last 7 weeks day and the last 7 months data Thank you -
gunicorn v job queue in django
In Django webapp that's deployed, I get request in views.py As soon as post request is received, I modified post function to do certain action and deliver results in views.py def post(self, request, *args, **kwargs): #do some action #deliver results to 1.1.1.1 In this case, I'm currently running task as the request comes. For instance, if 5 requests come in at once, it's currently processing one by one. But, I'd like to process all requests at once(assuming there are enough server load) and deliver results back. Would increasing workers in gunicorn solve the issue of concurrency or would it be better to utilize job queue like celery? If gunicorn is enough, how many workers would need to be set? And what is best practice method? -
How to fix "ImportError at / cannot import name "bar" " for the HelloWorldApp example?
I am a newbie in Django. last week, I did all the steps for running the HelloWorld example by this tutorial: http://taswar.zeytinsoft.com/visual-studio-code-with-python-django/ which worked perfectly. However, I was trying to run it today, and it is not working. when i run: "python manage.py runserver", I got the message of "0 error found", but in the browser I have the following error: Exception Type: ImportError Exception Value: cannot import name bar can anyone please help me? need to mention that I tried all posted answer into the similar question, but the problem is still there!! Thanks -
Django : TypeError: 'ListSerializer' object is not iterable
I'm posting multiple values to my "KeyboardEventView" ModelViewSet. The post is successful and I can see the data in the database getting logged correctly. However, I'm getting an error thrown from Django, ... TypeError: 'ListSerializer' object is not iterable This is driving me nuts. It works, but it's bothersome to see errors get thrown. Anyone else experiencing this? -----Views.py----- class KeyboardEventView(viewsets.ModelViewSet): queryset = KeyboardEvent.objects.all() serializer_class = KeyboardEventSerializer def get_serializer(self, *args, **kwargs): if "data" in kwargs: data = kwargs["data"] # check if many is required if isinstance(data, list): kwargs["many"] = True return super(KeyboardEventView, self).get_serializer(*args, **kwargs) -----Models.py----- class KeyboardEvent(models.Model): value = models.CharField(max_length=15) time = models.DateTimeField(auto_now=True) user_id = models.ForeignKey(UserData,on_delete=models.CASCADE) def __str__(self): return self.value -
How to call custom function inside generic class base view
How to call the custom function in update function, my views is this- class StokeBulkUpdate(generics.APIView): ...... def custom_function(list): return list def update(self, request,*args,**kwargs): data = self.request.data custom_function -
See if Django form submission came from the admin
I'm new to django, so I apologize if this has been asked. I'm using the post_save signal to run a task when a new object is created. I need to be able to check if the form was submitted from the admin page or if it was submitted on the live website, is this possible? Where might I find documentation on this? -
Why doesn't this Django filter by 'annotate' variable work?
I have this queryset in Django: obj = Obj.objects.annotate(duration = F('date_end') - F('date_start')).order_by('duration') The following works perfectly: obj[0].duration obj.aggregate(Sum('duration'))['duration__sum'] However filtering doesn't work in this case even though documentation says that it should: obj = obj.filter( duration__gte = <a_class_datetime.timedelta> ) # doesn't work obj = obj.filter( duration = 1 ) # doesn't work This is the error I am getting: TypeError: expected string or bytes-like object My way to bypass this issue is to loop through the dataset - which is huge. Any tips as to why this is not working? -
ModuleNotFoundError: No Module named 'django' when trying to run makemigrations
I have taken over maintenance of a deployed Django app that is used by employees. I have made minor changes here and there and I only had to restart the apache to implement the changes. For the first time, I have to add an integerfield model to one of the pre-existing models. This said value is already in the DB with default value of 0 for all rows. All I want to do is add it as one of the fields in one of the models but when I try to run sudo python3 manage.py makemigrations in the virtual environment, I get ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback(most recent call last): File "manage.py", line 14, in <module> ) from exc As the app is currently running fine, why am I receiving this error? If this is not how you apply changes in the model field in the live server, how else are you supposed to do it? Thank you so much! -
In Django, How to gather dynamic input forms entry?
In django, I was able to create add and delete rows via js. How to add those rows of data into django DB. It only saves last row entry. Here is the following code. VIEW: def dynamicRow(request, *args, **kwargs): form = Add_Form(request.POST or None) template_name = 'addentry.html' if request.method == 'POST': if form.is_valid(): no_of_rows = int(request.POST.get('totalnum')) print(no_of_rows) list_of_rows = [Add_Form() for i in range(no_of_rows)] args = {'forms': list_of_rows} for i in args['forms']: print(i) ## only prints last entry i = Add_Form(request.POST) task = i.save(commit=False) task.save() messages.success(request, 'Successfully stored data into database.') else: messages.error(request, form.errors) else: form = Add_Form() return render(request, template_name, {'form': form }) HTML: <form id="add_data" role=form method="POST" class="post-form" action="">{% csrf_token %} <div class="container"> <table id="table" class=" table order-list"> <thead class="thead-light"> <tr> <th scope="col">Device#</th> <th scope="col">Name</th> </tr> </thead> <tbody> <tr> <td class="col-sm-4"> <input type="mail" name="device" class="form-check"/> </td> <td class="col-sm-4"> <input type="mail" name="name" class="form-check"/> </td> <td class="col-sm-2"><a class="deleteRow"></a> </td> </tr> </tbody> <tfoot> <tr> <td colspan="5" style="text-align: left;"> <input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" /> </td> </tr> </tfoot> </table> <div class="row"> <div align="center" class="col"> <h4>Number of Rows: </h4> <input name="totalnum" id="totalnum" class="form-control" type="text" maxlength="2"></input> </div></div> </div> <!-- container --> <br><br> <div class="row "><div class="col"> <button type="submit" name="submit" class="btn">Submit</button><p><p> … -
Add new context variable in get_queryset
I've a page that shows the will show the monthly revenue, according to what user selects as month. In HTML there is a with all the possible inputs. Now in my I'm returning a new variable for use in the template, **not a queryset**. I just want to put `{{ revenue }}` in the template. I've read that I don't need to send a post, only with a get I can achieve this. So I've set up this form to capture selected month, but I'm getting: TypeError at /ordenes/ingresos unhashable type: 'slice' How should I set the context in the get_queryset method? Views.py class OrdersListView(ListView): model = Order template_name = "order/revenue.html" paginate_by = 10 def get_queryset(self): filter_month = self.request.GET.get('filtromes', '0') order = self.request.GET.get('orderby', 'created') context = {} if filter_month == "0": paid_orders = Order.objects.filter(status = 'recibido_pagado') revenue = 0 for order in paid_orders: revenue += order.total - order.shipping_cost context['revenue'] = revenue return context else: paid_orders = Order.objects.filter(created__month=filter_month).filter(status = 'recibido_pagado') #orders_shipping = Order.objects.filter(created__month=9).filter(status = 'recibido_pagado') revenue = 0 for order in paid_orders: revenue += order.total - order.shipping_cost context['revenue'] = revenue return context def get_context_data(self, **kwargs): context = super(OrdersListView, self).get_context_data(**kwargs) #filter_month = self.request.GET.get('filtro_mes', '0') context['filtromes'] = self.request.GET.get('filtromes', '0') context['orderby'] = self.request.GET.get('orderby', 'created') … -
I am getting unformulated Modal form for my Edit form in Django
I am new to Python and tying to create my first project, to add/edit/delete customers I have successfully done my first move which is the listing and crating parts but when i arrive to the editing part i hanged there, and could not know how to fix it So, would someone help me to fix this issue Thanks My Form customerform.py from .Customers import Customer,City, Region from TARGET.bootstrap_modal_forms.forms import BSModalForm class CustomerForm(BSModalForm): class Meta: model = Customer ` My Model Customers.py class Customer(models.Model): SMALL = 1 MEDIUM = 2 BIG = 3 CUST_SIZE = ( (SMALL, 'Small Business'), (MEDIUM, 'Medium Business'), (BIG, 'Larg Business'), ) name = models.CharField(max_length=50) description = models.CharField(max_length=100, blank=True) account_id = models.CharField(max_length=30, blank=True) account_executive_id = models.CharField(max_length=30, blank=True) customer_size = models.PositiveSmallIntegerField(choices=CUST_SIZE) branches = models.IntegerField(blank=True, null=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) region = models.ForeignKey(Region, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=100, blank=True) credit_limit = models.IntegerField(blank=True, null=True) payment_term = models.CharField(max_length=30, blank=True) libility = models.IntegerField(blank=True, null=True) timestamp = models.DateField(auto_now_add=True, auto_now=False) def get_absolute_url(self): return reverse("contacts", kwargs={"id": self.id}) def __str__(self): return self.name ` My Url url.py from django.urls import path from . import views from django.conf.urls import url from .views import (customers_view,dashboard_view,leads_view,opportunities_view,product_details_view,channel_details_view) app_name = "crm" urlpatterns = [ path("contacts/", view=product_details_view, …