Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Attach Multiple PDF files in email attachment using Django
I am trying to use django's core emailing functionality but for some reason I cant seem to find a way to attach 2 files in one email. I have tried to put the files in an array but this throws an error. Sending one file works but as soon as i create an array it stops working. Below are the steps I have taken. In my views.py i have from django.core.mail import EmailMessage and below is the part I am trying to send the 2 email attachments. msg = EmailMessage('Email Subject', 'Test Email', 'from@email.com', ['test@gmail.com']) msg.content_subtype = "html" msg.attach_file(['product/y.pdf', 'product/x.pdf']) msg.send() Please help. -
Testing a form on Django
I am trying to run a test on a form. It keeps returning invalid. Other forms work fine though. The form in forms.py: class SongForm(forms.ModelForm): class Meta(): model = Song fields = ('title', 'type', 'audio_file', 'description', 'written_by', 'song_text') The model the form comes from in models.py: class Song(models.Model): title = models.CharField(max_length=120) SONG_TYPES = ( ('KI', 'Kiirtan'), ('PS', 'Prabhat Samgiita'), ('BH', 'Bhajan'), ) type = models.CharField(max_length=30, choices=SONG_TYPES) capo = models.PositiveIntegerField(blank=True, null=True, validators=[MaxValueValidator(12)]) description = models.TextField(blank=True) uploader = models.ForeignKey('Profile', null=True, on_delete=models.SET_NULL) written_by = models.CharField(max_length=50, blank=True) song_text = models.TextField(blank=True) audio_file = models.FileField(upload_to='songs/') upload_date = models.DateField(auto_now=False, auto_now_add=True) edit_date = models.DateField(auto_now=True, auto_now_add=False) chords = models.ManyToManyField('Chord', related_name='chords', through='ChordIndex') The test in tests/test_forms.py: def test_Song_form_is_valid(self): the_data = { 'title': 'a song', 'type': 'KI', 'description': '', 'written_by': '', 'song_text': '', } form = SongForm(data=the_data) self.assertTrue(form.is_valid()) The form works correctly in the web app with a POST method. I even tried copying the values from a valid POST on the test and it still failed! I've been stuck with this for a while... Any clues? 🙏🏼 -
Best way to save hidden fields from CreateView that have unique_together constraint?
I found a lot of questions and answers on this topic but all of them leave me confused as to what would be the best way to handle this and it seems a lot of aspects have to be considered (e. g. I read about putting the validate_unique() function into the ModelForm but some say it would be unsafe to pass the user to the form) I want to build a form that users can use to register for an event. The event is derived from the url, the user from the request. Hence I don't actually need it in the form. The issue then is to conduct a check for the together_uniqueness as there can only be one registration per user per event. Currently my code looks like this: models.py: class Participant(models.Model): class Meta: constraints = [models.UniqueConstraint(fields=["user", "event"], name="user_unique_per_event")] user = models.ForeignKey(LocalUser, on_delete=models.PROTECT) event = models.ForeignKey(Event, on_delete=models.CASCADE) participating = models.BooleanField() forms.py: class EventRegistrationForm(forms.ModelForm): class Meta: model = Participant fields= ['participating'] views.py: class EventRegistrationView(CreateView): template_name = 'events/event_registration.html' form_class = EventRegistrationForm queryset = Event.objects.all() def form_valid(self, form): form.instance.event = Event.objects.get(slug=self.kwargs['slug']) form.instance.user = self.request.user What's the best way to implement a check regarding the unique_together constraint? What's the best way to handle … -
How to call stored PostgreSQL function in Django?
I have a stored function in PostgreSQl. I want to call this function through django and connect with a regular query(According to the table PayrPaymentSource). How to do it? Function: CREATE OR REPLACE FUNCTION select_cards() RETURNS TABLE(payer_id bigint , source_details jsonb) AS $$ SELECT payer_id as payer_id, source_details as source_details FROM "processing"."payer_payment_source" WHERE payment_type_id = 'bank_card_details'; $$ LANGUAGE sql; views.py query paymentsss = Transaction.objects.all().select_related('currency', 'payment_source__payment_type', 'deal__service__contractor') models.py class PayerPaymentSource(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) payer_id = models.BigIntegerField(blank=True, null=True) payment_type = models.ForeignKey(PaymentType, max_length=64, blank=True, null=True, on_delete=models.CASCADE) source_details = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = '"processing"."payer_payment_source"' class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE) # service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE) payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) context = models.TextField(blank=True, null=True) -
How to combine boostrap paginator and select to filter a table?
I currently use paginator on a table. I want to add a select to filter the table but I do not manage how to navigate through pages without loosing my selection currentlty (see code below) when I navigate by clicking on previous or next, option selected by used is lost and all data are presented I must change the 'else' condition to take account the option selected I was thinking about using global variable to store option selected in a variable but it can have side-effect and it is not so recommanded... views.py @login_required def index(request): # data sent (click on 'search' button or option selected) if request.POST: # data from select selection = request.POST.get('selection', False) # data from search ide = request.POST.get('ide', False) # search if ide == "": paginator = Paginator(Preinclusion.objects.all(), 5) preincluded = paginator.page(1) else: paginator = Paginator(Preinclusion.objects.filter(pat_num__startswith = ide),5) preincluded = paginator.page(1) # select if selection == 'Randomized': print('Randomized') paginator = Paginator([patient for patient in Preinclusion.objects.all() if patient.is_randomized], 5) preincluded = paginator.page(1) elif selection == 'Not randomized': print('Not randomized') paginator = Paginator([patient for patient in Preinclusion.objects.all() if not patient.is_randomized], 5) preincluded = paginator.page(1) elif selection == 'All patients': print('All patients') paginator = Paginator(Preinclusion.objects.all(), 5) preincluded = … -
Object of type QuerySet is not JSON serializable Django
When I am trying to send values in JsonResponse then The error is coming(object of type QuerySet is not JSON serializable ) def ajaxAgent(request): data = CommCenter.objects.values() responseData = { 'status': 'success', 'msg' : data} return JsonResponse(responseData) -
Override attribute of an abstract ModelField in django
I'd like to add an unique=True attribute to content_meta from Notification abstract model in EmailNotification, is there any way to do this without redeclaring the variable in the child model? class Notification(BaseModel): content_meta = models.CharField(max_length=3, unique=True) content_template = models.TextField() class Meta: abstract = True class EmailNotification(Notification): MISSING_TRANSACTION_ASSOCIATIONS = 'MTA' NON_ASSIGNED = 'N/A' META_CHOICES = ( (MISSING_TRANSACTION_ASSOCIATIONS, _('Missing transaction associations')), (NON_ASSIGNED, _('Non assigned')) ) content_meta = models.CharField(max_length=3, choices=META_CHOICES, default=NON_ASSIGNED, unique=True) def __str__(self): return self.content_meta -
No module named 'LoginForm.LoginForm'
I am creating a Django application and I am facing this issue can you please help me solve it.. Here is the error : Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 336, in run_from_argv connections.close_all() File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 219, in close_all for alias in self: File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 213, in iter return iter(self.databases) File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 147, in databases self._databases = settings.DATABASES File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf__init__.py", line 79, in getattr self._setup(name) File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf__init__.py", line 157, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\vaidehi.shejwalkar\AppData\Local\Programs\Python\Python38-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 973, … -
How to start google app engine on sympy-gamma
hello everyone, i am using windows-10 and i am completed all the process given by sympy-gamma document https://github.com/sympy/sympy_gamma/ . but at the end when i am configuration file for App Engine (needed to run the development web server): $ python deploy.py --generate-only --generate-test 1000 this given me output like. and run development web server and run this code will give me error: $ ../google_appengine/dev_appserver.py . error :- Error like this -
Django + JQuery - Append bars to table rows
I have table rows that look like this: {% for item in items %} <tr id="rows"></tr> {% endfor %} and bars that look like this: {% for item in items %} <div class='bar' id="bars"></div> {% endfor %} now I want to attach each bar to it's row, the first bar to the first row and so on... For a start, I tried using fragments but I haven't been successful yet... iBars = document.getElementById('bars'); var fragment = document.createDocumentFragment(); fragment.appendChild(iBars); rows = document.querySelectorAll('#rows').forEach(function (element, index) { rows.appendChild(fragment); }); Thank you for any help -
HOW TO ADD ONE MORE COLUMN IN django.contrib.auth.models from User in django rest framework
Actually i tried to authenticate my django project using JWT django.contrib.auth.models from User model and need to add one more column in user model but i cannot able to add one column don't no why? -
How to configure domain-based database filters?
Odoo has an option --dbfilter which selects database depending on domain, so the users can run different Odoo databases on different sub-domains. Let's say we have two subdomains: test1.example.com and test2.example.com. With simple configuration, Odoo can connect to test1 or test2 database. It is possible to handle it easily in Django? -
How to check this start_date>check_date in django ORM filter?
How to check this start_date>check_date in django ORM filter? check_date = request.GET.get('start_date') qs = AuditPlanning.objects.values('audit_opinion').annotate( count=Count('audit_opinion'), dcount=Count('audit_id', distinct=True)).filter(start_date__gte='check_date').order_by("count") here how can I check thestart_date with check_date. This method is not workingfilter(start_date__gte='check_date') filter(start_date__gte=check_date) also not working -
Running multiple celery instances in Production in same VM different virtual-envs
There have been similar questions. I have been running multiple production applications with Django Celery RabbitMQ, and so far so good. However now there's a customer on whose virtual machine we need to run three separate Django applications, and each of them has a Celery app. While running Celery as a stand-alone I had followed these docs. And they work like a charm. I am talking of /etc/init.d/celeryd option. The problem is the init.d scripts point to a script /etc/default and there is only one option to add a directory and other settings to point the right Django app. https://docs.celeryproject.org/en/latest/userguide/daemonizing.html#example-configuration However I am yet to see any docs, and what configs I will need to change if in the same VM, and for the same Rabbit-MQ Server we will need to make changes. In short, how do I run multiple Django Apps with celery and Rabbit MQ in a single machine. Apps are using different python VMs -
How to delay not exist task by celery?
I have two environments 1. webserver 2. celery worker webserver add jobs to celery message queue. but those env are separated, so can not import task function. how to call not exist task explicitly? ex) [X] task.delay() [O] add_jobs("task", *args) -
model forms were not generated automatically using django model forms
I'm creating Django forms using model forms because u I wanted the forms to be created automatically, but when I created this code the forms do not appear in the index.html page models.py from django.db import models class BaseCase(models.Model): base_case_name = models.CharField(primary_key=True, max_length=255) version = models.TextField(blank=True, null=True) default = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = 'base_case' forms.py from django import forms from SFP.models import * class BaseCaseForm(forms.ModelForm): class Meta : model = BaseCase fields='__all__' views.py from django.shortcuts import render,redirect from .models import * from .forms import * def addbc(self, request): bcform=BaseCaseForm(request.POST) bcform.save() basecasename = bcform.cleaned_data['post'] version = bcform.cleaned_data['post'] default = bcform.cleaned_data['post'] bcform = BaseCaseForm() return redirect('index.html') args = {'bcform':bcform, 'basecasename': basecasename, 'version': version, 'default' :default} return render(request, 'index.html', args) index.html <!DOCTYPE html> <html> <head> <title>S&FP</title> </head> <body> <h1>Forms</h1> {% csrf_token %} {{ bcform }} <input type="submit" value="add"> </body> </html> I was expecting the form fields to be generated automatically but they don't appear! -
run sympy-gamma on localhost on windows 10
I am new to sympy and python. i have download sympy code from github and run on local-host. code can be run on localhost server. it can be display error. can any one help me? how to run that code on localhost. -
Why tasks do not start?
I write this celery worker -A proj -c 2 -l info And get following log: -------------- celery@proj v4.3.0 (rhubarb) --- * *** * -- Linux-4.15.0-66-generic-x86_64-with-Ubuntu-18.04-bionic 2019-11-07 10:19:11 - ** ---------- [config] - ** ---------- .> app: proj:0x7f1ed0b36b70 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: redis://localhost:6379/0 - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . app.tasks.one . app.tasks.two [2019-11-07 10:19:11,968: INFO/MainProcess] Connected to redis://localhost:6379/0 [2019-11-07 10:19:11,978: INFO/MainProcess] mingle: searching for neighbors [2019-11-07 10:19:12,983: INFO/MainProcess] mingle: all alone [2019-11-07 10:19:12,990: INFO/MainProcess] celery@proj ready. nginx, redis and gunicorn are runned. Django 2.2.6, celery 4.3.0 -
Customuser model doesn't return username
I have a customuser model with class customuser(AbstractUser): # additional fields def __str__(self): return self.username I have another model, that becomes the foreign key for this model class bfs_support_ticket_model(models.Model): ticket_created_by = models.ForeignKey(customuser, on_delete = models.CASCADE) Why doesn't Django renders username for the form, but render or returns username everywhere correctly class ticket_edit_form(ticket_create_form): # ticket_created_by = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'readonly' : True})) # does not work in this way def __init__(self, *args, **kwargs): super(ticket_edit_form,self).__init__(*args, **kwargs) # self.fields['ticket_created_by'].disabled = True self.fields['ticket_created_by'].widget = forms.TextInput(attrs={'class' : 'form-control', 'readonly' : True}) # doesnot work in this way too class Meta: model=bfs_support_ticket_model exclude=['ticket_last_updated_by'] When the form is rendered it just prints the customuser.id instead of customuser.username But when no form initialization is made, it return the customuser.username correctly i.e. when class ticket_edit_form(ticket_create_form): def __init__(self, *args, **kwargs): super(ticket_edit_form,self).__init__(*args, **kwargs) self.fields['ticket_created_by'].disabled = True # only this line present it renders customuser.username class Meta: model=bfs_support_ticket_model exclude=['ticket_last_updated_by'] Please help me, where I am going wrong -
pgAdmin4 is not launching fails after some loading?
I just installed postgresql in my windows 10 but it is not opening.It says Starting pgAdmin4 server.. for some time but disappears after sometime without any error or notification. -
How would i replicate this SQL query in Django Rest Framework using generics.ListAPIView and serializers.ModelSerializer
Cant actually find anything like what i am trying to do with wanting to use case statements and left joins using DRF Django Rest Framework, yes this could be done on the front end of the project i am working on but id rather not have to let the front end potentially sending 100s of requests when loading a product list for example. Nothing i can really add to this but i have tried many different ways of doing the below SELECT p.itemno, CASE WHEN cp.price IS NULL THEN p.HighSell ELSE cp.price END AS price FROM api_product AS p LEFT JOIN api_customerprices AS cp ON p.itemno = cp.itemno AND cp.customerno = 'Examplecust' WHERE p.FreeStock > 0 or restockDate > '1900-01-01' -
How do I remove 404 error from Django app?
I am trying to create a web app using Django framework. I followed the tutorial and did everything as per the tutorial. DJANGO_PROJECT: from django.contrib import admin from django.urls import include from django.conf.urls import url urlpatterns = [ url(r'^dellserver/', include('dellserver.urls')), url(r'^admin/', admin.site.urls), ] Settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dellserver' ] dellserver\urls.py: from . import views from django.conf.urls import url urlpatterns = [ url(r'^dellserver/$', views.index, name="index") ] views.py: from . import views from django.conf.urls import url urlpatterns = [ url(r'^dellserver/$', views.index, name="index") ] Can anybody tell me what I am doing wrong? Why I a getting the ** Page not found (404) ** -
How to update exisiting date field in django using existing days field?
I want to update existing date field in django using existing days field in the same table. For example class Sample(models.Model): notify_status = models.BooleanField(default=0) next_date = models.DateField(blank=True, null=True) days = models.IntegerField(blank=True, null=True) Now I want to update days to next_date where next_date is less than todays date. I have tried this: import datetime from django.db.models import F Sample.objects.filter(next_date__lt=today).update(next_date=F('next_date')+datetime.timedelta(days=F('days'))) But its not working. -
DRF, Permissions and Tests: Receiving a 403 running tests, 200 OK in browser
I'm continuing my journey of testing my Django Rest Framework application as I add new views and more functionality. I must admit, at this stage, I'm finding testing harder than actually coding and building my app. I feel that there are far fewer resources on testing DRF available than there are resources talking about building a REST framework with DRF. C'est la vie, though, I soldier on. My issue that I'm currently facing is that I'm receiving a 403 error when testing one of my DRF ViewSets. I can confirm that the view, and its permissions work fine when using the browser or a regular python script to access the endpoint. Let's start with the model that is used in my ViewSet class QuizTracking(models.Model): case_attempt = models.ForeignKey(CaseAttempt, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) Of note here is that there is a FK to a user. This is used when determining permissions. Here is my test function. I have not included code for the entire class for the sake of brevity. def test_question_retrieve(self): """ Check that quiz tracking/ID returns a 200 OK and the content is correct """ jim = User(username='jimmy', password='monkey123', email='jimmy@jim.com') jim.save() quiz_tracking … -
Django 2: how to run code once on app initialization?
Using Django 2.2, how can I run code once after the code has been loaded but before any request is handled? (Similar to code executed in Rails initializers). The use case is the following: I'd like to create a pool of connections to a database and assign it to a global variable in a module but preferably not during module import. (Initially following: https://stackoverflow.com/a/1117692/3837660, I was doing it at module import. But this is not optimal. Partly because I am facing a double import issue which I haven't solved yet and partly because I'd like to avoid creating a pool of connections at module import time.) It should be done exactly once (no matter if that module happens to be imported twice) but at the application start (not on the first request).