Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Really slow RunPython migration on related models
I am trying to optimise the speed of a migration on a large table (250K objects). The goal is to add to each row a user field based on the user of an object related to this row: I tried using an F expression but sadly django won't allow relations in them. Note that I am mostly a beginner in SQL :) ## models.py class Band(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, default=None) ... class Album(models.Model): band = models.ForeignKey( Band on_delete=models.CASCADE, null=True, default=None) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, default=None) ... ## 0035_submission_add_user.py def forwards_add_user(apps, schema_editor): Album = apps.get_model('band', 'Album') db_alias = schema_editor.connection.alias albums = Album.objects \ .using(db_alias) \ .filter(band__isnull=False) \ .select_related('band', 'band__user') for each in albums: each.user = each.band.user Album.objects \ .using(db_alias) \ .bulk_update(albums, ['user']) class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.RunPython(forwards_add_user, reverse_add_user), ] This migrations currently takes an hour on my local with 100% usage on the database for the whole duration. I have a better CPU thank my production database so this worries me a lot, downing the production database for an hour is not really an option. I'm looking at two different solutions both of which I have no idea of how … -
Accessing Django session via API in development
I have separate backend and frontend apps that communicate via API. I am using DRF so it handles django sessions under the hood when I use production build of my JS app. Is there a way to make it work as nicely while JS app is running on dev server? DRF provides some testing tools, but I haven't figured out if any of them can be of use for this case. If there isn't any, will it be enough just to create sessions manually and save their keys in cookies? I mean, for testing purposes. -
Getting highest value from a table in Django
I have the following model: class tst(models.Model): item = models.CharField(max_length=15) Price = models.FloatField() Perc = models.FloatField() def save(self, *args, using=None, **kwargs): super(tst, self).save() From a view, i would like to get the highest value for the columnPerc and the name of Item for that value. How can i do that? I tried to use aggregate: max = tst.objects.aggregate(Max('Perc')) But other than returning None, it doesn't return the value Item for the row with the highest Perc. Is there any way to do that in django? Any advice is appreciated -
How to pass a ListView variable into a JavaScript variable in Django
I opened a new pop-up window in the parent form template. And the child template gets the list through the ListView. How can I access the values in a table? I want to get the zipcode value of JS. (The id value of the parent template is id_zipcode.) view.py class OldAddress(ListView): model = Address context_object_name = 'child' template_name = 'partials/address.html' I want to pass the zipcode value of the corresponding row to the parent input when clicking Select. <div class="container my-5"> <h2 class="my-5">Address List</h2> <table class="table table-hover"> <thead align="center"> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Zipcode</th> <th scope="col">Apply</th> </tr> </thead> <tbody align="center"> {% for addr in child %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ addr.name }}</td> <td>{{ addr.zipcode }}</td> <td> <a class="mr-2" href=""><span class="badge" onclick="setZipcode();">Select</span></a> </td> </tr> {% endfor %} </tbody> </div> <script type="text/javascript"> zipcode = "{{ addr.zipcode }}"; </script> <script> function setZipcode(){ opener.document.getElementById("id_zipcode").value = zipcode } </script> -
not showing the title in django framework
I'm new to django framework and i'm using VS code this is view.py file posts = [ { 'author': 'CoreyMS', 'title': 'Blog Post 1', 'content': 'First post content', 'date_posted': 'August 27, 2018' }, { 'author': 'Jane Doe', 'title': 'Blog Post 2', 'content': 'Second post content', 'date_posted': 'August 28, 2018' } ] def home(request): context = { 'posts': posts } return render(request, 'blog/home.html', context) and this my home.html file <!DOCTYPE html> <html lang="en"> <head> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p>{{ post.content }}</p> <p>{{ post.authorname }}</p> <p>{{ post.postdate }}</p> {% endfor %} </body> </html> the body part works fine but the title doesn't work , i expect to see the title which is blog post one or blog post 2 where is the problem ? thank you -
How to login with registration number and password in Django
I am looking for ways to login in Django using something like student registration number and password or matriculation number and password, all I am seeing on the internet is username and password or email and password, can I use AbstractBaseUser for it? What is the easiest way to achieve it. -
Parse obj in DRF when use multipart/form-data
I have a model: class Post(models.Model): fonts = JSONField() # Postgres I have a nested serializer: PostSerializer(serializer.ModelSerializer): fonts = FontsSerializer(many=True, required=False) FontsSerializer(serializer.Serializer): primary = serializers.CharField(required=False, allow_null=True) secondary = serializers.CharField(required=False, allow_null=True) Front guys used multipart/form-data to send me data: But its not update data on my side. I cant find how to deal with it. I tried change keys to .: And its working.Data is successfully updated. What way is a correct? How can I setup DRF to work with [] template? P.S: They cant used json, The question about form-data and how to deal with nested inside. -
Firebase messaging in Django template
Is it possible to get notifications from firebase using Django templates? As I understand, there must be a service worker in firebase-messaging-sw.js file, that must be in project root. But how can I do this in Django, if js-scripts goes to the static folder? -
How to remove blank row in word table using jinja2?
Code Given When {{ loop.index }} is even it prints out blank white row while checking at if statement.Giving the below output- Output recieved But the required output is Required Output What all we tried is {% spaceless %}, {%- if ... %}, {% if ..-%},{%- if ..-%}, -
I am making a portfolio website but my browser is not recognising javascript code
document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.materialboxed'); var instances = M.Materialbox.init(elems,{}); }); I have written this javascript code but I am getting this error message- Uncaught ReferenceError: M is not defined at HTMLDocument. ((index):63) -
Use Bootstrap only for its Form styling
I have a Django website already complete with its CSS. One of its templates has a form. As anyone familiar with Django forms, the most common way to style it nicely is by using crispy form or Bootstrap. However, with my CSS already in place whenever I use either of the above solution, the website appearance gets messed up. Things I have already done and attempted: placed the Bootstrap stylesheet before my own stylesheet override Bootstrap but realised it was so tedious when I only want to style a single form Is there a way to use only the Form styling of Bootstrap so it doesn't mess up the rest of my stylesheet? -
Django not using databases from settings.py
I'm a few weeks into Python/Django and encountering an annoying problem. I have some existing databases set up in settings.py, everything looks good, I've even accessed the databases using connections[].cursor() But the databases (and data) are not making their way into models that I want to use, despite doing the makemigrations and migrate commands. I was able to use py manage.py inspectdb --database-dbname and copied that class information manually into my models.py, but that didn't work either (typing py manage.py inspectdb on its own does not pull up these databases, I was only able to view by that --database extension). So I'm stumped, as it seems I'm doing all the right steps but not able to use these existing databases in Django. Any other hints and steps I can take are welcome! -
DRF cursor pagination with custom OrderBy
I need to do some custom sorting on a Member model which looks like this (simplified): class User(): username = models.CharField() # ... class Member(): user = models.ForeignKey(User) # not required invite_email = models.EmailField() # ... I need to sort my queryset of Member in the following way: Members that do not have a user set come last; Sort by user username alphabetically (case insensitive), or invite_email if Member does not have a user. I can do the appropriate sorting with django: queryset.order_by(Lower('user__username').asc(nulls_last=True), 'invite_email') I thought that I could override the order_by method to apply my custom ordering. My problem comes with DRF cursor pagination. Reading from the doc, it seems like the ordering should be a string, or an unchanging value generally speaking. But when I use the Lower expression to order my queryset as needed, the ordering received in the cursor pagination class is an OrderBy object. Doing so, the paginate_queryset method is unusable. I find it weird that you can't apply a custom filtering with the DRF pagination classes. Am I missing something? Thanks in advance for any tips you might have! -
ML Application using Python Django
I have developed a Python Django application where I have used ML model to classify incoming data. I have used celery as task scheduler. As soon as a new data comes, celery will pick it and pass into the model for prediction. Used Azure cache for Redis as the broker and the database is Azure SQL Server DB. Can you please suggest how to build the dockerfile and I would need to host the application on Azure WebApp. Issues: 1) How to build the dockerfile 2) how to pass the connection strings of redis and database in docker 3) Do I need to use docker build or docker compose. Please help. -
How can i add user data into CSV FILE in python
HII i can write headers but i'm not able to add user data into csv file.. def add(request): # data={} if request.method=='POST': form=dataform(request.POST) a=form.data['Areatype'] b=form.data['Size'] c=form.data['Location'] fields = ['areatype','size','location'] with open(r'F:\project\raj1.csv','w') as f: dict_data=DictWriter(f,fields) dict_data.writeheader() -
How do I include a built-in django widget template in my custom widget template?
I am writing a django widget in my app. However, as the widget is an extension of a <textarea> I would like to include within it the django textarea widget: django/forms/templates/django/forms/widgets/textarea.html. I tried this: <div name="{{ widget.name }}"{% include "django/forms/widgets/textfield.html" %}> {% if widget.value %}{{ widget.value }}{% endif %} </div> However, it resulted in the following error: TemplateDoesNotExist at /admin/myApp/myModel/add/ How should I refer the include statement to the proper template file? -
Django: reencode request and call another view
I am working on a backend application that exposes a JSON-based REST api. However, I am using some library that has some of its own endpoints and they accept form-endcoded data. I want to extend the actions done by those endpoints and expose my extended versions. At the same time, I want my API to be consistent and I want all my endpoints to use JSON. To be more specific, I use the oauth2_provider library, and I want to logout users when they revoke a token. I am also considering making a logout handle that would require the bearer token in the Authorization header and would both logout the user and revoke the token. My first approach to this was to write a wrapper view around the oauth2_toolkit revoke token view, loggging the user out in the wrapper view and then calling the actual revoke_token view. However, I have to modify the body of the request, which is immutable. class Logout(View): def get(self, request): if request.user.is_authenticated: logout(request) # modify or create a new request here RevokeTokenView.as_view(request) I couldn't find a way to clone a Django request or modify it. Is there a way to do it? (For now I am … -
Django subquery to self model returns None
I'm trying to do a Subquery expression to the same model to get an object of a different type. For some reason the annotated attribute is returning None despite having a value when completed manually. What am I missing here? Unfortunately I can't change the models. class AccountsReceivable(models.Model): DEBIT = 1 CREDIT = 2 TYPE_CHOICES = ((DEBIT, 'Debit'), (CREDIT, 'Credit')) type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES) order = models.ForeignKey(Order, blank=True, null=True) on_account = models.ForeignKey(OnAccount, blank=True, null=True) payments = models.ManyToManyField(Payment, blank=True) allocated = models.DecimalField() Here are the relevant lines in the shell. The output is commented next to each line. payment = Payment.objects.last() debits = ( AccountsReceivable.objects .filter(payment=payment) .exclude(type=AccountsReceivable.CREDIT) .annotate( to_reverse=Subquery( AccountsReceivable.objects .filter( type=AccountsReceivable.CREDIT, order=OuterRef('order'), on_account=OuterRef('on_account'), payments=payment ) .values('allocated')[:1] ) ) .order_by('id') ) debits.count() # returns 150 (correct number of debits) debits[0].to_reverse # returns None to_reverse = ( AccountsReceivable.objects .filter( type=AccountsReceivable.CREDIT, order=debits[0].order, on_account=debits[0].on_account, payments=payment ) .values('allocated')[:1] ) to_reverse # returns <QuerySet [{'amount': Decimal('1716.47')}]> -
NOT NULL constraint failed: users_profile.usertype
I'm trying to build a Django app, where two different types of users can register - Tenants and Landlords. I have added a BooleanField in my models.py which will add an entry to DB and in my forms.py I have added a ChoiceField where users have an option to choose who they are. Upon clicking Register, the account is created but I get an IntegrityError at /register. I'm using Python 3, Django=3.0.3 and django-crispy-forms=1.8.1 models.py from django.db import models from django.contrib.auth.models import User from PIL import Image usertypechoices = [(1,'Landlord'),(2,'Tenant')] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') usertype = models.BooleanField(choices=usertypechoices) def __str__(self): return f'{self.user.username} Profile' # Resize images to reduce memory wasted def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile from django.forms import ModelForm from .models import usertypechoices class UserRegistrationForm(UserCreationForm): email = forms.EmailField() usertype = forms.ChoiceField(choices=usertypechoices) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegistrationForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators … -
Best practices to store rsa private keys used to sign JWT tokens
I have an application that generate signed JWT using private generated keys and expose corresponding public keys. I'd like to find a secure way to store those keys on the server. Note that I can safely revoke a key without causing huge problems for my application, and thus I don't care if I drop keys. Ideally I don't want to store those permanently in a file or in a database. And all keys can be revoked/dropped when the server is initialized. Is-it considered as safe if I generate new keys with a short TTL? Something like 2 hours? I would then generate a new key each time I need to sign a token and the most recent available key TTL is to close compared to the required validated period for the corresponding JWT signed with a key. In that case is-it considered safe enough to store the keys in the database and/or the file system ? Which option is considered the best? -
Python script processes and generates a result in html format. I want it post on web using WSGI
how do I call from myapp.wsgi my existing testreport.py . testreport.py processes DB fetches a result in HTML format . myapp.wsgi status = '200 OK' html = '<html>\n' \ '<body>\n' \ '<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \ 'Welcome to mod_wsgi Test Page\n' \ '</div>\n' \ '</body>\n' \ '</html>\n' response_header = [('Content-type','text/html')] start_response(status,response_header) return [html]``` -
Get last Django db model instance created corresponding to conditional field filter?
Let's say I've this Django database model: class Something(models.Model): relevant_field = IntergerField() ... Instances are created with different values for relevant_field, let's say 1, 2, 3, 1, 2, 3. Now I'd like to get the single latest (created most recently) instance for every field value 1, 2 and 3. How do I have to implement the query? -
Is there anything like Ruby trailblazer for Django?
I use Django every day in work and I recently came across Ruby project using trailblazer and I find it pretty cool concept for storing business logic. Trailblazer is a thin layer on top of Rails. It gently enforces encapsulation, an intuitive code structure and gives you an object-oriented architecture. Django is not strict and does not tell you where to store business logic exactly. We use services in our projects but I find concept of trailblazer much better. Is there anything like trailblazer for Django and wehere do you usually store business logic in Django projects? -
How can to test data migration?
I have following data migration from django.db import migrations, models def gen_str(apps, schema_editor): Donation = apps.get_model('donation', 'Donation') Donation.objects.filter(payment_method_id__isnull=True).update(payment_method_id='') class Migration(migrations.Migration): dependencies = [ ('donation', '0006_auto_20200129_0942'), ] operations = [ migrations.RunPython(gen_str, reverse_code=migrations.RunPython.noop), migrations.AddField( model_name='donation', name='payment_intent_id', field=models.CharField(blank=True, default='', max_length=256), ), How can to test function gen_str? I tried this: class DataMigrationTests(TestCase): def test_gen_str(self): migrations.AlterField( model_name='donation', name='payment_intent_id', field=models.CharField(blank=True, null=True, default='', max_length=256), ) DonationFactory.create_batch(7, payment_method_id=None) data_migration.gen_str(apps, connection.schema_editor()) payment_ids = Donation.objects.values_list('payment_method_id', flat=True) print(payment_ids) self.assertTrue(payment_ids, '') But got error django.db.utils.IntegrityError: Null value in column "payment_method_id" -
Unread posts Django
I've build a blog using Django (very minimal functional blog) and I want to be able to show to the user in my blog only the posts he hasn't read yet. I have 10,000+ posts and I want to show the user every time he log in a random posts he has not seen yet/ I am new with Django and I not sure I should do it the right way. I have the Post model: class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title Thank you!