Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my local python server don't know my static css file to run
i inserted a css file to my django project (in 'static' directory) and set address of this css to my index.html file (in 'template' directory) according to django dacumentation but my css dosn't work! this is my addresses: myproject/myapp/templates/html/index.html myproject/myapp/static/css/index.css this is my html: {% load static %} <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head lang="eng"> <link rel="stylesheet" type="text/css" href={% static "myapp/index.css" %}/> </head> <body onload="myFunction()"> ----some code---- </body> </html> this is my setting.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') but my css dosn't work! please help me to run myproject completely -
Any tool to create graphs from data of a tree?
is there any simply and easy to use tool for Django (or for python) which is going to create a nice graphicon from the datas of a tree? Of course i can format the datas in any way, i just need a program which can process it and create a graphicon for it, like: https://en.wikipedia.org/wiki/Tree_(data_structure)#/media/File:Binary_tree.svg . It' s only a tree, no circle inside. Actually i' m using django-treenode . Thanks for any tip, idea. -
Is there a way i can submit my a registration form and show the flash message?
im creating a registeration form in django and i want to submit the form and redirect me to the home page with the flash message. i have created the register view and the form and set the flash message as well. views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') base.html <div class="col-md-8"> <!--for flash message--> {% if messages %} {% for message in messages %} <div class="alert alert-{{message.tags}}"> {{ message }} </div> {% endfor %} {% endif %} {% block content %}{% endblock %} </div> i expect it to submit the form and register a user and redirect me to the home page and show the flash message as well -
elastic-Search Aggregation [python]
I indexed the post and community models, post = Index('posts') post.settings( number_of_shards=1, number_of_replicas=0 ) @post.doc_type class PostDocument(DocType): community = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'description': fields.TextField(), 'name': fields.StringField(), }) I want to search posts and aggregate the communities (returns communities of the posts in the result) I may need to use aggregation, I had difficulties while implementing it, the documentation was not clear for me. q = Q("multi_match", query=query, fields=['title', 'content']) document.query(q) document.aggs.bucket('per_tag', 'terms', field='community') -
Celery django tasks ModuleNotFoundError
I am running into a strange ModuleNotFoundError. I am making a docker-compose network where tasks are shared between containers by a shared volume. the volume looks like this: celery_use │ celery_config.py │ tasks.py │ __init__.py # celery_config.py import os from celery import Celery app = Celery(include=('celery_use.tasks',)) # tasks.py from celery.utils.log import get_task_logger from .celery_config import app import os logger = get_task_logger(__name__) @app.task(bind=True, name='process_availability', queue='availability') def process_availability(self, message): print(os.getcwd()) print(os.listdir()) from avail.models import AvailabilityConfirmation my docker-compose file looks like this: version: '3.3' services: pas-gateway: build: context: ./ dockerfile: Dockerfile.pas command: bash -c "python appserver.py" environment: &env - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672 depends_on: - rabbitmq ports: - 18000:8000 restart: 'no' volumes: - ./pas_gateway:/pas_gateway - ./celery_use:/pas_gateway/celery_use/ django: build: context: ./ dockerfile: Dockerfile.django command: python manage.py runserver 0.0.0.0:8001 ports: - 18001:8001 environment: *env depends_on: - rabbitmq - postgres volumes: - ./ops_interface:/code django-celery: build: context: ./ dockerfile: Dockerfile.django command: bash -c "celery worker --app=celery_use.celery_config:app --concurrency=20 --queues=availability --loglevel=INFO" environment: *env depends_on: - rabbitmq - postgres volumes: - ./ops_interface:/code - ./celery_use:/code/project/celery_use postgres: image: postgres ports: - "15432:5432" volumes: - postgres-data:/var/lib/postgresql/data rabbitmq: image: rabbitmq:3.7.8 volumes: postgres-data: Dockerfile.django looks like this FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY ./requirements.txt /code/ RUN pip install -r requirements.txt COPY ./ops_interface/ /code/ … -
Django Rest Framework save to a model with an ImageField
I have the following model: class ProgressImage(TimeStampedModel): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='progressimages') image = models.ImageField( upload_to=obfuscate_filename, storage=storage, null=True) This is the serializer class: class ProgressImageSerializer(serializers.ModelSerializer): class Meta: model = ProgressImage fields = ('image', 'created') And this is the view set class: class ProgressImageViewSet(viewsets.ModelViewSet): serializer_class = ProgressImageSerializer queryset = ProgressImage.objects.all() filter_backends = (IsOwnerFilterBackend,) http_method_names = ['get', 'post'] permission_classes = (IsAuthenticated,) def perform_create(self, serializer): serializer.save(user=self.request.user) What I don't understand is how to perform the image save. Probably somewhere in the view set, but I don't know how. Anyone knows? -
DRF: Do not expost API
I am using Django with Django Rest Framework. I have disabled the browseable api in the settings.py file, however, when I visit http://mysite.api I get this response: {"api/projects":"http://example.com/api/projects/"} I don't want it to print that, it shouldn't print anything. I didn't define that endpoint. How can I tell DRF not to expose any information about my API unless I specifically tell it to? REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } -
How to run nodejs server as a background task in jenkins and restart the server on autobuild?
I'm currently working on nodejs application. I need to make frequent changes to it. I have a job set up in jenkins which automatically builds if changes are made. The job runs django and node api concurrently as background tasks but severs do not restart after autobuild. I've tried using nohup , forever start and pm2 start. commands used - nohup python3 manage.py runserver ...:**** & pm2 start app.js How to run django and nodejs servers as background tasks in jenkins and automatically restart if changes are pushed? -
Django build efficiency with API
I have silly question about efficiency of django. I will build application based on templates and using API. Which option will be better? 1) 1 server, 1 django (template+djangorestframework in one running framework) 2) 1 server, 1 djangorestframework or flask api, 1 django template -
Save Django Form wizard data to three models with related fields
I am working on a project that requires use of form wizard to populate three related models. The first model has general data which has a OneToOneField relationship with the second model. The first model also has a moany to many relationship with the third model. In general, I am using 4 forms in the wizard. Here is the models definition models.py class Listing(models.Model): listing_type_choices = [('P', 'Property'), ('V', 'Vehicle'), ('B', 'Business/Service'), ('E', 'Events')] listing_title = models.CharField(max_length=255) listing_type = models.CharField(choices=listing_type_choices, max_length=1, default='P') status = models.BooleanField(default=False) featured = models.BooleanField(default=False) city = models.CharField(max_length=255, blank=True) location = PlainLocationField(based_fields=['city'], zoom=7, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expires_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True ) listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='list_owner' ) def __str__(self): return self.listing_title def get_image_filename(instance, filename): title = instance.listing.listing_title slug = slugify(title) return "listings_pics/%s-%s" % (slug, filename) class ListingImages(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) image_url = models.ImageField(upload_to=get_image_filename, verbose_name='Listing Images') main_image = models.BooleanField(default=False) class Meta: verbose_name_plural = "Listing Images" def __str__(self): return f'{self.listing.listing_title} Image' class Property(models.Model): sale_hire_choices = [('S', 'Sale'), ('R', 'Rent')] fully_furnished_choices = [('Y', 'Yes'), ('N', 'No')] listing = models.OneToOneField(Listing, on_delete=models.CASCADE) sub_category = models.ForeignKey(PropertySubCategory, on_delete=models.CASCADE) for_sale_rent = models.CharField(choices=sale_hire_choices, max_length=1, default=None) bedrooms = models.PositiveIntegerField(default=0) bathrooms = models.PositiveIntegerField(default=0) rooms = models.PositiveIntegerField(default=0) land_size … -
Replace Django Objects in a list with their corresponding id
i have a list of django objects a = [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>] Can I replace the objects with their id in ORM? What I need: a = [3,5,6] How can I do that? -
Exchanging token on localhost rather than using http://django-oauth-toolkit.herokuapp.com/consumer/exchange/ for the same
I am trying to integrate Oauth to security module, for that I am using django-oauth-toolkit. For during application registration I the tutorial says to put http://django-oauth-toolkit.herokuapp.com/consumer/exchange/ for exchanging authorization code with access token.But instead of using Heroku application provided in the tutorial I want to exchange the codes on a different port on LocalHost.I cant find the codes of the OAuth toolkit Playground or Heroku application to include it in a different program.Can Anybody Help?? P.S: I am a newbie in Django and missing something Obvious I guess. -
Django Rest Filefield saved under wrong URL
Simplyfied, I have a model with an attached Filefield: models.py def uploadpath(instance, filename): return os.path.join('uploads/record/', filename) class Measurement(models.Model): data = models.FileField(null=True, upload_to=uploadpath) with MEDIA_URL = '/media/' MEDIA_ROOT = '/vol/web/media' and the django rest serializer serializers.py class MeasurementDataSerializer(serializers.ModelSerializer): class Meta: model = Measurement fields = ('id', 'data',) read_only_fields = ('id',) If I upload a file, say data.dat, with with the browser and the djange rest interface, it correctly returns the url of data: "data": "http://localhost:8000/media/uploads/record/data.dat" However, sometimes I create a model manually in the shell: with NamedTemporaryFile() as tmp_file: filepath = "/vol/web/media/uploads/record/data.dat" some_measurement.data.save(filepath, tmp_file, save=True) and list all measurements in the browser, it returns the wrong URL: http://localhost:8000/media/vol/web/media/uploads/record/data.dat" How do I have to adjust the manual creation of the file, such that the correct url, in this case "data": "http://localhost:8000/media/uploads/record/data.dat" is returned? -
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 …