Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I redirect to mturk from an external application?
I have an otree App that redirects the user to another (on a second server) application and back to the otree app. This works great with consistent URLs (in otree its called "rooms") but when I connect it with mturk, this solution does not work because the URLs are not consistent (rooms don't work with mturk). So I cannot redirect from my second app back to otree/mturk. How can I redirect them back to mturk? Is it possible to save the URL from mturk where the users came from? -
Django Queryset: Prefetch with sliced main query
Using prefetch_related / Prefetch() in combination with a sliced / paginated main query The database contains 1 million rows a have to combine with other data with prefetch_related(). This works, but cause of the size the Query is aborted. So i try to slice the result. But Slicing looks not supported by Django 1.11. query=AAA.objects.all().prefetch_related(BBB.objects.all()) query[500000:501000] This code runs a query which gets 1000 rows from the database. This works, but in the related query, used by Prefetch, all 1 million AAA ids are included to retrieve BBB objects. This kills the database. Is there a solution the propagate the slicing into the Prefetch Query? -
How to get Response from Yahoo Server in django views
I am getting the response from server once I have typed curl -H "Authorization: Bearer " https://example.com/v1/user/me/profile?format=json in CLI of windows but how to get the response in views of django -
Excel is not starting using win32 on Django application running on Apache
I have a application build on Django 2.1.4. I have a piece of code which converts excel xlsx to PDF using win32 COM object. The problem is the same code works on QA environment which has same specification as PROD. Below code is not initiating the excel application because of which I'm not able to convert this workbook to PDF. It is returning a Excel Application but excel does not start. I have kept "xlApp.Visible = True".. xlApp = client.DispatchEx("Excel.Application") The above code works fine with IDLE environment and converts excel to PDF where as inside Django's view function it has a problem. I'm also using pythoncom.CoInitialize() inside View function. Tried running it on IDLE and it works fine.. It has a problem inside Django application print("PDF Required") pythoncom.CoInitialize() xlApp = client.DispatchEx("Excel.Application") #xlApp = client.gencache.EnsureDispatch("Excel.Application") print("xlApp : ",xlApp) xlApp.Visible = False books = xlApp.Workbooks.Open(os.getcwd() + '\\' + directory_name + '\\' + directory_name + '.xlsx') print("Books : ",books) #ws = books.Worksheets[0] ws = books.Worksheets('CFS') ws.Visible = 1 print("Visible is 1") ws.ExportAsFixedFormat(0, os.getcwd() + '\\' + directory_name + '\\' + directory_name + '.pdf') print("Exported ") xlApp.Quit() Expected output is a PDF with the same name as xlsx file in the same directory -
How to adjangodd additional context to a django form widget
the basic Django CheckboxSelectMultiple widget allows for a label and value to be passed through to the template. I want to add 2 additional fields from a model but I cannot work out how, although I believe it is through subclassing get_context I have this model and I would like to include the icon and description in the widget class AddOnItem(models.Model): name = models.CharField( verbose_name = 'AddOn Title', max_length = 50 ) description = models.CharField( verbose_name = 'Description', max_length = 255 ) icon = models.FileField(upload_to="addon_icons/", blank=True, null=True) active = models.BooleanField(default=False) Within my form I've specified this widget class JobPostWizardForm1(forms.ModelForm): class Meta: model = Job fields = [ ..., 'addons' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ... self.fields['addons'].widget = AddOnCheckboxSelectMultiple() self.fields['addons'].queryset = AddOnItem.objects.filter(active=True) And I've subclassed the CheckboxSelectMultiple widget as class AddOnCheckboxSelectMultiple(forms.CheckboxSelectMultiple): template_name = 'jobboard/widgets/addon_checkbox_select.html' option_template_name = 'jobboard/widgets/addon_checkbox_option.html' def get_context(self, name, value, attrs): context = super().get_context(name, value,attrs) return context Obviously this doesn't do anything at the moment but I want to add something like context['icon'] = obj.icon but I cannot work out how to do this. That is, I do not follow how Django widgets are getting the object. I would greatly appreciate any help available - thanks -
python manage.py migrate on terminal then error show?
Traceback (most recent call last): File "manage.py", line 16, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Annotate and order_by causes duplicates
I'm filtering on a queryset in Django Rest Framework, and i cannot get rid of duplicates I'm querying on a Restautant model, which has a reverse foreign key to Booking Im making some aggregations on the Restaurant model based on the values from the related Booking model, and when grouping i get duplicates class Restaurant(models.Model): pass class Booking(models.Model): address = models.ForeignKey(Restaurant, null=True, on_delete=models.CASCADE) event_date = models.DateTimeField(null=True) Restaurants.objects.annotate(bookings_at_date=Count(Case( When(booking__event_date__date=value, then=1), output_field=IntegerField(), ))).order_by('bookings_at_date) -
use custom decorator to perform an API post call from a different endpoint python django
I have a different endpoint that has my user model and i need to validate a user and get the user info before a particular route or viewset class is processed. In my code, i did the following I added a file called main_app/ags/permissions.py from .apps import PriceAgsConfig import json import logging import requests def can_access_application(self, request, **kwargs): print("it comes here first") data = { 'username': 'admin', 'password': 'password' } r = requests.post(PRICE_ENGINE_URL,None, data, timeout=60) print(r.json()) return r.json() in my main_app/ags/views.py from django.db.models import Q from rest_framework import mixins, viewsets from rest_framework.response import Response from .permissions import can_access_application from .models import ( PriceRequest ) from .serializers import ( PriceRequestSerializer ) @can_access_application(request) class PriceRequestViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """Creates a price request. """ queryset = PriceRequest.objects.all() serializer_class = PriceRequestSerializer pagination_class = None def retrieve(self, request, pk=None): """Use `client_id` or `refno` as id. Prefer client_id. """ try: obj = self.get_queryset().get( Q(refno=pk) | Q(client_id=pk) ) serializer = self.get_serializer(obj) return Response(serializer.data) except Exception as e: return Response(str(e)) So basically, before i execute the PriceRequestViewSet, i want to call the can_access_application method in my permissions.py file. i want to be able to pass the data sent in my call to the can_access_application as well. e.g. my call … -
Best sequence when uploading large files to different cloud services
I am trying to upload large files (100+ Gb) to several cloud storage services from a Django app. I have written a first view to do this for S3 and it is working: class FilePolicyAPI(APIView): ... I have written these views for S3 multipart upload, my question is, should I write similar views for the other cloud services (Google Cloud Storage, Azure), or would it be best to implement a S3 lambda function that responds to the upload to the S3 bucket and replicates these files in the other cloud services? What would be less costly for my Web App? thanks -
How to create a function in views which can be called from templates, with or without arguments?
I have a function which displays the live location of a vehicle on demand. There are two functions and thus buttons, when clicked should run a code internally, and display the result on this same view/page. I am not able to understand how to create those two functions, without reloading my page or going to another page. I do not have to pass any kind of arguments in the function from the template, as of now. Is this possible in django?? Code Here is my function in my view.py @method_decorator([login_required, teacher_required], name='dispatch') class QuizResultsView(DetailView): model = Quiz context_object_name = 'quiz' template_name = 'classroom/teachers/quiz_results.html' tripId = str() def start_trip(self): quiz = self.get_object() lr_object = get_object_or_404(LR, lr_quiz=quiz.id) # ----------Call api to fetch location code -----------# My api fetch code will return a json object which I have to parse and enter the same in a Google Iframe, and it takes about 2-3 seconds to populate the iframe. I have many 'mini-functions' or whatever they are called in my same function, just like : def get_queryset (self): return self.request.user.quizzes.all() Hence, is there a way to create more functions just like these? Also, how will I call such functions from my templates? Is there … -
Django objects.create produces more output than it should
There are two lists: master_values: [{<Truckdb: Truckdb object (141)>: [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>]}, {<Truckdb: Truckdb object (18)>: [<ItemBatch: Iphone>]}] truck_objects: [<truck_name: 17 Feet 6000>, <truck_name: Tempo 407 1500>] When I run the following code it craetes more dispatchplan than it should: for i in range(len(truck_objects)): for j in range(len(master_values)): if i == j: for q, w in master_values[j].items(): for aa in range(len(w)): print("len(w) ",len(w)) DispatchPlan.objects.create(owner=request.user, truck_type=container_object, truck_name=truck_objects[i], items=w[aa]) In this it created 5 dispatch plans when it should have created only two -
cx_oracle installation beaking for version lesser than 6.0
I know the questions around this have already been asked and I tried most of the solutions on that. Perhaps, my python2.7 pip environment has cx-Oracle==5.2.1 installed and it was working ok and still, it is. python2.7 installs. cx-Oracle==5.2.1 Django==1.11.20 oracle 11g I created python3.7 pip environment and before that, I converted my python2.7 code python3.7. In my pip environment, I ran pip install requirements.txt and cx_oracle failed with the following traceback. Collecting cx-Oracle==5.2.1 Using cached https://files.pythonhosted.org/packages/95/7f/3b74fe3adeb5948187b760330cb7e9175e3484bd6defdfeb9b504d71b4b3/cx_Oracle-5.2.1.tar.gz Building wheels for collected packages: cx-Oracle Building wheel for cx-Oracle (setup.py) ... error ERROR: Complete output from command /Users/kishorpawar/.virtualenvs/rp3/bin/python3.7 -u -c 'import setuptools, tokenize;__file__='"'"'/private/var/folders/n0/9yxmvh4x2pj_g5b71w2tnx6m0000gn/T/pip-install-7c1s82of/cx-Oracle/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/n0/9yxmvh4x2pj_g5b71w2tnx6m0000gn/T/pip-wheel-crdxmnta --python-tag cp37: ERROR: running bdist_wheel running build running build_ext building 'cx_Oracle' extension creating build creating build/temp.macosx-10.14-x86_64-3.7-12c clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -I/Users/kishorpawar/oracle/instantclient/ -I/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c cx_Oracle.c -o build/temp.macosx-10.14-x86_64-3.7-12c/cx_Oracle.o -DBUILD_VERSION=5.2.1 cx_Oracle.c:10:10: fatal error: 'oci.h' file not found #include <oci.h> ^~~~~~~ 1 error generated. error: command 'clang' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for cx-Oracle Running setup.py clean for cx-Oracle Failed to build cx-Oracle Installing collected packages: cx-Oracle Running setup.py install for cx-Oracle ... error ERROR: Complete output from command … -
Not able to initialize the hidden fields in django
This is my view: def my_view(request): if request.method == 'GET': form = MyForm(initial={'user': "my_user"}) if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): print("form is valid") else: form = MyForm() return render(request, 'my_template.html', {'form': form}) And this is the form class MyForm(forms.Form): my_field = forms.CharField(max_length=100) user = forms.CharField(widget=forms.HiddenInput()) def clean(self): cleaned_data = super(MyForm, self).clean() my_field = cleaned_data.get('my_field') if not my_field: raise forms.ValidationError('error') Nothing is printed on the console (print("form is valid")), so the form is not valid, and this problem comes from the hidden field. When I work without the hidden fields, the form is valid What's wrong with my code ? How to initialize the values of hidden fields from the view function (or another way to do it without including it in the HTML) ? -
Conditionally display with Crispy Forms - error 'tuple' object has no attribute 'get'
I am trying to follow solution for this question: Conditionally display a Fieldset with Crispy Forms. However, I am not able to completed it due to error: Request Method: GET Request URL: http://127.0.0.1:8000/project/customer/ Django Version: 2.2.2 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' model.py: class Project(models.Model): project_name = models.CharField(max_length=50, primary_key=True) # who owns the project? owner = models.ForeignKey(User, on_delete=models.PROTECT) created_date = models.DateTimeField(auto_now=False, auto_now_add=True) is_active = models.BooleanField(default=True) ## when on call starts 5 pm? on_call_begings = models.TimeField(auto_now=False, auto_now_add=False, default=datetime.time(17, 00)) ## when on call ends 9 am? on_call_ends = models.TimeField(auto_now=False, auto_now_add=False, default=datetime.time(9, 00)) country = CountryField() follow_holidays = models.BooleanField(default=True) slug = models.SlugField() class Meta: verbose_name = "Project" verbose_name_plural = "Projects" def __str__(self): return self.project_name def get_absolute_url(self): return reverse("Project_detail", kwargs={"slug": self.slug}) Forms.py from django import forms from core.models import Project from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Field, Layout class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ("project_name", "is_active", "on_call_ends", "on_call_begings", 'country', 'follow_holidays') def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(args, kwargs) self.username = kwargs.pop('user', None) self.helper = FormHelper(self) self.helper.attrs = {'novalidate': ''} self.helper.layout = Layout( Fieldset("project_name", "is_active", "on_call_ends", "on_call_begings", 'country', 'follow_holidays') ) if self.username and self.username.is_staff: self.helper.layout.append(Fieldset( 'owner', ) ) The problem is there. When I remove … -
Having troubles in usage custom font in template on Heroku
I have a problem with using custom font on Heroku. In order to show Russian text correctly on generated pdf pages I use following custom font in my html: <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title>Boat pdf</title> <style type="text/css"> @font-face { font-family: Palatino Linotype; src: url({% static "fonts/Palatino.ttf" %}); } body { font-family: Palatino Linotype, Arial, sans-serif; color: #333333; } </style> </head> It works fine locally but after migration to Heroku whenever I am trying to generate pdf file based on the html I get an exception: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 420, in stored_name 2019-06-26T09:52:03.873127+00:00 app[web.1]: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) 2019-06-26T09:52:03.873128+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'fonts/Palatino.ttf' This is the only error I get related to staticfiles. All other static works fine. I have tried to manually run collectstatic one more time and even placed this font to staticfiles folder manually – no success. In production static assets are served by Whitenoize. Development setting related to static are: INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', STATIC_ROOT = os.path.join(BASE_DIR, "static") # new STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' production settings are: STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Question is how to serve this font on … -
How to adjust the zoom of website at different browser at different screen size?
I have deployed a website http://www.muskan-group.com/ it's zoom is fine at screen resolution 1920x1080. I want to zoom 80% at screen resolution 1366x768. I tried to set @media only screen and (min-width: 768px) { zoom: 80%; } It works fine in chrome but not working properly in internet explorer and microsoft edge. I have used meta tag for viewport. <meta name="viewport" content="width=device-width, initial-scale=0.6, maximum-scale=1, user-scalable=0"> I expect the output that at screen resolution 1366x768 the zoom of page is set to 80%. And it should be compatible with all browser. -
Access related fields through inline_formset
I am trying to view (not edit) related fields in an inline formset. In this case I want to display the item cost in the quantity formset. models.py class Item(models.Model): name = models.CharField(max_length=40) notes = models.CharField(max_length=200, blank=True) cost = models.DecimalField(default=0.00, max_digits=8, decimal_places=2, blank=True) class Quantity(models.Model): quantity = models.IntegerField(default=0) item = models.ForeignKey(Item, on_delete=models.CASCADE) forms.py class QuantityForm(ModelForm): def __init__(self, *args, **kwargs): super(QuantityForm, self).__init__(*args, **kwargs) class Meta: model = Quantity fields = ['id','item', 'quantity'] views.py QuantityFormSet = inlineformset_factory(Option, Quantity, form=QuantityForm, formset=QuantityInlineFormSet, extra=1) quantityForm = QuantityFormSet(instance=option) I imagine I have to do something like this. for form in quantityForm.forms: form.item_cost = form.fields['item'].selected.cost But I'm a little stuck. Surely doing this in forms.py is a better place? -
relation " " does not exist
I am creating a project in django using postgresql database. When I run my server the page returns the error relation "backtest_trade" does not exist LINE 1: INSERT INTO "backtest_trade" ("pos", "neg", "profit", "trans... when i try to save my model in the database using back.save(), where back is a variable of the model. I have registered the model in models.py of my app. I understand that there is no table being created in the database but my understanding is that admin.register should do it. I tried looking up but none of the questions asked was able to help me. from django.contrib import admin from django.db import models from django.contrib.postgres.fields import ArrayField # Create your models here. class trade(models.Model): pos = models.IntegerField(default = 0) neg = models.IntegerField(default = 0) profit = models.IntegerField(default = 0) transaction = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9,default= 0), default = list) investment = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9,default = 0), default = list) sell = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9, default = 0), default = list) entry_date = ArrayField(models.CharField(max_length = 20, default=''), default = list ) exit_date = ArrayField(models.CharField(max_length = 20, default = ''),default = list) name = models.CharField(max_length = 100, default = "hello") admin.site.register(trade) -
Django : Displaying ManyToManyField in admin page as a Table
I have the following two models. class Question(models.Model): id = models.AutoField(primary_key=True) question_body = models.TextField(blank=True) question_response = models.TextField(blank=True) def __str__(self): return self.question_body class SIGRound(models.Model): sig = models.CharField(max_length=9, choices=SIG_CHOICES) round_number = models.IntegerField(default=1) round_description = models.CharField(max_length=500) questions = models.ManyToManyField(Question) I want to use the SIGRound from the admin page and since it is a many to many field, many answers on StackOverflow suggested to use filter_horizontal or inline filter_horizontal does not give me what I want and with inline it looks like this: But I want to display this field as a table, similar to list_display in the normal admin page, how would I go about doing this? -
Connect mysql database with django
I am a begginer in django, i try to connect mysql database with django but when i write 'python manage.py migrate' in cmd i see this error: mysqlclient 1.3.13 or newer is required yo have 0.9.3 so i decide to upgrade mysql client using this command:pip install mysqlclient --upgrade and i get this output: [https://i.stack.imgur.com/bq7Jn.jpg][1] [https://i.stack.imgur.com/nYGSQ.jpg][2] [https://i.stack.imgur.com/u8wzN.jpg][3] How to fix it? -
Add multiple (but not all) tables to PostgreSQL publication if not added
I'm trying to set up publication on PostgreSQL 10 database for logical replication. The database is used for Django website and all tables are currently in one schema - public. I plan to keep database structure updated via Django migrations, so I need to exclude some tables from PostgreSQL publication, namely all that start with django. I can receive an entire list of tables that I need to replicate using query SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname='public' and tablename not like 'django%'; Tables are added to the publication using query ALTER PUBLICATION my_publication ADD TABLE table0, table1; How can I pipe output of my SELECT query to the above ALTER PUBLICATION query? It would also be great if tables that have already been added were skipped instead of breaking execution of the entire ALTER PUBLICATION query. At the moment I think I will have to use PL/pgSQL - SQL Procedural Language. But maybe there is a better/simpler way to edit publication with only queries? -
Datatable recommandation for django
I want to load millions of data from Django with search bars on each column to search all the database quickly on server-side. However, there is no datatable example for django with server-side and column search bar. I tried django-datatable-view and I can load the dataset with server-side. But I could not implement the column searchbar on the whole dataset. -
Django Rest Framework save multipart/form-data
I have the following model: class Exercise(TimeStampedModel): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='roms') # ... other fields recording = models.ManyToManyField(Recording) The Recording model contains, among other fields, a field called zip_file, which is a FileField. Since this is the first time I'm using DRF and my work is mostly frontend, unrelated to Django in general, I'm having difficulties understanding how to save an instance of a model like this. This is the ExerciseSerializer: class ExerciseSerializer(serializers.ModelSerializer): recording = RecordingSerializer() class Meta: model = Exercise fields = ('duration', 'recording', ...) This is the Recording model: class Recording(TimeStampedModel): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='recordings') sensors = models.ManyToManyField(Sensor) category = models.CharField( max_length=4, choices=( ... ), default=(...) data = JSONField(null=True, blank=True) zip_file = models.FileField( upload_to=upload_location, storage=storage, null=True) and this is the RecordingSerializer: class RecordingSerializer(serializers.ModelSerializer): sensors = SensorSerializer(many=True) class Meta: model = Recording fields = ('sensors', 'category', 'data', 'zip_file') If I understood right, I need to update this RecordingSerializer in order to save the zip_file field properly. Is that correct? Or I need to change something in the ExerciseSerializer? -
Adding JavaScript variable to Django static url
I am attempting to add a custom Javascript variable to my Django static url. Unfortunately, the below code is failing. $(document).ready(function() { var randomNum = Math.floor((Math.random() * 12) + 1) var text = "{% static '5LW/images/slider/" + randomNum + ".1.jpg %}" document.getElementById("headerImage").style.backgroundImage = url(text) }); I receive the error: -- Error during template rendering Could not parse the remainder: ''5LW/images/slider/"' from ''5LW/images/slider/"' var text = "{% static '5LW/images/slider/" + randomNum + ".1.jpg %}" -- How would I go about fixing this? -
'NoneType' object has no attribute 'email'
I am using rest-social-auth for my project and it returns jwt token. Now if I am going to create a user profile in Django admin everything is ok I select author fill some fields etc and profile is ready and it returns user email which was taken from social network. But in Postman when I test my api it works with jwt token auth but I do not know which user has create the profile. models.py class Profile(TimeModel): user = models.OneToOneField('user_accounts.CustomUser', related_name='profiles', null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) birthdate = models.DateTimeField(null=True) image = models.ImageField(upload_to='profile_images', null=True) def __str__(self): return self.user.email if I change __str__ method to return first_name it works but I do not know which user did it. But It returns email instead it gives me a error in admin like 'NoneType' object has no attribute 'email' serializers.py looks like this class ProfileSerializer(serializers.ModelSerializer): birthdate = serializers.DateTimeField(format='%Y-%m-%d') class Meta: model = Profile fields = ['first_name', 'last_name', 'birthdate', 'gender', 'image'] How can I solve this issue? pls any help would be appreciated