Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Client secret not found in docker
I am using the google calendar API in my django project. I have two calendars connected which was working fine until i tried to run my project in a docker container. Now the client_secret.json files are not found anymore even though they are still in the same folder and practically nothing has changed. The error is this: Exception Value: ('Error opening file', 'client_secret.json', 'No such file or directory', 2) So my question is: what am i missing? -
Annotation of root parent on django recursive model
I have a recursive model Case (model has a self reference called parent), and I want to annotate a queryset Cases with the root parent. So if I have a root A with child B which has a child C, i want the queryset containing all three to have a reference to A. I have created sql that accomplished this for a single Case, but I cannot grasp how to annotate a queryset with it. I am experimenting with a subclass of django.db.models.Func, but can't make it work. Model: class Case(CoreModel): ... fields ... parent = ForeignKey( 'Case', verbose_name=ugettext_lazy("Parent case"), null=True, blank=True, on_delete=models.SET_NULL, ) SQL query that works: query = ''' WITH RECURSIVE Ancestors AS ( SELECT id, parent_id FROM core_case m where id = %(expressions)s UNION ALL SELECT m.id, m.parent_id FROM Ancestors JOIN core_case m on m.id=Ancestors.parent_id ) SELECT id, parent_id FROM Ancestors WHERE parent_id IS NULL ''' current attempt at a Func subclass: class RootCase(Func): template = query def __init__(self, *expressions): super(RootCase, self).__init__(*expressions, output_field = IntegerField()) When testing this cases = ( Case .objects .filter(customer__company=514) .annotate(root=RootCase(7401)) ) It fails: django.db.utils.ProgrammingError: syntax error at or near "WITH" -
how to compare Hierarchical foreign key in Django?
I have three model Subject, Examiner and Session in Django model and I want to filter those objects that are the same course_id with last Sessional object and Examiner. class Subject(models.Model): course_no = models.CharField(max_length=20) title = models.CharField(max_length=200) year = models.CharField(max_length=100,choices=T_Year) # 'title': Textarea(attrs={'cols': 80, 'rows': 20}), semester = models.CharField(max_length=100,choices=T_Semester) def __str__(self): return self.course_no class Examiner(models.Model): year = models.CharField(max_length=100,choices=T_Year) semester = models.CharField(max_length=100,choices=T_Semester) NamAdd = models.ForeignKey(Teacher, on_delete=models.CASCADE) course_no = models.ForeignKey(Subject, on_delete=models.CASCADE) noOfScripts = models.IntegerField() portion = models.CharField(max_length=50,choices=PORTIONS) examtype = models.CharField(max_length=30,choices=EXAMTYPE) examyear = models.CharField(max_length=30,choices=EXAMYEAR) def __str__(self): return self.NamAdd.Name + " " + self.year + " -> " +self.examyear class Sessional(models.Model): year = models.CharField(max_length=100,choices=T_Year) semester = models.CharField(max_length=100,choices=T_Semester) NamAdd = models.ForeignKey(Teacher, on_delete=models.CASCADE) course_no = models.ForeignKey(Subject, on_delete=models.CASCADE) noOfStudent = models.IntegerField() portion = models.CharField(max_length=50,choices=PORTIONS) examtype = models.CharField(max_length=30,choices=EXAMTYPE) examyear = models.CharField(max_length=30,choices=EXAMYEAR) def __str__(self): return unicode(self.course_no)+ " " +self.year how to create a filter query? I think it's look like this : obj = Sessional.objects.all().last Examiner.objects.filter(course_no= obj.course_no) but its always return 0(Zero) Object Please give me any hint... -
Why Django Rest Framework 404 after browsable API login?
when I try to login using the Rest Framework browsable API, I get a 404 after the login and the URL points to /accounts/profile. -
Django REST unit test TypeError: __init__() takes 1 positional argument but 2 were given
I'm launching the below code with the command $ python manage.py test, and it's returning the error: TypeError: __init__() takes 1 positional argument but 2 were given As far as i can see I'm only passing self to the init method, where is this additional arg coming from? I've checked multiple answers on here and looked at the django docs, but can't seem to find my error. What is causing this? Code: import requests import json from django.contrib.auth.models import User from django.test import TestCase from django.test import Client class BasicFunctionality(TestCase): def __init__(self): user_name = 'boris_the_blade' password = 'boris_the_sneaky_russian' self.client = Client() self.login_status = self.createUserAndLogin(user_name, password) def createUserAndLogin(self, user_name, password): self.user = User.objects.create_user(username=user_name, password=password) login = self.client.login(username=user_name, password=password) return login def test_login(self): self.assertTrue(self.login_status) Full terminal output: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/tompreston/.python_virtualenvs/lagoon-back-end-K1-2r-Ad/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/tompreston/.python_virtualenvs/lagoon-back-end-K1-2r-Ad/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/tompreston/.python_virtualenvs/lagoon-back-end-K1-2r-Ad/lib/python3.6/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv super().run_from_argv(argv) File "/home/tompreston/.python_virtualenvs/lagoon-back-end-K1-2r-Ad/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/tompreston/.python_virtualenvs/lagoon-back-end-K1-2r-Ad/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/tompreston/.python_virtualenvs/lagoon-back-end-K1-2r-Ad/lib/python3.6/site-packages/django/core/management/commands/test.py", line 56, in handle failures = test_runner.run_tests(test_labels) File "/home/tompreston/.python_virtualenvs/lagoon-back-end-K1-2r-Ad/lib/python3.6/site-packages/django/test/runner.py", line 603, in run_tests suite = self.build_suite(test_labels, extra_tests) File "/home/tompreston/.python_virtualenvs/lagoon-back-end-K1-2r-Ad/lib/python3.6/site-packages/django/test/runner.py", line 514, in … -
Django datetime.now() remains unchanged
I'm looking for set token authentification in order to download server files with secure way and add after an expiration time. Requirements : Django 1.11 Ubuntu 18.04 Database PostgreSQL Process : User fills a form with some informations CustomerForm(email, ...) and he has to choose one or several document(s) with checkboxes. When form is submitted, an email is sent with a generated token. This token has an expiration delay (1 minute in the first in order to make some tests). Issue : When user clicks on my link, it displays if token is in the list or not, datetime.now() and expiration_delay. But, if I click one more time on the link (maybe 30s after the first one), datetime.now() still remains as the first one. It should change. I suspect cookie to keep value inside, but I don't know if it's the right way. My files : I have a class in my view which let to fill the form, generate token and send the email. Then, I have this new class which let to compare token with database and compare expiration_time with now() too. class TokenDownloadView(TemplateView): template_name = 'freepub/token.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['token'] = self.kwargs['token'] token = … -
Django TestCase not destroying test data after tests finish running
I am currently trying to write my first Django specs for an application. However, everytime I run the tests I receive a IntegrityError: UNIQUE constraint failed: auth_user.username due to the user I created in the previous running of the test now existing in the database. I was under the impression that TestCase encloses the test code in a database transaction so that all data created during the test is rolled back on completion? What am I doing wrong here? from django.test import TestCase from django.contrib.auth.models import User from basic.models import SavedModels # Create your tests here. class SavedModelsTestCase(TestCase): User.objects.create(username="user_001", password="useruser", first_name="Test", last_name="User", email="test_user@test.com" ) user = User.objects.filter(username="user_001") saved_model = SavedModels.objects.create(name="Test Model", description="A model", user=user ) def test_saved_models(self): saved_model = create_saved_model() self.assertTrue(isinstance(saved_model, SavedModels)) self.assertEqual(saved_model.name, "Test Model") self.assertEqual(saved_model.description, "A model") self.assertEqual(saved_model.user, user) -
Django migrate returning 1064 - You have an error in your SQL syntax
I have 3 models - site, organization and institution defined as below. The problem is that when I run the migrations I get the following error: File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 42, in defaulterrorhandler raise errorvalue django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'None) NOT NULL, `site_uid` varchar(50) NOT NULL)' at line 1") site.py class Site(models.Model): STATUS = ( ('Active', 'Active'), ('Pending', 'Pending'), ('Incomplete', 'Incomplete') ) uid = models.CharField(primary_key=True, max_length=50, unique=True, editable=False) site_name = models.CharField(max_length=100, null=False, default='') country = models.CharField(max_length=100, null=False, default='') postcode = models.CharField(max_length=20, null=False, default='') full_address = models.TextField(max_length=200, null=False, default='') status = models.CharField(max_length=20, choices=STATUS, default='Pending') created_on = models.DateTimeField(default=date.today) def __str__(self): return self.site_name organization.py class Organization(models.Model): STATUS = ( ('Active', 'Active'), ('Pending', 'Pending'), ('Incomplete', 'Incomplete') ) uid = models.CharField(primary_key=True, max_length=50, unique=True, editable=False, default=uuid.uuid4) organization_name = models.CharField(max_length=100, null=False, default='') country = models.CharField(max_length=100, null=False, default='') postcode = models.CharField(max_length=20, null=False, default='') full_address = models.TextField(max_length=50, null=True, blank=True) status = models.CharField(max_length=20, choices=STATUS, default='Pending') created_on = models.DateTimeField(default=date.today) def __str__(self): return self.organization_name institution.py class Institution(models.Model): uid = models.CharField(primary_key=True, max_length=50, unique=True, editable=False, default=uuid.uuid4) organization_uid = models.ForeignKey(Organization, on_delete=models.CASCADE, editable=False) site_uid = models.ForeignKey(Site, on_delete=models.CASCADE, editable=False) def __str__(self): return self.uid Is there … -
Annotation to count and return zero when there is no relation
Given the following relation: class LicenseRequest: license_type = models.ForeignKey(LicenseType) created_at = models.DateField(default=now, editable=False) class LicenseType: name = models.CharField(max_length=100) value = models.CharField(max_length=3, unique=True) I want to count how many requests have been created for each license type. However, since I am generating a graphic, I must include 0 (zero) for license types without any license request in that specific period. I tried to do what was suggested here, but it did not work. qs = LicenseType.objects.filter( Q(licenserequest__created_at__range=(start_date, end_date)) | Q(licenserequest__isnull=True) ).annotate(rel_count=Count('licenserequest__id')) I cound find anonther way to achieve this goal, but I was wondering if I can do it through annotation. -
how can i authenticate logged in user in django generic views?
Hello to Stack Overflow community, I had created login and logout functions in django views.py hence i had successfully achieved login and logout methods also but i am confusing know that how can i pass data of this logged in user details to my class based views in views.py because i want to give access to my class based views only if user login happened views.py def admin_login(request): context = {} if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user: login(request, user) context['user'] = request.user return redirect('profile') else: context['error'] = 'Provide Valid Credentials' return render(request, "aapp/alogin.html", context) else: return render(request, "aapp/alogin.html", context) def admin_logout(request): logout(request) return redirect('alogin') i want to authenticate below view only if user logged in class index(TemplateView): template_name = 'aapp/index.html' -
django : url tag -> how to use a variable as url_name?
I have a django view which declare a target variable : target = "name_of_next_view_to_call" return render(request, template, locals() ) I want to use this target variable into my template, I tried the following : <form action="{% url '{{target}}' %}" method="post"> which gives me an error : Reverse for '{{target}}' not found. '{{target}}' is not a valid view function or pattern name. How to use the value of my "target" variable as the name of the url to be constructed ? From the doc I know it should be possible : The first argument is a URL pattern name. It can be a quoted literal or any other context variable. -
How do I extract a nested json value in my view template
I'm exploring graphql and it's driving me a bit bonkers. Here is my call to my endpoint... getMedications(value) { axios.post('http://localhost:8000/graphql', { query:`{ cat(name: "${value}"){ id carelogSet{ id medication{ name duration frequency dosageUnit dosageGuidelines notes } medicationDosageGiven medicationDosageUnit } } }` }).then(response => {console.log("getMedications: "); console.log(response.data.data.cat.carelogSet); this.catMedications = response.data.data.cat.carelogSet}) .catch(error => console.log(error)); }, My json response from my api like so.... "carelogSet": [ { "id": "4", "medication": { "name": "another med", "duration": "short", "frequency": "5", "dosageUnit": null, "dosageGuidelines": null, "notes": null }, "medicationDosageGiven": 2, "medicationDosageUnit": "ML" }, { "id": "1", "medication": null, "medicationDosageGiven": null, "medicationDosageUnit": null } ] In my view I have a standard "med in medications" <span>{{med.medication}}</span> when I look for "med.medication" I get this displayed... { "name": "another med", "duration": "short", "frequency": "5", "dosageUnit": null, "dosageGuidelines": null, "notes": null } If I do "med.medication.name" I get ... Nothing. Blank content will be displayed <-- this is the problem My question is, How do I get the value for just the "name"? What should "med.medication?????" become so that the value for "name" is displayed? -
Passing data from a django view to a template
I would like to display data from a view after a calculation to a template. The View collects data from a Django form and then performs a simple calculation. However, the function does not redirect to the template. views.py from . import forms from django.http import HttpResponseRedirect from django.shortcuts import render,redirect def index(request): form = forms.InputForm() return render(request, 'index.html', {'form': form}) def addition(a,b): c = a + b return c def input_form_Addition(request): if request.method == 'post': form = forms.InputForm(request.POST) if form.is_valid(): input1 = form.cleaned_data['input1'] input2 = form.cleaned_data['input2'] total = addition(input1,input2) return redirect('output.html', {'total': total}) else: form = forms.InputForm() The template (output.html) looks like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Forms</title> </head> <body> <p>The Sum is {{ total }}</p> </body> </html> My url routing is as follows: from django.urls import path from .views import index from simple_addition import views urlpatterns = [ path('', views.index, name='index'), path('output/', views.input_form_Addition, name='output') ] My Django form displays the form. Please Help. Thanks in advance. -
my django registration form doesn´t validate the data
def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid() is True: form.save() #log the user in return redirect('/account') else: form = UserCreationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) I was following a tutorial and couldn´t find a solution on the web. This is the code at my views.py. The problem is if i try to log in it seems that it doesnt think the data is valid an i don´t know why. -
Django form.ModelMultipleChoiceField label needed for each checkbox generated
please I want the name given to each generated checkbox(in the html) to have different names base on the "title" field in the Category Model. The html output is giving the same label(name) to each checkbox produced. Here is my forms.py class ProductFilterForm(forms.Form): category_id = forms.ModelMultipleChoiceField( label='Categories', queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) as you can see, this html is generated. but i want each to have the name base on category title. "Category object is displayed but that is not what I want" </label> <div class="controls "> <label class="checkbox"> <input type="checkbox" name="category_id" id="id_category_id_1" value="1" >Category object </label> <label class="checkbox"> <input type="checkbox" name="category_id" id="id_category_id_2" value="2" >Category object </label> <label class="checkbox"> <input type="checkbox" name="category_id" id="id_category_id_3" value="3" >Category object </label> <label class="checkbox"> <input type="checkbox" name="category_id" id="id_category_id_4" value="4" >Category object </label> </div> </div> <div id="div_id_max_price" class="form-group"> <label for="id_max_price" class="control-label "> This is the model.py class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=20) active = models.BooleanField(default=True) categories = models.ManyToManyField('Category', blank=True) default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True) def __unicode__(self): return self.title Please this is the output Categories </label> <div class="controls "> <label class="checkbox"> <input type="checkbox" name="category_id" id="id_category_id_1" value="1" >Category object </label> <label class="checkbox"> <input type="checkbox" name="category_id" id="id_category_id_2" value="2" >Category object </label> <label class="checkbox"> … -
KEyError when use request.data and request.FILES?
I want to upload Image to my database.I can do it By USing ModelSerializer.No problem But If i wanna pass using serializers.Serializer so my serializers.py looks like this: class QuestionSerializer(serializers.Serializer): image = serializers.ImageField() name = serializers.CharField(max_length=120) And my models.py looks like this class UploadedImage(models.Model): image = models.ImageField("Uploaded image", upload_to=scramble_uploaded_filename) name = models.CharField(max_length=120) and views.py : class UploadedImagesViewSet(viewsets.ModelViewSet): queryset = UploadedImage.objects.all() serializer_class = QuestionSerializer def create(self,request): serializer1 = self.get_serializer(data=request.data) serializer.is_valid() data = serializer1.data print(data) img,iss = UploadedImage.objects.get_or_create(name=data['name'],defaults={'image':files['image']}) return Response("UploadedImage") In views.py when i do data=request.data it SHows keyError in image When i do data=request.FILES it shows KeyErrorIn name How can i fix this error ??How can i upload image and save name in database?? Sorry For My english Hope U will Understand my Question. -
How to use ckeditor plugin for non admin app templates in django
I want to use the ckeditor in non admin template's text area .How can i do it? -
Django use 'python manage.py' runserver instead Gunicorn
I have a django project hosted on an amazon ec2 linux instance. For run my app also when section is close i use gunicorn but i experience some errors and degradation in perfonrmances. When i run command: python manage.py runserver from terminal all works great but when section is close app does not work. How can i run command "python manage.py runserver" for work forever (until i'll kill it) in background also in case of closed session? I know there is uWSGI but i prefer if possible use directly django native command. Thanks in advance -
Django subquery using or (Q) prefer one option over the other?
Is it possible to prefer a result in an or query using Django? I have a subquery which im using Q to get some values, however I want to prefer one value over the other if available. in my below sample, I want to prefer subnet__mgmt_prefer True if it is avialble, if it is not then use the subnet__subnet_type__mgmt True. is this possible? mgmt_ip = Subquery( DeviceCircuitSubnets.objects.filter(Q(subnet__mgmt_prefer=True) | Q(subnet__subnet_type__mgmt=True), device_id=OuterRef('id')).values('subnet__subnet')[:1] ) site_id = Subquery( Site.objects.filter(id=OuterRef( 'site_id')).values('id')[:1] ) site_name = Subquery( Site.objects.filter(id=OuterRef( 'site_id')).values('location')[:1] ) # query devices = Device.objects.filter(model__vendor__vendor='A10').annotate( mgmt_ip=mgmt_ip, site_id=site_id, site_name=site_name ) -
Smooth session migration to PickleSerializer
We need to deploy a new version in which the session serializer is changed from the default to PickleSerializer. We afraid that our connected users will experience exception before of the session change. Is that the case? is there any way to do the deployment with a smooth transition? Thanks -
How to change password for Django Social auth loggedin Google+ user and facebook user?
I am using social-auth in my app. I want to provide a functionality for google+ and facebook loggedin users to change their password using django change password form but for google+ and facebook user current password is not available to change it so please anyone can help me with it. Thanks in advance -
django-simple-history save_without_historical_record is not working
The following is my django model Banner: class Banner(models.Model): id = models.AutoField(primary_key=True) description = tinymce_models.HTMLField() created_time = models.DateTimeField(auto_now=True) modified_time = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=False) history = HistoricalRecords() def save_without_historical_record(self, *args, **kwargs): self.skip_history_when_saving = True try: ret = self.save(*args, **kwargs) finally: del self.skip_history_when_saving return ret class Meta: db_table = 'banners' managed = False Nose test case which access the above model: import unittest from tests import factory as f class BannerTest(unittest.TestCase): def test_insert_to_banner(self): """ Banner test insert """ f.banners(description="sample banner123").save_without_historical_record() factory : def banners(**kwargs): print kwargs return _create_default_model_instance(test_app.Banner, **kwargs) When this test case is executed, it is not saving without historical record, as it is expecting a User instance. ValueError: Cannot assign "<django.utils.functional.SimpleLazyObject object at 0x7fc74dce5dd0>": "HistoricalBanner.history_user" must be a "User" instance. Not sure about what to be done. -
Exceptions not caught by sentry for django project
Following the Sentry Django guide I've setup my project and deployed it. So I configure RAVEN_CONFIG with the SENTRY_DSN value and release values, and include raven.contrib.django.raven_compat in my INSTALLED_APPS. I've confirmed that with this configuration the following command will properly generate a message in sentry. python manage.py raven test However, I've created a django view to raise an exception as an alternative way to confirm that sentry is working, and when I hit this view, I get a 500 response, but nothing shows up in sentry. My expectation is that any exception (including 500 errors) that occurs in django will be sent to sentry. Do I need to configure something else? I am using the LOGGING setting of django, but at the moment I don't care if these messages 'error' or otherwise are sent to sentry. My main goal at the moment is to catch and send any exception that occurs to sentry. -
Django - Share a selected object model in many apps
I'm working on a webinterface to manage (crud) point cloud and 3d scanning work. To avoid to mention on which project i m working on, i would like to use something like a cookie that says i m working on object C26 from object B5 from A5. I want to display on which object i m working on an automatically feed form with the foreign key. I have 3 apps. app1 : select or create an object A app2 : based on object A (foreign key), i create an object B or select a B object if many are existing. app3 : based on object B (foreign key), i create C Concretely, App1, i create and manage (crud) a geolocation (geodjango object : point) App2, i create and manage (crud) a station (similar to geolocation) App3, i create and manage (crud) a scanning instance for pointcloud (pointclouds) Which is the best tool to do that and how to? signal middleware context url with parameter something else? https://github.com/jlstanus/ocm_django -
How can I decrease the memory usage of my web server which forks processes to run an executable?
I have a Django web server running on an AWS EC2 instance with 1GB of RAM. When a certain request is made to the web server, I need to run an executable using subprocess.call('./executable'). The executable runs a Perl script which does some file I/O and then some computations on the data parsed from the files, nothing too crazy. I began running into memory allocation issues which caused my web server to crash, so I messed around setting hard limits on the virtual memory allocated to each subprocess using ulimit -v some_value. I discovered that each subprocess requires around 100MB to run without erroring out, so it's no surprise that I'm running into memory issues with only 1GB of RAM. I'm wondering, though, why this memory usage is so high. Is a lot of extra memory being allocated because I'm calling subprocess.call from a process that's running a web server which is memory-intensive? Is running an executable that runs a Perl script necessarily memory intensive because Perl has some overhead or something? Would it use much less memory if the Perl script were re-written in Python and run directly in the Django web server? Would greatly appreciate any and all …