Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django use models from outside script
I have an external script that I want to have access to django's models primarily because it's an external implementation of sockets which is simple I want to see if this is possible. This is the snippet of code I added below the settings.py file based on an answer on stackoverflow. #Allow Django to be used externally from django.conf import settings settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, }, #TIME_ZONE='America/Montreal', ) and at the start of my separate script named path.py I did the following imports import django import pixelart.settings os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "pixelart.settings" ) django.setup() from gallery.models import ThumbnailCache, Area, Color Note: My django project is called pixelart with a model gallery I'm importing models from. When I try to run the script I get the following error: (pixelart) sam@sam-Lenovo-G51-35:~/code/pixelart$ python path.py Traceback (most recent call last): File "path.py", line 23, in <module> from gallery.models import ThumbnailCache, Area, Color File "/home/sam/code/pixelart/gallery/models.py", line 2, in <module> from django.contrib.auth.models import User File "/home/sam/code/envs/pixelart/lib/python3.6/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.contenttypes.models import ContentType File "/home/sam/code/envs/pixelart/lib/python3.6/site-packages/django/contrib/contenttypes/models.py", line 134, in <module> class ContentType(models.Model): File "/home/sam/code/envs/pixelart/lib/python3.6/site-packages/django/db/models/base.py", line 95, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and … -
How to keep manager.py command running with Gunicorn (without supervisor or circus)
I want to keep running a manager.py command (python manage.py qcluster) without Supervisor and Circus (both have some errors while installing). I need this to be running even if I've closed SSH connection to the server. Is there a way to do this only with Gunicorn? (I'm using Python 3.6 and Django 2.1) ps: I'm using Gunicorn and Nginx for deploying to the web. If there is not any way to do this via Gunicorn, please introduce me some alternative process managers. I've read Gunicorn documentation and there was not any sign of command support. I need this command: python manage.py qcluster to be running even if I've closed my connection to the server (VPS) -
Django: View all URLs registered in an app
I want to display all the URLs registered in app on the front end of my web application. For example, if an app has the following URLs, urlpatterns = [ url(r'^z/$', views.AuthBase.as_view(), name="login"), url(r'^h/$', views.Home.as_view(), name="home"), ] I want to build an HTML page that can show these URLs as a table. I have tried def get_urls(self): from store.urls import urlpatterns return urlpatterns but that does not seem to get the job done. -
Customize dropzone in django
I have this following model and I wanted to use dropzone.js for the model. I have tried django-dropzone but I can only upload files but not the description that I have like author, title, description. class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) visible_to_home = models.ManyToManyField(Home, blank=True) # when none visible to all home visible_to_company = models.ManyToManyField(Company, blank=True) # when none visible to all company # To determine visibility, check if vtc is none or include company of user and if true, check same for home created_date = models.DateTimeField(auto_now=True) published = models.BooleanField(default=True) upload = models.FileField(blank=True, null=True, upload_to=update_filename) title = models.CharField(max_length=225, blank=True, null=True) description = models.TextField(blank=True, null=True) -
Django - save a nested record
I want to create a nested object model in django. e.g. student: { name: 'Tom', age: 18, contact: { phone_num: 12345678, email: tom12345678@gmail.com } } How can I create it? I've tried to use abstract model but it's not my needs. class Contact(models.Model): phone_num = models.IntegerField() email = models.TextField() class Meta: abstract = True class Student(Contact): name = models.TextField() age = models.IntegerField() When I saved as: student = Student(name='Tom', age=18, phone_num=12345678, email=tom12345678@gmail.com) it returns: { name: 'Tom', age: 18, phone_num: 12345678, email: tom12345678@gmail.com } How can I put the phone_num and email under the contact? -
How to query OneToOneField in UserAttributeSimilarityValidator settings
When users change their password I want to prevent them to use a similar password as their firstname, lastname and or username. I have created a Profile Model that has a OneToOne relation with the built-in User Model. in models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) In settings.py: AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 'OPTIONS': {'max_similarity': 0.5, 'user_attributes': ('user.profile.first_name', 'user.profile.last_name', 'username')}}, Currently it only seems to check similarity of Built-in User Model attribute 'username' and not the Profile Model attributes 'last_name' and 'first_name'. -
How can I change http to https in django rest browsable api when I am using apache2 + gunicorn
The set up is Apache2 as a reverse proxy gunicorn serves django rest app gunicorn + django app + mysql are in docker Now the problem is in the browsable API, gunicorn serves the app at http://0.0.0.0:8000 but I use https://example.com/ as in Apache config. Every link in the browsable API is in the form of http://xxxxx. When clicks the link, it redirects to http protocol, resulting in 404. How can I tell gunicorn or django app to use https in the browsable API? -
Path configuration for sqlite3 in python3.6
I have a system Centos7 which has python2.7 as default and python3.6. Then I am running the following command on my django version=2.1 project python3 manage.py migrate but unfortunately I am having the following error No _sqlite3 module. I did some research and found that I should install sqlite-devel but still not working. -
How to set settings.DEBUG == True only for superuser and False for all users
I am using Django 2.1 and my project is ready for production. Is there a way that i can set settings.DEBUG == True only for superuser and show a default 500 internal server error for normal users. I have tried to write a middleware, but it seems not working. I do not want to use sentry(as recommended at many places). my middlewares.py is: import sys from django.views.debug import technical_500_response from django.conf import settings from django.contrib.auth import get_user_model user = get_user_model() #I am using CustomUser model not Django user model class UserBasedExceptionMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_exception(self, request, exception): if request.user.is_superuser: return technical_500_response(request, *sys.exc_info()) I have also loaded my middleware in. MIDDLEWARE = ['myproject.middlewares.UserBasedExceptionMiddleware',] -
The result of the annotated value is None after Subquery
This are my models: class Stockdata(models.Model): stock_name = models.CharField(max_length=32,unique=True) class Stock_Total_sales(models.Model): sales = models.ForeignKey(Sales,on_delete=models.CASCADE,null=True,blank=False,related_name='saletotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='salestock') quantity = models.PositiveIntegerField() class Stock_Total(models.Model): purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') quantity_p = models.PositiveIntegerField() I want to calculate the quantity of both purchase and sale and perform a Subtraction to the total quantity per Stockdata. I have done this: qs = Stockdata.objects.annotate( sales_sum = Subquery( Stock_Total_sales.objects.filter( sales = OuterRef('pk') ).values( 'sales' ).annotate( the_sum = Sum('quantity') ).values('the_sum') ), purchase_sum = Coalesce(Sum('purchasestock__quantity_p'),0) ) qs1 = qs.annotate( difference = ExpressionWrapper(F('purchase_sum') - F('sales_sum'), output_field=DecimalField()) But the value of sales_sum is coming null... Can anyone tell me what mistake I have done In my code. -
why am i getting error during django uploading process
this is my code in the views.py format = str(request.FILES['file']).rsplit(".")[-1] audio_tem = AudioSegment.from_file(request.FILES['file'],format=format) lenght = len(audio_tem) / 1000 folder = Folder.objects.get(pk=form.cleaned_data['folder'].id) file_name = f"{form.cleaned_data['name']}.{format}" #saving fs = FileSystemStorage() fs.save(file_name, request.FILES['file'] ) but i am getting error Exception Type: FileNotFoundError Exception Value:[Errno 2] No such file or directory:'C:\\Users\\user\\AppData\\Local\\Temp\\czyefhm_.upload.mp3' and also this C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\files\move.py in file_move_safe with open(old_file_name, 'rb') as old_file: i have googled it and also checked other related topic on stackoverflow but i can't get it working -
Django admin help text choicefield in tooltip
I need to add a specific help-text for each possible value in the choicefield. And I need to show it in a tooltip bubble. How should I include the value specific help text in the model? and should I use CSS or Javasript tooltip. I already included helptext in tooltips for other charfields using CSS :hover and adding it in an "extra-admin.css" and this works. -
Using docxjs to render a file preview in Django returing page not for a js file
I am using docxjs to render a file preview but it raises an error for certain jquery files called inside when it is being used in Django such as Request URL: http://localhost:8000/app/include/pdf/build/pdf.worker.js This seems to be called by pdf.js. How can I fix this? -
How to make django look for static in specified directories instead of view/file.css
I am aware that similar question was answered in Django - Static file not found But looks like I miss something or it was, somehow, a different case. I have my static folders set in settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static/") ] And in the code, I refer to file like {% load staticfiles %} <link href="{% static 'filename.css' %}" rel="stylesheet"> Still, django searches for this file in /view/filename.css How do I make it work? P.S. Also bootstrap.css <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="hash" crossorigin="anonymous"> isn't loaded for the same reason. -
How to implement django cms page versioning?
I am using django-cms 3.5.2 I am unable to find any plugins which support page versioning. There is plugin on github: https://github.com/divio/djangocms-versioning But I am not sure if it is published and ready to use. Any references. -
How to select a random Image from a directory of images for ImageField in Django model?
I am not being able to select a random image from a directory of random images. def random_img(): dir_path = os.path.join(BASE_DIR, 'media') files = [content for content in listdir( dir_path) if isfile(path_join(dir_path, content))] return str(choice(files)) I am using this function with: profile_pic = models.ImageField( default=random_img(), upload_to="profile_images/") But this is giving issues during migrations -
wordpress to Django & Keeping it SEO friendly?
I want to migrate to Django from Wordpress. Also i want to keep my new website seo friendly... So how can i move stuff from wordpress to Django and maintain the same URL structure? with human readable urls i.e. www.xyz.com/how-to-do-it instead of www.xyz.com/blog/12 Also, can i create everything in project folder instead of creating an App in Django? -
decorating a view with @login_required makes POST requests fail
I'm trying to handle a POST request from outside of django to path /app/process When I decorate my view with @login_required the requests come to my view change to /app/process/login?next=/app/process/ and request.POST contains non of my posted data! What is the problem? My View is like this: @login_required def callback(request): state = request.POST['State'] -
TypeError: 'Question' object is not iterable in test case assertion
I am testing whether the context variable contains a string def test_past_question(self): past_question = create_question(question_text='past question',days=-30) response = self.client.get(reverse('polls:detail',args=(past_question.id,))) self.assertQuerysetEqual(response.context['question'],'<Question: past question>') But it throws the following error: (mysite) sugumar@mysitedotcom:~/python/django/mysite$ python manage.py test polls Creating test database for alias 'default'... System check identified no issues (0 silenced). .E........ ====================================================================== ERROR: test_past_question (polls.tests.QuestionDetailViewTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/sugumar/python/django/mysite/polls/tests.py", line 73, in test_past_question self.assertQuerysetEqual(response.context['question'],'') File "/home/sugumar/.local/share/virtualenvs/mysite-VWHaFuat/lib/python3.5/site-packages/django/test/testcases.py", line 946, in assertQuerysetEqual items = map(transform, qs) TypeError: 'Question' object is not iterable ---------------------------------------------------------------------- Ran 10 tests in 0.069s FAILED (errors=1) Destroying test database for alias 'default'... In the command line: >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> from django.test import Client >>> client = Client() >>> from django.urls import reverse >>> response = client.get(reverse('polls:detail',args=(1,))) >>> response.context [{'True': True, 'False': False, 'None': None}, {'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0xb74425ec>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0xb69feecc>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0xb7440bfc>>, 'csrf_token': <SimpleLazyObject: 'FrAJ52rWG57SSbSE9y4V2tammjvQqjBUyl2tK6aEzj8ZfENSyFl7Fy05bnQh3XyQ'>, 'request': <WSGIRequest: GET '/polls/1/'>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'object': <Question: What's Up?>, 'question': <Question: What's Up?>, 'view': <polls.views.DetailView object at 0xb6a2fd4c>}] >>> response.context['question'] <Question: What's Up?> >>> exit See that in the command it showed so i tried self.assertQuerysetEqual(response.context['question'],'<Question: past question>') -
Django annotation is giving two diffrent result in two cases
I have two cases: Case 1: qs = Stockdata.objects.annotate(sales_sum=Coalesce(Sum('salestock__quantity'))) qs2 = Stockdata.objects.annotate(purchase_sum=Coalesce(Sum('purchasestock__quantity_p'))) Case 2: qs = Stockdata.objects.annotate( sales_sum = Coalesce(Sum('salestock__quantity'),0), purchase_sum = Coalesce(Sum('purchasestock__quantity_p'),0)) The result which is coming in Case 1 is absolutely perfect but when I am trying Case 2 the result is coming multiplying the no of entries I made.. Can anyone tell me what is the reason for this and can give a perfect solution to rectify the errors because the 2nd Case is what I need to use in my project... Thank you -
django: TestCase shows error only in script
I am checking whether my code runs correctly or not, using testcases If I run in the command line it works correctly >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> from django.test import Client >>> client = Client() >>> from django.urls import reverse >>> response = client.get(reverse('polls:detail',args=(1,))) >>> response.context [{'True': True, 'False': False, 'None': None}, {'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0xb74425ec>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0xb69feecc>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0xb7440bfc>>, 'csrf_token': <SimpleLazyObject: 'FrAJ52rWG57SSbSE9y4V2tammjvQqjBUyl2tK6aEzj8ZfENSyFl7Fy05bnQh3XyQ'>, 'request': <WSGIRequest: GET '/polls/1/'>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'object': <Question: What's Up?>, 'question': <Question: What's Up?>, 'view': <polls.views.DetailView object at 0xb6a2fd4c>}] >>> response.context['question'] <Question: What's Up?> But if test in the script it throws a key error: from django.test import TestCase from django.utils import timezone import datetime from polls.models import Question from django.urls import reverse def create_question(question_text,days): time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text,pub_date=time) class QuestionDetailViewTests(TestCase): def test_past_question(self): past_question = create_question(question_text='past question',days=30) response = self.client.get(reverse('polls:detail',args=(past_question.id,))) self.assertQuerysetEqual(response.context['question'],['<Question: past question>']) It throws the following error: (mysite) sugumar@sugushivaatgmaildotcom:~/python/django/mysite$ python manage.py test polls Creating test database for alias 'default'... System check identified no issues (0 silenced). ......... ---------------------------------------------------------------------- Ran 9 tests in 0.061s OK Destroying test database for alias 'default'... (mysite) sugumar@shiva:~/python/django/mysite$ … -
How to apply variable taxes in a Strategy in django oscar?
I am working on an oscar project for India and now I want to apply taxes on products. I have followed the docs for applying taxes over prices and availability , forked the partner app. When I specified rate=('0.20'), it applied a tax of 20 % on all products, now I want to make it dynamic. So I went through the code for strategy.FixedRateTax,and I tried implementing the code for get_rate(), since it gets called for all the products. How I want to make it dynamic is, based on the product category I want to apply the tax on the product which is in get_rate(). So I created a model in core/models.py class CategoryTax(models.Model): category = models.OneToOneField(Category, on_delete=models.CASCADE, unique=True) gst_tax = models.DecimalField(max_digits=11, decimal_places=4, null=True, default=0) def __str__(self): return "%s" % self.category Here importing of the category model is working fine,but when I go to the strategy.py and import models from core, and the other apps, django gives an exception. My forked_apps/partner/strategy.py is: from decimal import Decimal as D from oscar.apps.partner import strategy, prices from django.conf import settings from oscar.core.loading import get_model from core.models import CategoryTax Partner = get_model('partner', 'Partner') Category = get_model('catalogue', 'Category') Product = get_model('catalogue', 'Product') ProductCategory = get_model('catalogue', … -
How to create a custom default text in choicefield
In my web application, i have a drop-down list created using ModelForm which is rendering well, however, i can't set default text like "Choose One Option", rather its showing the default "----" which I would love to override I have tried using forms.ChoiceField in my widgets but its still not making any difference from django import forms from . import models from .models import FacultyData class DepartmentCreationForm(forms.ModelForm): class Meta: model = models.DepartmentData fields = ['fid', 'dept_name'] data = [] #data.append((None, 'select one')) data.append(('20', "---Choose One---")) CHOICES = FacultyData.objects.all() for v in CHOICES: # fname = "%s -- $%d each" % (v.faculty_name, v.created_on) data.append((v.id, v.faculty_name)) widgets = { 'fid': forms.Select(attrs={'class': 'form-control'}), 'dept_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Department Name'}) } I expect the default output to be "Select One" but the actual output is "-----" -
Google Sign-in in Android with django-rest-auth
I've been trying to add Google Sign-In in Android but have a couple of doubts. From the Android documentation Integrate google sign in android In the server side authentication part Client Id is required which is OAuth 2.0 web application client ID for your backend server. From android's documentation: Get your backend server's OAuth 2.0 client ID If your app authenticates with a backend server or accesses Google APIs from your backend server, you must get the OAuth 2.0 client ID that was created for your server. To find the OAuth 2.0 client ID From my understanding the flow would be: Android app will get the auth code from google which will be passed to the backend. The backend will get the access token with the auth code from the android app and the client secret. With the acess token we get the user's information and the access token is saved in the database. My doubts are: I read somewhere on StackOverflow that we need to create two OAuth client one for Android and one for Web Application. Is this True? Django Rest Auth Login View need to have one redirect_url defined but I don't understand what would be the … -
django PDF FileResponse "Failed to load PDF document."
I am trying to generate and output PDF from a django view. I followed the example in django documentation using ReportLab but the downloaded PDF is not opening in any PDF readers. I use Python 3.7.0, Django==2.1.3, reportlab==3.5.12. I tried adding content_type="application/pdf" to 'FileResponse` but still having the same issue. import io from django.http import FileResponse from reportlab.pdfgen import canvas def printPDF(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) p.drawString(100, 100, "Hello world.") p.showPage() p.save() return FileResponse(buffer, as_attachment=True, filename='hello.pdf') The generated PDF should be opening in all PDF readers. But I am getting 'Failed to load PDF document.'