Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Lambda Appears to Execute on Declaration in Python 3.5
I just ran into a heck of a strange problem when we were deploying our application. Suddenly, serializers that were fully defined in dev were suddenly missing lookup fields after the code was deployed! Our deployments are in Python 3.5, while our local development environments are in Python 3.6.. Yes, I know, we're fixing that as we speak. It turned out that the following line: setattr(api_meta, 'serializer_copy', lambda serializer = api_meta.serializer: serializer_helpers.copy(serializer)) Was causing the issue, but only while running in python 3.5 The issue: I'll add some specifics: While api_meta is used, the serializer_copy attribute is never called. No issues occurred while running in a python 3.6 venv The issue immediately occurs when running in a python 3.5 venv, or while deployed Commenting this line prevents the issue from occurring Perhaps the strangest detail: Adding a breakpoint as such: import ipdb;ipdb.set_trace() setattr(api_meta, 'serializer_copy', lambda serializer = api_meta.serializer: serializer_helpers.copy(serializer)) And simply hitting c to continue without changing anything also fixed the issue. It was as though the PDB trace was preventing the bug, making this even harder to debug. I'm hoping someone will know something finicky about python lambdas in 3.5 v 3.6 that might cause this, but I understand … -
Uncaught ReferenceError: jQuery is not defined at jquery.livequery.js:226 When using Django Location Field
I'm using Django Location Field (django-location-field) tried it on a test project and it worked perfectly, when i installed it to new project with the same settings it throws these errors when i try to view the map from Admin page: Uncaught ReferenceError: jQuery is not defined at jquery.livequery.js:226 (anonymous) @ jquery.livequery.js:226 form.js:368 Uncaught ReferenceError: jQuery is not defined at form.js:368 (anonymous) @ form.js:368 tried collectstatic and even tried copying static files from pld project to new but still the same error any help?? -
How to transfer data/state between components where data is stored in an API
I'm looking for advice on getting a table to re-render after a successful POST (the table and form are on the same page). I have data that is being provided to a Table via an API (Django-Rest-Framework), so I don't want to have a callback that checks every second for new data since that would needlessly hammer my API. The relationship between the components are there is a DataProvider, which is the parent of the Table. The form is it's own component. What I think I need to do is have an onClick event on the form submit that will fetch from the API again, and re-render the table. I'm new to React, and have no idea how to actually do this and I haven't had much success googling around (or only finding examples that have a 1sec callback to update a clock or something). Here are the 4 files that are interacting: App.js import React from "react"; import ReactDOM from "react-dom"; import DataProvider from "./DataProvider"; import Table from "./Table"; import Form from "./Form"; class App extends React.Component { constructor(props) { super(props); }; } render() { return ( <React.Fragment> <DataProvider endpoint="/api/properties/" method="GET" render={(data) => <Table data={data} />} /> <Form endpoint="/api/properties/" … -
Django app on Heroku - Path Issue
I'm trying to configure my django app on Heroku for the first time. I've made it to the point of pushing my code to "heroku master", but I'm getting a ModuleNotFound error: $ git push heroku master Counting objects: 390, done. Delta compression using up to 4 threads. Compressing objects: 100% (251/251), done. Writing objects: 100% (390/390), 56.56 KiB | 2.83 MiB/s, done. Total 390 (delta 205), reused 262 (delta 122) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.4 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: Collecting django (from -r /tmp/build_9b6fcbcef79c70d29d429c430e653020/requirements.txt (line 1)) remote: Downloading Django-2.0.4-py3-none-any.whl (7.1MB) remote: Collecting psycopg2 (from -r /tmp/build_9b6fcbcef79c70d29d429c430e653020/requirements.txt (line 2)) remote: Downloading psycopg2-2.7.4-cp36-cp36m-manylinux1_x86_64.whl (2.7MB) remote: Collecting python-decouple (from -r /tmp/build_9b6fcbcef79c70d29d429c430e653020/requirements.txt (line 3)) remote: Downloading python-decouple-3.1.tar.gz remote: Collecting django-debug-toolbar (from -r /tmp/build_9b6fcbcef79c70d29d429c430e653020/requirements.txt (line 4)) remote: Downloading django_debug_toolbar-1.9.1-py2.py3-none-any.whl (206kB) remote: Collecting Pillow (from -r /tmp/build_9b6fcbcef79c70d29d429c430e653020/requirements.txt (line 5)) remote: Downloading Pillow-5.1.0-cp36-cp36m-manylinux1_x86_64.whl (2.0MB) remote: Collecting pytz (from django->-r /tmp/build_9b6fcbcef79c70d29d429c430e653020/requirements.txt (line 1)) remote: Downloading pytz-2018.4-py2.py3-none-any.whl (510kB) remote: Collecting sqlparse>=0.2.0 (from django-debug-toolbar->-r /tmp/build_9b6fcbcef79c70d29d429c430e653020/requirements.txt (line 4)) remote: Downloading sqlparse-0.2.4-py2.py3-none-any.whl remote: Installing collected packages: pytz, django, psycopg2, python-decouple, sqlparse, django-debug-toolbar, Pillow remote: Running setup.py install for python-decouple: started remote: … -
load XGBoost model in django framework
I´m trying to load an xgboost model from a FileField of a Django model entity. It is not working. def do(execution): dataFile = execution.dataFile np = genfromtxt(dataFile, delimiter=',') import xgboost as xgb bst = xgb.Booster({'nthread': 4}) # init model # bst.load_model('testModel.bin') "Working when used instead of following line" bst.load_model(execution.modelFile) data = xgb.DMatrix(np) preds = bst.predict(data) print(preds) I am getting this error: TypeError: memoryview: a bytes-like object is required, not 'FieldFile' Full trace: Traceback (most recent call last): File "/home/andrea/environments/new_env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/andrea/environments/new_env/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/andrea/environments/new_env/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/andrea/Documents/python/DataProject/DataProject/views.py", line 19, in run ModelService.do(e) File "/home/andrea/Documents/python/DataProject/executions/ModelService.py", line 10, in do bst.load_model(execution.modelFile) File "/home/andrea/environments/new_env/lib/python3.5/site-packages/xgboost/core.py", line 1106, in load_model ptr = (ctypes.c_char * len(buf)).from_buffer(buf) TypeError: memoryview: a bytes-like object is required, not 'FieldFile' Execution Model: class Execution(models.Model): title = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) dataFile = models.FileField(upload_to="dataset", null=True) modelFile = models.FileField(upload_to="model", null=True) def __str__(self): return self.title I am not sure how to proceed, a BinaryField, a Custom xgboost object field, or is there a simpler solution. Many thanks -
Django: Updating foreign_keys
in my project flow I first create a database entry in Orders. At this point, the foreign_key transaction_profile stays empty. At a later point in my checkout_page view, the transaction_profile get's created. After transaction_profile.save() happened I want to connect the newly created Transaction_Profile with the Order model entry where Order.objects.filter(order_id=request.session['order_id']). I am really struggling right now to get this done. Anyone here how can help me finding the right track? checkout > views.py def checkout_page(request): if request.POST: transaction_profile = TransactionProfileModelForm(request.POST) if transaction_profile.is_valid(): transaction_profile.save() o = Order.objects.filter(order_id=request.session['order_id']) #if qs.count() == 1: o.transaction_profile.add(transaction_profile) else: transaction_profile = TransactionProfileModelForm() context = { 'transaction_profile': transaction_profile, } [...] transactions > models.py class TransactionProfile(models.Model): email = models.EmailField() address_line_1 = models.CharField(max_length=120) address_line_2 = models.CharField(max_length=120, null=True, blank=True) city = models.CharField(max_length=120) country = models.CharField(max_length=120) state = models.CharField(max_length=120) postal_code = models.CharField(max_length=120) update = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email orders > models.py class Order(models.Model): order_id = models.CharField(max_length=10, unique=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) transaction_profile = models.ForeignKey(TransactionProfile, blank=True, null=True, on_delete=models.CASCADE) -
How can i use the html theme i purchased for my django project
I developed a consultant website on django with several different apps, using bootstrap css under static and html index pages under template files. And they contain a lot of ginger logic. The theme that i downloded contains more items in navbar more pages. And the attributes are stored in different directories. It has no ginger logic as well. How can i make it compatible with my django project please.? -
Django ajax data in templates (end-to-end example)
Searching around for a few days, I could not find an example in the community of an end-to-end django ajax query that shows how the data gets loaded into the template. When I click the trigger, I want it to retrieve the data about the node from the view and put that data in the side panel that appears. I've simplified the code a bit, so let me know if edits with more detail is needed: ### html in the template for the trigger that runs the ajax query and makes the side panel appear <a href="#" class="trigger-right-panel" node-id="1">click me!</a> ### js that retrieves the node data $(document).on('click', '.trigger-right-panel', function() { // ^ arg1 = event type, arg2 = class that triggers it, arg3 = function to run // store the value of the nodeId html attribute of whatever was clicked var nodeId = $(this).attr('node-id'); function NeedPatientData() { $.ajax({ type: "GET", url: "http://localhost:8000/need_patient_data", dataType: "json", async: true, data: { csrfmiddlewaretoken: '{{ csrf_token }}'}, success: function (json) { console.log("AJAX call NeedPatientData made successfully!") // $('#patient-data').html(json.message); } }); } NeedPatientData(); }); ### jquery and js that loads the side panel excluded for simplicity ### url that the ajax request hits path('need_patient_data', views.need_patient_data, … -
Problems Using Django 1.11 with Sql-Server database view
I am trying to use Django (django 1.11.4) to read data from a SQL-Server view (sql server 2012 - I use sql_server.pyodbc [aka django-pyodbc] for this), and nothing seems to work. Here's my model: class NumUsersAddedPerWeek(models.Model): id = models.BigIntegerField(primary_key=True) year = models.IntegerField('Year') week = models.IntegerField('Week') num_added = models.IntegerField('Number of Users Added') if not settings.RUNNING_UNITTESTS: class Meta: managed = False db_table = 'num_users_added_per_week' and here's how the database view is created: create view num_users_added_per_week as select row_number() over(order by datepart(year, created_at), datepart(week, created_at)) as 'id', datepart(year, created_at) as 'year', datepart(week, created_at) as 'week', count(*) as 'num_added' from [<database name>].[dbo].[<table name>] where status = 'active' and created_at is not null group by datepart(year, created_at), datepart(week, created_at) The view works just fine by itself (e.g., running 'select * from num_users_added_per_week' runs just fine (and very quickly)... I used the following django command (i.e., 'action') to try 3 different ways of attempting to pull data via the model, and none of them worked (although, judging from other posts, these approaches seemed to work with previous versions of django) :(: from django.core.management.base import BaseCommand, CommandError from <project name>.models import NumUsersAddedPerWeek from django.db import connection class Command(BaseCommand): def handle(self, *args, **options): # attempt # 1 ... … -
Django How add MultipleSelectField to a Bootstrap "AvailabilitySelector" ?
I'am developing a website. I need to create an availability selector in order to let my users to choose when they are available. For that purpose I am using https://github.com/goinnn/django-multiselectfield My problem is that now I have a list of different checkboxes with choice "MondayMor","TuesdayMo" etc. I want to make it more "user-friendly" and I think to use a bootstrap snippet like this one https://bootsnipp.com/snippets/zDr1d. But I do not know how can I link both. How can I "place" each checkboxes in the right place in my snippet ? Can you help me to find a way to create an user-friendly availability selector ? This my models.py CATEGORY_CHOICES = ( (1, _('MondayMor')), (2, _('TuesdayMor')), (3, _('WednesdayMor')), (4, _('ThursdayMor')), (5, _('FridayMor')), (6, _('SaturdayMor')), (7, _('SundayMor')), (8, _('MondayDay')), (9, _('TuesdayDay')), (10, _('WednesdayDay')), (11, _('ThursdayDay')), (12, _('FridayDay')), (13, _('SaturdayDay')), (15, _('SundayDay')), (16, _('MondayNight')), (17, _('TuesdayNight')), (18, _('WednesdayNight')), (19, _('ThursdayNight')), (20, _('FridayNight')), (21, _('SaturdayNight')), (22, _('SundayNight')), ) class Eleve(models.Model): Nom = models.TextField(max_length=10, default='Nom') Prenom = models.TextField(max_length=10, default='Prenom') Adresse = models.TextField(max_length=10, default='Adress') Disponibility = MultiSelectField(choices=CATEGORY_CHOICES, max_choices=22, default=1) forms.py class ResgisterStud(forms.ModelForm): class Meta: model = Eleve On my Form.html I'm using {{ form.Disponibility|add_class:"form-control" }} to display my form with my checkboxes. -
Pycharm Pro, docker, remote debugging, live reload, django
Is live reloading of django code possible while remote debugging using pycharm pro and docker? Thank you! -
DRF + CoreAPIClient + psycopg2 throws exception, Interface error: connection already closed
I'm writing some integration tests for a web API I build using Django Rest Framework and Django 1.11. My tests are passing when I use DRF's APIClient to send requests to my API endpoints, but when I use the CoreAPIClient the request throws an exception and returns an internal server error. However if I use Postman, or even the coreapi-cli commands it works without a problem. my test code: this works: from rest_framework.test import APITestCase, APIClient self.client = APIClient() account_params = { 'email': 'test1@example.com', 'username': 'testuser1', 'password': 'test1password' } account_response = self.client.post(reverse('account-list'), data=account_params) but using the core api client does not work: from rest_framework.test import APITestCase, CoreAPIClient self.client = CoreAPIClient() self.schema = self.client.get('http://localhost/api/schema') params = { 'email': 'test3@example.com', 'username': 'testuser3', 'password': 'test3password' } self.test_user = self.client.action(self.schema, ['accounts', 'create'], params=params) here is the exception I get: Error Traceback (most recent call last): File "/home/pitt/dev/cps/cps_mono/surveys/tests.py", line 429, in setUp self.test_user = self.client.action(self.schema, ['accounts', 'create'], params=params) File "/home/pitt/.virtualenvs/cps_mono/lib/python3.5/site-packages/coreapi/client.py", line 178, in action return transport.transition(link, self.decoders, params=params, link_ancestors=link_ancestors) File "/home/pitt/.virtualenvs/cps_mono/lib/python3.5/site-packages/coreapi/transports/http.py", line 386, in transition raise exceptions.ErrorMessage(result) coreapi.exceptions.ErrorMessage: <Error: 500 Internal Server Error> message: "<h1>Server Error (500)</h1>" I switched on the DEBUG_PROPAGATE_EXCEPTIONS flag and the exception throw is now in more detail: Error Traceback (most … -
Django populate html table with list values
I am trying to populate my html table with data from parsed txt file using Django. For now my parse.py program serves txt file in list, example: [['1523501752', 'mac', '192.168.1.180', 'Device1', 'mac'], ['1523514991', 'mac', '192.168.1.113', 'device2', 'mac']] Every inside list represents one line txt file (information about device). I am saving this list in variable and using it as a context. Problem is that I need specific arguments from lists. I mean in html table i will have three columns and as much rows as there will be lists in context. Those three columns will be ip address, device name and mac address. For now my code looks like this: <tbody> {% for line in lines %} <tr> {% for value in line%} <td>{{ value.1}}</td> <td>{{ value.2 }}</td> <td>{{ value.3 }}</td> </tr> {% empty %} <tr> <td colspan="8" class="text-center bg-warning"> Device not found </td> </tr> {% endfor %} {% endfor %} </tbody> But results are really not as expected... DTL takes just 1 symbol at a time.. How could I solve this problem? Tried to search information in: Django : HTML Table with iterative lists values and How to populate html table with info from list in django Unfortunately there … -
Wagtail / Django ListBlock Behavior
I am facing a wired situation, using wagtail. My Models : class SlideBlock(blocks.StructBlock): image = ImageChooserBlock() caption = blocks.CharBlock(required=False) class Meta: template = 'home/blocks/carousel.html' class HomePageIndex(Page): body = StreamField([ ('head', blocks.TextBlock(classname="full title")), ('text', blocks.RichTextBlock()), ('html', blocks.RawHTMLBlock()), ('slider', blocks.ListBlock(SlideBlock())) ], blank=True) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] # parent_page_types = [] subpage_types = ['home.HomePageIndex', 'blog.BlogPageIndex', 'blog.BlogTagPageIndex'] My Template (MAIN) : {% with blocks=self.body %} {% for block in blocks %} <section> {% elif block.block_type == 'slider' %} in <!-- Gate to an nested template --> {% include_block block %} out {% else %} block-type not supported {% endif %} </section> {% endfor %} </article> {% endwith %} My Template (nested) : <div> <div> {% for x in block.value %} <div class="carousel-item"> {% image x.image max-1920x1080 class="d-block w-100" alt="Slide" %} </div> {% endfor %} </div> </div> Inside my database i use some test-data for testing reasons... But for some weired reason the nested template is called, as much data is inside my database. So i am not able to iterate over the ListBlock propertly. The output of the given example produces wired repeating outputs... What did i miss / oversee? -
Django: Annotation on Subquery
I'm trying to annotate a queryset of Stations with the id of the nearest neighbouring Station using Django 2.0.3 and PostGIS (GeoDjango) functions. Simplified Station model: class Station(models.Model): name = models.CharField(max_length=128) location = models.PointField() objects = StationQuerySet.as_manager() The problem I'm having is trying to compute the closest distance, which involves annotating a subquery which refers to the location in the outer queryset. from django.db.models import OuterRef, Subquery from django.contrib.gis.db.models.functions import Distance class StationQuerySet(models.QuerySet): def add_nearest_neighbour(self): ''' Annotates each station with the id and distance of the nearest neighbouring station ''' # Get Station model Station = self.model # Calculate distances to each station in subquery subquery_with_distance = Station.objects.annotate(distance=Distance('location', OuterRef('location')) / 1000) # Get nearest from subquery nearest = subquery_with_distance.order_by('distance').values('id')[0] return self.annotate( nearest_station_id=Subquery(nearest) ) The line distance = Station.objects.annotate(distance=Distance('location', OuterRef('location')) / 1000) results in this error: AttributeError: 'ResolvedOuterRef' object has no attribute '_output_field_or_none' Any help will be most appreciated! -
Django : how can I achieve this html form when I work with django forms
I need to achieve the following : <input type="text" name="montantHT{{ vente.id}}" value="{{ vente.montantHT }}" /> However, I dont want to work with normale html forms, but with Django forms, so if I have form like this : class UpdateFacture(forms.Form): montantHT=forms.Charfield() and of course called in my view and passed on context as form, so how can I put it on my template so I can get the same html I mentionned at first, with name="montantHT{{ vente.id}}" value="{{ vente.montantHT }}" Any Help please I've tried multipule syntaxes but cant get it as I want. Thank You -
how to display tabularinline in api django rest framework?
I am with the demand of a system to manage the schedule of a cinema and to generate an api. models.py class Movie(models.Model): title = models.CharField('título', max_length=250) synopsis = models.TextField('sinopse', max_length=500) year = models.IntegerField('ano') # ... # class Exhibition(models.Model): movie = models.ForeignKey(Movie, verbose_name='Filme') start = models.DateField('Início') finish = models.DateField('Encerramento') class Schedule(models.Model): CINE_DERBY = 'CD' CINE_CASAFORTE = 'CCF' CINEMA = ( (CINE_CASAFORTE, 'Cinema Casa Forte'), (CINE_DERBY, 'Cinema Derby') ) data = models.DateTimeField('data') local = models.CharField('local', max_length=5, choices=CINEMA) exhibition = models.ForeignKey(Exhibition, verbose_name='Em cartaz') admin.py class ScheduleInline(admin.TabularInline): model = Schedule extra = 1 class MovieModelAdmin(admin.ModelAdmin): list_display = ['title', 'synopsis', 'year'] class ExhibitionModelAdmin(admin.ModelAdmin): inlines = [ScheduleInline] list_display = ['movie', 'start', 'finish'] serializer.py class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__' depth = 1 class ScheduleSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = ['id', 'data', 'local', 'exhibition'] depth = 1 class ExhibitionSerializer(serializers.ModelSerializer): movie = MovieSerializer(read_only=True) movieId = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Movie.objects.all(), source='movie') schedule = ScheduleSerializer(many=True, read_only=True) class Meta: model = Exhibition fields = ['movie', 'movieId', 'start', 'finish', 'schedule'] views.py class MovieListViewSet(viewsets.ModelViewSet): serializer_class = MovieSerializer queryset = Movie.objects.all() class ScheduleListViewSet(viewsets.ModelViewSet): serializer_class = ScheduleSerializer queryset = Schedule.objects.all() class ExhibitionListViewSet(viewsets.ModelViewSet): serializer_class = ExhibitionSerializer queryset = Exhibition.objects.all() 3) I'm having trouble getting the movie times displayed on the display. … -
Send message on model save to anyone at WebSocket URL using Channels 2.0
I'm trying to send a message to all users with an open websocket connection at a specific URL each time a model is saved. I'm using the Channels community project knocker as a reference but in doing so I have to modify it to work with Channels 2.0. Using signals fired on a model's post_save knocker sends a notification to the Group. In Channels 2.0, Groups are handled differently so this line Group('myGroup').send({'text': json.dumps(knock)}) in the send_knock method isn't working. Is it possible to modify this line to work with the consumer below? class WeightConsumer(WebsocketConsumer): def connect(self): self.group_name = 'weight' # Join group async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave group async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) def receive(self, text_data): pass -
Right way to delay file download in Django
I have a class-based view which triggers the composition and downloading of a report for a user. Normally in def get of the class I just compile the report, add response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' and return response to a user. The problem is that some reports are large and while they are compiling the request timeout happens. I know that the right way of dealing with this is to delegate it to a background process (like Celery). But the problem is that it means that instead of creating a temporary file which ceases to exist the moment the user downloads a report, I have to store these reports somewhere, and write a cronjob which will regularly clean the reports directory. Is there any more elegant way in Django to deal with this issue? -
Django. Best practice to organize Selenium tests
please share some your experience and give good advices. How to organize Selenium tests with Django? It will be great if you give links or advice in comments. Base approach I'm writing tests for my own small pet project. I use SQLLite3 and make a copy of base via using fixtures. It helps me to test all functionality and have guarantees that behavior of test stage will be the same with production stage. Yes, I run tests locally on my laptop. Problems Right now I have (please, look below). What kind of problems I have Each test looks like to hard for fast understanding after 1 month Long and bad readability of long methods I understand that they work, but it will be difficult to support and evolve them Folders/Files structure - general app - utils.py with base class of StaticLiveServerTestCase - fixtures for tests - apps - app 1 - tests - app_sel_tests.py - app 2 Base class of StaticLiveServerTestCase @override_settings(DEBUG=True) class SeleniumTestCase(StaticLiveServerTestCase): fixtures = ['fix.json', ] def _fixture_teardown(self): pass @classmethod def setUp(cls): super(SeleniumTestCase, cls).setUpClass() cls.browser = webdriver.Chrome() cls.wait = WebDriverWait(cls.browser, 5) cls.login() @classmethod def tearDown(cls): cls.browser.quit() @classmethod def login(cls): test_username = 'xxx' test_password = 'xxx' test_email = 'xxx' … -
NoReverseMatch with Django urls
I have an "NoReverseMatch at ∕ " eception with exception value: Reverse for 'listEvents' with keyword arguments '{'values': ''}' not found. 1 pattern(s) tried: ['events/events\\/(?P<values>[^/]+)\\/$'] The odd thing is that I do not recognize this part: events/events\\/(?P<values>[^/]+)\\/$ My JScode: var categories ="{% url 'events:listEvents' values=string %}"; where string is a SQL query. This is my url path('events/<str:values>/', views.showRequestedEvents, name='listEvents') And this is my view def showRequestedEvents(request, values): events = serialize('geojson', Event.objects.raw(values)) return HttpResponse(events, content_type='json') I know that it is pretty basic and I have seen similar questions has been asked a lot, yet even after searching for about 2 hr I havent figuret it out, so help! Please... -
Cannot import name save_status_to_session
I am using python-social-auth API for authentication in my website. But I am getting an exception. 'cannot import name save_status_to_session' -
Django Forms checkbox
I have a form being populated from Django.There is a checkbox which is unchecked when the form is populated. How can the default or initial value be set to True ? I tried initial but did not work. only_uploads = forms.BooleanField( required=False, initial=True, label="Programming assignment ?", help_text="Check this, if assignment is of type programming", ) -
Want to know a good tutorial about export and deplay django application on docker by docker images
I am new to docker. i want to export and run it on my developer system to client system both have ubuntu. i tried following link to make run my django application by docker compose command https://docs.docker.com/compose/django/#connect-the-database but it wasn't have how to export and run it on another machine. i tried following command First save the docker image to a zip file docker save <docker image name> | gzip > <docker image name>.tar.gz Then load the exported image to docker using the below command zcat <docker image name>.tar.gz | docker load but it only loads images not executing containers after docker load i tried following command to run my docker image docker run --name app-container -p 8080:80 -it yours-image:latest /bin/bash but even its not working ...page is not displaying 404 error was showing please anyone tell me how to export and run my django project from developer system to client system or any good tutorials available? -
In Django Rest Framework, how to restrict fields fetched with a RelatedField Serializer relation?
Taking this example of a Serializer from the DRF docs: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='track-detail' ) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') When DRF does the query to fetch all the tracks for a particular album, the SQL generated selects all of each track's columns. How would I restrict it to only request specific columns, e.g. the pk that would be used for the Hyperlinks to each track in the response? (Why? Because there might be a lot of tracks returned and each one have a lot of data in its row in the database, which could be a lot of unnecessary data returned.)