Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing django-recurrence field via REST API
Folks, I am using django recurrence field in my app and its not clear how to format the field when passed via REST API. Any help is appreciated. from recurrence.fields import RecurrenceField class Course(models.Model): title = models.CharField(max_length=200) recurrences = RecurrenceField() -
django signals, channels and transactions
It seems an obvious combination to use django's signalling architecture together with channels: a model is changed, a signal is fired, and a consumer is notified (via the signal handler and channel layer) to update a client via, for instance, a WebSocket. However, very often a model is updated as part of a transaction, and django's pre_save and post_save signals are sent in the middle of the transaction, meaning the change you notify the client about may never happen at all. Even more annoyingly, when you send the information across the channel layer you're looking at the database from another thread and, since the transaction is not complete, you can't get the new data. django.db.transaction.on_commit provides a way to schedule (part of) the signal handler to run after the transaction is done, providing a workaround, but this seems to be such an obvious problem with absolutely no documentation or stackoverflow chatter that I'm a bit perturbed (one can of course find discussions about each pair of the three mentioned topics!) So is this architecture: signal -> handler -> channel layer -> consumer [ -> client ] actually a bad one? Is there some alternative that doesn't involve wrapping each handler … -
Why can you import UpdateView in "multiple ways"
Why do both of the following ways of importing UpdateView work?: 1. from django.views.generic import UpdateView 2. from django.views.generic.edit import UpdateView I was assuming 2. was the correct way, and 1. would not work, but from testing both work. -
Django Templating filter Object in Status X
i want to display all objects of category_request in status Rejected, but it seems that im doing something wrong here. I'm quite new to Django/Python, if somebody has an idea please scream it out to me ;) models.py class CategoryRequests(models.Model): author = models.ForeignKey(User, related_name='status', on_delete=models.CASCADE) title = models.CharField(max_length=20, verbose_name="Title") description = models.TextField(max_length=175, null=True, blank=True) cover = fields.ImageField( blank=True, null=True, validators=[default_image_size, default_image_file_extension], upload_to=get_file_path_user_uploads, dependencies=[FileDependency(processor=ImageProcessor(format='JPEG', quality=99, scale={'max_width': 1000, 'max_height': 1000}))]) published_date = models.DateField(auto_now_add=True, null=True) status = StatusField() STATUS = Choices('Waiting', 'Rejected', 'Accepted') views.py def view_profile_categoy_requests_rejected(request, pk=None): if pk: user = get_user_model.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'myproject/category_request_rejected.html', args) template.html <div class="container"> {% if category_request.status_set == Rejected %} {% if user.categoryrequests_set.count == 0 %} <div class="centercontentfloat"> <div class="card border-primary mb-3"> <div class="card-header">No Requests available </div> <div class="card-body text-primary"> <p class="card-text">You did not created any posts at all, go ahead and tell the world what it use to know!</p> <a href="{% url 'post_new' %}"> <button class="btn btn-dark" type="submit">Create new Post <i class="fa fa-arrow-right"></i></button> </a> </div> </div> </div> {% else %} <h4 class="sub-titel-home">Rejected Request(s):</h4> <table class="table center class-three-box"> <thead> <tr> <th style="font-size: small">Title</th> <th style="font-size: small">Comment's</th> <th style="font-size: small">Created</th> </tr> </thead> <tbody> {% for category_request in user.category_request_set.all %} <tr> <td><a … -
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$ …