Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form with more than one MultipleChoiceField
Problem Description Having a django form defined as class MyCustomForm(forms.Form): tomodel1 = models.ModelChoiceField(queryset=MyModel1.objects.all()) tomodel2 = models.ModelChoiceField(queryset=MyModel2.objects.all()) gives me a form where only the second field is in the form. I looked through the documentation - I thought it would be something similar to having multiple foreign keys and needing a related_name, but couldn't find anything on that. Any help is greatly appreciated! -
How can I check if a page has been visited? (I'm using an array field on the user model and I'm trying to add the page id in it)
This is not really a problem, this is more of a question because I don't know how to do this thing. So I need to check if a lesson has been done (by checking if the page has been visited once on a logged account). I've been trying to check if the page has been visited. If not, the ID should be added in the array of visited pages. The if condition looked like this: if lectie_id in Profile.lectiiRezolvate: pass and I'm getting argument of type 'DeferredAttribute' is not iterable . models.py from accounts from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.postgres.fields import ArrayField class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) xp = models.IntegerField(default=0) lectiiRezolvate = ArrayField(models.IntegerField(), null=True) exercitiiRezolvate = ArrayField(models.IntegerField(), null=True) exercitiiProvocari = ArrayField(models.IntegerField(), null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Lectie from accounts.models import Profile def lectii(req): lectii = Lectie.objects.all().order_by("id") context = { 'lectii': lectii } return render(req, '../templates/pagini/lectii-selector.html', context) def lectie(req, lectie_id): if lectie_id in Profile.lectiiRezolvate: pass lectie2 = get_object_or_404(Lectie, pk=lectie_id) lectiePDF = 'lectii/lectia-{}.pdf'.format(lectie2) context … -
Authy/Twilio OTP in Django without custom user model
I'm trying to learn how to use Authy/Twilio in a new Django app. I found this helpful demo application https://github.com/TwilioDevEd/account-security-quickstart-django which I was reading through to see how it all worked. I noticed in the settings.py file they referenced a custom user model, which I found here. The custom model looks very basic and doesn't have much of the info stored in the regular user model. My questions are: Is it required to use this custom model or can you somehow add the required info into the existing/default user model? How would this integrate with Django apps using something else (like ldap) as the backend instead of the django db user model? -
Django messages how to display certain success messages
I have two success messages displaying:one from 'profile.html' the other from include 'sidebar.html' after redirect i want to display the update profile notification only profile.html <div class="row justify-content-center"> <div class="col-md-6"> {% if messages %} <div class="alert alert-success p-3" role="success"> <ul class="messages" style="list-style: none; margin-bottom: 0;"> {% for message in messages %} <li{% if 'info' in message.tags %} class="info-message" {% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} </div> <div class="col-md-4"></div> </div> {%include 'base/sidebar1.html' with post=category_count all_cat=all_cat%} sidebar.html {% if messages %} <div class="alert alert-success" role="success" style=" padding-top: 16px; padding-bottom: 0px; margin-bottom: 10px;"> <ul class="messages" style="list-style: none;"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} -
How to get Django admin's "Save as new" to work with read-only fields?
I want to implement the "Save as new" feature in Django's admin for a model such as this one: class Plasmid (models.Model): name = models.CharField("Name", max_length = 255, blank=False) other_name = models.CharField("Other Name", max_length = 255, blank=True) selection = models.CharField("Selection", max_length = 50, blank=False) created_by = models.ForeignKey(User) In the admin, if the user who requests a Plasmid object is NOT the same as the one who created it, some of the above-shown fields are set as read-only. If the user is the same, they are all editable. The issue I have is that when a field is read-only and a user hits the "Save as new" button, the value of that field is not 'transferred' to the new object. On the other hand, the values of fields that are not read-only are transferred. Does anybody why, or how I could solve this problem? I want to transfer the values of both read-only and non-read-only fields to the new object. -
Django: create object from CSV that has a ForeignKey
I've 2 models: Category and Product, and I need to upload both from CSVs files. I can do that when uploading CSV data for the Category model, as it does not have a ForeignKey field. But I get an error when trying to upload data from a CSV fro the Product model. As it has a ForeignKey to the Category model. ValueError: Cannot assign "'Stickers'": "Product.category" must be a "Category" instance. Is it possible? I could leave the field as blank and not requeried to do this manually later, but woudl be ideal to do this automatically. commands/products.py: import pandas as pd import csv from shop.models import Product from django.core.management.base import BaseCommand tmp_data_products=pd.read_csv('static/data/products.csv',sep=',', encoding="utf-8").fillna(" ") class Command(BaseCommand): def handle(self, **options): products = [ Product( category=row['category'], product=row['product'], slug=row['slug'], description=row['description'], size=row['size'], quantity =row['quantity'], price=row['image'], available=row['available'] ) for _, row in tmp_data_products.iterrows() ] Product.objects.bulk_create(products) models.py: class Category(models.Model): category = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True, null=True) image = models.ImageField(upload_to='category', blank=True, null=True) video = EmbedVideoField(null=True, blank=True) class Product(models.Model): product = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) size = models.CharField(max_length=20, choices=TAMANIOS) quantity = models.CharField(max_length=20, choices=CANTIDADES) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True, null=True) available … -
How to break a line from a very large text in a django variable?
I need to display large text in a table, the problem that this is done dynamically by the variable {{students.answer}}. I tried the linebreaks but did not get the expected result. The table currently: -
Is it possible to aggregate a second query without using select_related? Django
Is it possible to aggregate a second query without using select_related? Django I am trying to aggregate a second query to compose the data needed for use in a single request. I have the main table and another table that are not linked in the model. The only form that identifies them is id; The main table has the id_tipo; The second table has an id; Thank you very much for your attention. aulas = Aula.objects.select_related('cliente').extra( select={ 'row_reposicao': 'SELECT data FROM app_reposicao WHERE app_reposicao.id = id_tipo' }).all() -
Displaying only the first paragraph of a body of text in a Django template
If I have a large body of text, e.g. a blog post, how could I display the entire first paragraph of each text on the blog's home page, instead of breaking it on a random letter in a random word with the following? <p>{{ post.text|linebreaksbr|slice:":400" }}</p> -
instantiate class in python as a callable object
i have just trying to do some coding in django until i found this block of code which sound strange for me, the problem, if it's a problem is that in the following code he instantiated the class with an object but we used it as a callable even without define call method here is the code of the class in djagno source code on github code of the class you can see the instantiation at the bottom of page, too and here we when we used it used it by inheriting from it class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_vlaue(self, user, timestamp): return (str(user.pk)+str(timestamp)+str(user.is_active)) account_activation_token = TokenGenerator() and when used it as i said we called it -- in the token key of the dictionary message = render_to_string('acc_activate_email.html', {'user': new_user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(new_user.pk), 'token': account_activation_token(new_user))}) you can take a look at the original code here original code where we used the object ask me for any Clarification -
ValueError: Cannot serialize: <google.oauth2.service_account.Credentials object at 0x7f292c774908>
I am using Django storages form google cloud, but on migrations its throwing an error ValueError: Cannot serialize: <google.oauth2.service_account.Credentials object at 0x7f292c774908> There are some values Django cannot serialize into migration files. I have also used deconstructible decorator but the provlem still persists. from django.utils.deconstruct import deconstructible from google.oauth2 import service_account from storages.backends.gcloud import GoogleCloudStorage GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "/path/to/my-key.json" ) @deconstructible class MyGoogleCloudStorage(GoogleCloudStorage): pass My models.py is class Company(models.Model): image_1 = models.ImageField( upload_to=image_directory_path, storage=MyGoogleCloudStorage( credentials=GS_CREDENTIALS, bucket_name='webdeveloper', default_acl='publicRead' )) image_2 = models.ImageField( upload_to=image_directory_path, storage=MyGoogleCloudStorage( credentials=GS_CREDENTIALS, bucket_name='webdeveloper', default_acl='publicRead' )) What am I doing wrong. Its very frustuating -
Getting permission errors for newly added template file
Django gives <[Errno 13] Permission denied:> Error for an html template file when navigating to the link that uses that template.The template is for a details view of Posts on a blog site. I have all the other templates in the same directory, only this one gives an error. Tried to open the PyCharm IDE with administrator permissions but it didn't work. I added the file from PyCharm IDE by going to the folder and add files, and then selected the HTML file format. Here's my template file: from django.contrib import admin from django.urls import path from .views import PostListView, PostDetailView from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('about/', views.about, name='blog-about'), ] Here's the url.py file: from django.contrib import admin from django.urls import path from .views import PostListView, PostDetailView from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('about/', views.about, name='blog-about'), ] Here's the Views.py File: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post # Create your views here. def home (request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' #<app>/<model>_<viewtype.html> context_object_name = 'posts' ordering … -
Django-Push-Notification BareDevice & DeviceManager Lost
A long day ago, I notice in Django-Push-Notification had two class name DeviceManager and BareDevice but now i tried to use them installing the package. can anyone let me know, in what version of Django-Push-Notification Contain these Two Classes? -
django delete object using AJAX or javascript with confirm
hello I want to delete a Django object using AJAX or JavaScript with confirm message on clicking delete but I don't know how to complete AJAX request. views.py def delete(request,id): try: inta = work.objects.get(pk=id) inta.delete() except: pass return HttpResponseRedirect(reverse('home')) urls.py url(r'^delete/(?P<id>\d+)/$',views.delete, name='delete') html : {& for app in apps &} <p>{{ app.item0 }}</p> <p>{{ app.item1 }}</p> <p>{{ app.item2 }}</p> <button data-object-id="{{ app.id }}">remove</button> {% endfor %} $('button').on('click', function(){ var confirmation = confirm("are you sure you want to remove the item?"); if (confirmation) { // execute ajax alert('removed'); } }) -
How to fix an attribute with no file associated with it?
I'm setting up a form and want to allow user editing (clear or upload) their profile picture. I got a ValueError - attribute has no file associated with it when the profile picture has no file. here are some code forms.py class EditProfileForm(ModelForm): first_name = forms.CharField( label='firstname', widget=forms.TextInput(attrs={ 'name': 'firstname', 'id': 'firstname', 'class': 'form-control' }) ) last_name = forms.CharField( label='lastname', widget=forms.TextInput(attrs={ 'name': 'lastname', 'id': 'lastname', 'class': 'form-control' }) ) class Meta: model = UserProfile fields = ( 'first_name', 'last_name', 'profile_picture' ) def save(self, user=None): user_profile = super(EditProfileForm, self).save(commit=False) if user: user_profile.User = user user_profile.save() return user_profile views.py def user_edit(request): title = "profile suno.space" heading = "Your account" context = { 'title': title, 'heading': heading, } if request.method == 'POST': form = EditUserForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect(reverse('accounts:view_profile')) else: form = EditUserForm(instance=request.user) context['form'] = form return render(request, 'accounts/user_edit.html', context) template <form id="account-form" method="post" enctype="multipart/form-data" class="form"> {% csrf_token %} <div class="form-controls"> <div class="row"> <div class="col-sm-12"> <div class="form-group"> <label for="profile_picture" class="form-label">Your profile picture</label> <div>{{ form.profile_picture }}</div> </div> </div> </div> </div> </form> I expect that the template renders the browse button such as the admin template does. thanks for your answer. -
How fix: No so such file <nameproy>_django_1 exited with code 127? (trying to start the project locally)
trying to start the project locally? using django-composer- 1. pip install "cookiecutter> = 1.4.0" 2. cookiecutter https://github.com/pydanny/cookiecutter-django 3. docker-compose -f local.yml build 4. docker-compose -f local.yml up What is this error? ty -
How to render a django-filter queryset to PDF?
I am using django-filter and I would like to add a button on my template to render as PDF after the user filtering the model. Here my views.py def search_people(request): person_list = models.Person.objects.all() person_filter = filters.PersonFilter(request.GET, queryset=person_list) return render(request, 'template.html', { 'person_filter': person_filter, } ) How can the user filter the Person by City and render to PDF when he clicks on a button? This as very helpful to render the entire model to PDF, but I only need the filtered part. -
How to use extra function to aggregate a table separately django?
How to use extra function to aggregate a table separately django? I tried the example below, but I did not succeed. Thank you very much for your attention. aulas = Aula.objects.extra( select={ 'reposicao': 'SELECT * FROM app_reposicao WHERE app_cfc_reposicao.id = app_aula.id_tipo' }) subquery must return only one column LINE 1: SELECT (SELECT * FROM app_reposicao WHERE app_reposi... -
How do I pass my variable from template to views.py
I wish to know how I can pass the oobcode value to def postresetusername in views.py . Thank you in advance. Any help is greatly appreciated reset_username.html <script type="text/javascript"> var oobcode; function func(){ oobcode = localStorage.getItem("storageName"); } </script> views.py def postresetusername(request): authe.verify_password_reset_code(oobcode,"new_password") return render(request, "reset_username.html") -
How to create and filter related model objects in django application
I am building a testing application and I need to run through a series of test steps. I have a few questions surrounding the concern of mine. When you create a test, you will select wether it will be a full or partial test. A full test will run through all the test steps. A partial test will be able to go a individual step. When a full test is created then all the test steps should be created by default. How will I filter the test steps when a user selects a partial test? In my test-detail template, I need to go through a series of questions which will be forms that send requests and recieve responses from an api. I am wondering how i can use a form set or another way to pass on to the next form. For example, step 1 - do whatever it says, click next. Next will be the form submit which will send the request and the next form will populate the django template. Any help is greatly appreciated. View.py def create_test(request, id=None): form = PrinterTestForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.printer = Printer.objects.get(id=id) instance.save() # test = Test.objects.get_object_or_404(Test, id=instance.id) … -
Problems with get_object_or_404 in Python
I have an error where I can't seem to get this part of my code to work. It gives me the following error 'element_id' is an invalid keyword argument for this function. At first, I saw that I didn't call the proper model, I have altered this but it still doesn't seem to work. def Input(request, element_id, session_id): input_element = get_object_or_404(InputData, pk=element_id) voice_service = input_element.service session = lookup_or_create_session(voice_service, session_id) if request.method == "POST": session = get_object_or_404(CallSession, pk=session_id) value = 'DTMF input' result = UserInput() result.session = session result.category = input_element.input_category result.save() return redirect(request.POST['redirect']) session.input_step(input_element) context = input_generate_context(input_element, session) context['url'] = request.get_full_path(False) return render(request, 'input.xml', context, content_type='text/xml') InputData model: class InputData(VoiceServiceElement): """ An element that saves user input to a line in the database. """ _urls_name = 'service-development:InputData' ask_input_label = models.BooleanField(_('Ask the user to fill something in'), default=True) input_voice_label = models.ForeignKey( VoiceLabel, verbose_name = _('Ask input label'), help_text = _('The voice label that is played before the system asks the user to fill in the input'), on_delete=models.SET_NULL, null=True, blank=True, related_name='ask_input_label_input' ) ask_confirmation = models.BooleanField( _('Ask the caller to confirm their input'), default=True) ask_confirmation_voice_label = models.ForeignKey( VoiceLabel, verbose_name = _('Ask for confirmation voice label'), help_text = _('The voice label that asks the … -
Django ManyToManyField insert with create()
Per documentation you can create and add to M2M field in one step using create(): new_publication = a2.publications.create(title='Highlights for Children') but, in my case this approach throws an error: ValueError: Cannot add "<Atributi: ['id: 18', 'naziv: sa', 'vrijednost: sdu', 'tip: txt']>": instance is on database "None", value is on database "default" Here are my models: class MetaModel(models.Model): class Meta: abstract = True def __str__(self): return str([field.name+': '+str(getattr(self, field.name)) for field in self._meta.fields]) class Atributi(MetaModel): naziv = models.CharField(max_length=50) vrijednost = models.CharField(max_length=50) tip = models.CharField(max_length=10) class Inventar(MetaModel): naziv = models.CharField(max_length=50, unique=True) kolicina = models.DecimalField(max_digits=16, decimal_places=10, blank=False) jedMjere = models.CharField(max_length=50, blank=False) atributi = models.ManyToManyField(Atributi) And if I try: item = Inventar(id=1) item.atributi.create(**someparams) it successfully inserts into Atributi but on creating relation it throws aforementioned error. Following is executed successfully: item.atributi.add(idFromAtributi) Django version is 2.2 -
Unable to select custom databases for Admin
I am currently working on a django application to feature multi-tenancy. I am currently using an isolated data base model for my project. I currently have two databases. 1. Default 2. Alora With edits to the authentication mechanism, I am able to pass in the database selector during login and handle things with views. However, when I try to login to the admin page, i.e, "sitename/admin" , the system somehow only picks up the default database, even though I have edited the template to accept database selector. Could you please help identifying the file>methods to edit to incorporate database selector. I perform this selection operation by using ".using('database_name')." Any help on this is deeply appreciated :) -
How do you write a Django query where the condition if a COUNT of related items?
I'm using Django and Python 3.7. I have these two models, related to one another through a foreign key ... class Website(models.Model): objects = WebsiteManager() path = models.CharField(max_length=100) class Article(models.Model): website = models.ForeignKey(Website, on_delete=models.CASCADE, related_name='articlesite') title = models.TextField(default='', null=False) url = models.TextField(default='', null=False) I want to write a Django query that returns the web sites who have more than 100 articles tied to them. In PostGres, I can write this query select w.id, count(*) FROM website w, article a where w.id = a.website_id group by w.id; but I'm unclear how to do this with a Django query. How do I write a query where the condition if a COUNT function? -
Django Push_notification's Bare Device can't be imported
I got a Django project and its model, this module imported: from push_notifications.models import BareDevice I have installed push_notification library successfully but the problem is, this library don't have any function or class named BareDevice Can anyone know about this? I just stuck with this project only for this BareDevice