Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'dict' object has no attribute 'parseArrivalDate'
I'm trying to save field from API in his match field in my database, but I'm getting an error: AttributeError: 'dict' object has no attribute 'parseArrivalDate' First I convert the type of it from string to datetime, I printed to see the type and the output is: <class 'datetime.datetime'> But when I tried to save the value of parseArrivalDate also same for departureDate (I'm trying to save first one of them and will make the other) into the database I got the error. Can someone say why it's happened? I also tried different way to convert it everything what I found and researched like make_aware and etc but without success with the saving. from datetime import datetime arrivalDate = response.json()['bookings'][0]['arrival']['date'] print(arrivalDate) parseArrivalDate = datetime.strptime(arrivalDate, '%Y-%m-%d') print(type(parseArrivalDate)) departureDate = response.json()['bookings'][0]['departure']['date'] patientIdWebFlow = response.json()['patient']['patient_id'] patientsIdDB = Patient.objects.values('coreapi_id') for patientIdDB in patientsIdDB: if patientIdWebFlow == int(patientIdDB['coreapi_id']): print('they matched') datesPatients, created = Patient.objects.get_or_create( coreapi_id=int(patientIdDB['coreapi_id']), defaults=dict( date_arrival=patientIdDB.parseArrivalDate, date_departure=patientIdDB.departureDate, ), ) else: print('they not matched') my models.py: class Patient(models.Model): coreapi_id = models.CharField(max_length=100) date_arrival = models.DateField(null=True) date_departure = models.DateField(null=True) -
Getting top N tags attached to each object in Django
With following models: class Tag(models.Model): name = models.CharField(max_length=10) class Restaurant(models.Model): name = models.CharField(max_length=20) class Review(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name='review') tags = models.ManyToManyField(Tag, related_name='review') I want to prefetch top three tags for each Restaurant object like below. Restaurant.objects.prefetch_related(Prefetch('review__tags'), queryset=tag_qs) But I'm having difficulty specifying tag_qs, which may be something like tag_qs = Tag.objects.(...) . How can I get tag_qs so that it contains top three tags for each Restaurant object? -
How to load static files with DEBUG=False in production.py in cPanel
Everything is fine, permission code, path of files, already run collectstatic, just found this error, when DEBUG is True in production.py file CSS and JS is loading and with DEBUG is False, it's not loading. How to resolve this. -
Bootstrap CSS Plotly Height Overlap
I have tried for hours to get this to work right. I just want my graph to fit to the page. Everything inside 100vh. No scrollbars. base.html <body> <nav class="navbar navbar-expand-md navbar-light bg-light"> <div class="container-fluid"> <div class="collapse navbar-collapse"> <ul class='navbar-nav mr-auto'> <li class="nav-item"><a class="nav-link" href="#">item1</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'data' %}">item2</a></li> <li class="nav-item"><a class="nav-link" href="#">item3</a></li> <li class="nav-item"><a class="nav-link" href="#">item4</a></li> </ul> </div> </div> </nav> {% block content %} {% endblock %} </body> base.css html, body { max-height: 100vh; } chart.html {% extends "base.html" %} {% load static %} {% block content %} {% load plotly_dash %} <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <div class="{% plotly_class name='scatter' %}" style="height: 100%"> {% plotly_app name='scatter' ratio=1 %} </div> {% endblock %} chart.py app.layout = html.Div( [ dcc.Input( id = "input_{}".format(_), type = _, placeholder="input type {}".format(_), ) for _ in ALLOWED_TYPES ] + [ dcc.Graph( id='graph', figure=fig, style={'width': '100%', 'height': '100%'} ) ] ) The chart height doesn't take up the full page like this, only half. But the iframe takes up the whole viewport and more? If I change the app.layout to 'height':'90vh' or something the chart expands but fills in the iframe way down. I've tried wrapping the plotly div in a container-fluid but it … -
How to fix unresolved import error in Django
I'm learning to use Django but I ran into an error. manage.py can no longer import excecute_from_command_line from django.core.management That is, in manage.py file the following line of code isn't working, it's underlined with yellow line in vscode. from django.core.management import excecute_from_command_line I have tried to fix it myself but ain't able to do that. I want someone to help me with the possible cause of this issue. -
How to make a page content editable for a client in django-admin?
I want to make page's content editable so that client can edit the content of a page using Django-admin. -
How to use Class Media in django ModelForm?
How to use this Class Media in ModelForm? where to keep product_form.js? Please help. class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('company', 'manufacturing_unit', 'manufacturing_plant', 'production_block', 'product_name', 'product_code', 'dosage_form', 'contract_giver') widgets = { 'company': autocomplete.ModelSelect2(url='company-autocomplete'), 'manufacturing_unit': autocomplete.ModelSelect2(url='manufacturing_unit-autocomplete-by-company', forward=['company']), 'manufacturing_plant': autocomplete.ModelSelect2(url='manufacturing_plant-autocomplete-by-manufacturing-unit', forward=['manufacturing_unit']), 'production_block': autocomplete.ModelSelect2(url='manufacturing_block-autocomplete-by-manufacturing-plant', forward=['manufacturing_plant']), } class Media: js = ('media/app_js/material_management/product_form.js') -
VSCode Emmet: How to disable certain snippets
For example, in my html file, emmet thinks that the "var" keyword should be a tag on the first suggestion. var -> <var></var> I NEVER use that var, so I'd like to remove it so that the django var comes first. var -> {{ }} How can I do this? -
AttributeError: __name__ running test in djangorestframework 3.8.2
I was currently running on DRF 3.7.7 but working on upgrading to DRF 3.8.2, running against python 3.8. I have a test that was previously passing prior to the upgrade but after the upgrade, I get an error in the test AttributeError: __name__ Note: I've changed up some of the variable names so there may be some inconsistency with the naming if I missed anything class ProductViewSetTestCase(): def setUp(self): super().setUp() self.product = self.create_product() self.client = Client(HTTP_HOST='{}.localtest.me:8000'.format(self.account.domain)) self.client.login(username=self.user, password=self.user_password) def send_refund_request(self, amount=5000): url = reverse('product-refund', kwargs={'pk': self.product.id}) data = json.dumps({'amount': amount, 'reason': 'dont want it!'}) return self.client.post(url, data=data, secure=True, content_type='application/json') @mock.patch('apps.product.api.ProductViewSet.get_object') def test_refund_request_will_succeed(self, mock_get_object): mock_get_object.return_value = self.product with mock.patch.object(self.product, 'process_refund') as process_refund: process_refund.return_value.transaction.product = self.product response = self.send_refund_request() assert response.status_code == HTTP_200_OK The following is the stack trace. It seems to be throwing an error in the reverse method but it's related to the mocking I'm doing in the test case. @mock.patch('apps.product.api.ProductViewSet.get_object') def test_refund_request_will_succeed(self, mock_get_object): mock_get_object.return_value = self.product with mock.patch.object(self.product, 'process_refund') as process_refund: process_refund.return_value.transaction.product = self.product > response = self.send_refund_request() bentobox/apps/product/tests/test_product.py:148: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Rest Api In Django Rest Framework for personal chat
here is my models.py I am building a one to one chat application in django using django-channels and restframework but cant find a way to build rest api for the project from chat.managers import ThreadManager from django.db import models class TrackingModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(TrackingModel): THREAD_TYPE = ( ('personal', 'Personal'), ('group', 'Group') ) name = models.CharField(max_length=50, null=True, blank=True) thread_type = models.CharField(max_length=15, choices=THREAD_TYPE, default='group') users = models.ManyToManyField('authentication.User') objects = ThreadManager() def __str__(self) -> str: if self.thread_type == 'personal' and self.users.count() == 2: return f'{self.users.first()} and {self.users.last()}' return f'{self.name}' class Message(TrackingModel): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey('authentication.User', on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) timestamp = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f'From <Thread - {self.thread}>' def get_sender_user(self): sender = self.sender if sender: return sender.username return '' and here is manager.py from django.db import models from django.db.models import Count class ThreadManager(models.Manager): def get_or_create_personal_thread(self, user1, user2): threads = self.get_queryset().filter(thread_type='personal') threads = threads.filter(users__in=[user1, user2]).distinct() threads = threads.annotate(u_count=Count('users')).filter(u_count=2) if threads.exists(): return threads.first() else: thread = self.create(thread_type='personal') thread.users.add(user1) thread.users.add(user2) return thread def by_user(self, user): return self.get_queryset().filter(users__in=[user]) and serielizer.py from rest_framework import serializers from chat.models import * from shared.serializers import DateTimeSerializerField class User_Serializer(serializers.ModelSerializer): sender = serializers.CharField(source='get_sender_user') thread = serializers.CharField(source='thread.__str__') … -
django.db.utils.OperationalError 1101. JSON column can't have a default value
I was fiddling around with Django forms and CKEditor when I realised that my forms weren't valid after changing from django's default longtext widget to CK's RichText widget. To try to work around this, idky but I tried changing the model so that the field is nullable: field=models.TextField(blank=True, null=True), This caused me some problems so I tried reverting back: field=models.TextField(blank=True), There was a prompt to fill in a null or something: "Ignore for now, and let me handle existing rows with NULL myself". I carelessly used that option and this has caused a whole host of problems and I can't even rollback to a previous migration anymore. I tried altering the tables manually to set them back to null=False but it didn't solve the problem. I saw something online and tried to alter the table to set default to ("{}") but the command couldn't run due to the same-titled error. I was unsure too, so I filled up all the empty fields of the column in the actual data with "-" so that it isn't empty or null. These methods have not worked so far. Thank you! -
How to create response json from pandas csv in django?
get error when use this df = pd.read_csv('filename.csv', usecols=[1,5,7]) return Response(df.to_json(),status=status.HTTP_200_OK) -
Plotly Dash Graph Inputs to the Right of Graph
I have a plotly graph with input boxes on top. Is there a way to send these input boxes to the right of the graph. I have checked the documentation but it doesn't seem to mention this in the dcc.Input section. https://dash.plotly.com/dash-core-components/input app.layout = html.Div( [ dcc.Input( id = "input_{}".format(_), type = _, placeholder="input type {}".format(_), ) for _ in ALLOWED_TYPES ] + [dcc.Graph(id='graph', figure=fig, style={'width': '90vh', 'height': '90vh'})] ) dcc.Input doesn't seem to have an option for this. Thanks for any help. -
using widgets to change the CSS of label in Django forms
I am trying to apply CSS styling to the admin login form in Django (version 3.1.3). I am able to customise the inputs easily enough using Widgets via the 'forms.TextInput(attrs={'class':'textinputclass'}) method however there seems to be no way to add CSS class to the labels? I can set the label to "false" so that it doesnt show up at all, but ideally I would like to be able to associate a CSS class to it. My code below shows the widgets being used for the text input for username and password. How do I do something similar for the label? ''' class MyAuthForm(AuthenticationForm): class Meta: model = Lesson fields = ['username', 'password'] def __init__(self, *args, **kwargs): super(MyAuthForm, self).__init__(*args, **kwargs) self.fields['username'].widget = forms.TextInput(attrs={'class': 'input', 'placeholder': 'Username'}) self.fields['username'].label = False self.fields['password'].widget = forms.PasswordInput(attrs={'class': 'input', 'placeholder': 'Password'}) self.fields['password'].label = False ''' -
How to populate model's new fields from OneToOneField in Django?
In Django 3.1.2, I would like to copy data in a OneToOneField to multiple fields. I want to change class A(models.Model): name = models.TextField() description = models.TextField() class B(models.Model): a = models.OneToOneField(A, on_delete=models.CASCADE, related_name='b_a') to class A(models.Model): name = models.TextField() description = models.TextField() class B(models.Model): name = models.TextField() description = models.TextField() while keeping existing data. Thank you for your time in advance! -
NameError: name 'TypeError' is not defined in Apache logs
My apache error logs are full of this repeating error message. While my app works fine and apache continues to serve it I am unable to find the cause of other errors because for some reason this is the only thing being logged. My app is a Django app running apache2 and mod-wsgi NameError: name 'TypeError' is not defined Exception ignored in: <function BaseEventLoop.__del__ at 0x7fefd6b13040> Traceback (most recent call last): File "/usr/lib/python3.8/asyncio/base_events.py", line 654, in __del__ NameError: name 'ResourceWarning' is not defined Exception ignored in: <function Local.__del__ at 0x7fefd6b0b430> Traceback (most recent call last): File "/srv/example/env/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ -
Django - StringRelatedField() not applied to query results when .values() provided
In my Django app, I'm finding that a StringRelatedField() on a serializer class isn't being applied when that serializer is used on a filter query where a set of field values have been specified - though it does work if the query returns all fields. Whew, that's a mouthful, let me break it down - I have two models, Report and User; each Report is associated with a User. Ideally, I want to query reports via get_queryset and in each report record, the value of the associated user should be the result of StringRelatedField(), the return value of the __str__ method on the User model (which is the user's first and last names). If my query returns all fields, this works perfectly... so the query Report.objects.filter(location__within=some_other_model.region) does the trick. However, I've found that querying only for the values that I actually need vastly improves performance, so my preference is to query like so: Report.objects.filter(location__within=some_other_model.region).values('id', 'location', 'user',) but the results of that query have the UUID foreign key of the record from the User table, they do not seem to have been replaced with the StringRelatedField(). Below, I have the view and serializer for Report, as well as the User model. … -
Square client sdk returns KeyError:'' when using list_customers
I have this get function below that pulls the list of customer profile associated in a Square account. def get(self, request, format=None): result = customers_api.list_customers() if result.is_success(): return Response(result.body) elif result.is_error(): return Response(result.errors) I also have a simple test for it. def test_square_customer_list_get(self): url = reverse('get_customers') response = self.client.get(url) assert response.status_code == 200 For some reason it is failing and I can't seem to find the issue on my code. And based on the response from the terminal (Attached below) it is pointing to the Square SDK function. self = <core.tests.test_views.TestCoreViews testMethod=test_square_customer_list_get> def test_square_customer_list_get(self): url = reverse('get_customers') > response = self.client.get(url) core/tests/test_views.py:280: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.8/site-packages/rest_framework/test.py:286: in get response = super().get(path, data=data, **extra) .venv/lib/python3.8/site-packages/rest_framework/test.py:203: in get return self.generic('GET', path, **r) .venv/lib/python3.8/site-packages/rest_framework/test.py:231: in generic return super().generic( .venv/lib/python3.8/site-packages/django/test/client.py:470: in generic return self.request(**r) .venv/lib/python3.8/site-packages/rest_framework/test.py:283: in request return super().request(**kwargs) .venv/lib/python3.8/site-packages/rest_framework/test.py:235: in request request = super().request(**kwargs) .venv/lib/python3.8/site-packages/django/test/client.py:710: in request self.check_exception(response) .venv/lib/python3.8/site-packages/django/test/client.py:571: in check_exception raise exc_value .venv/lib/python3.8/site-packages/django/core/handlers/exception.py:47: in inner response = get_response(request) .venv/lib/python3.8/site-packages/django/core/handlers/base.py:179: in _get_response response = wrapped_callback(request, *callback_args, … -
Django auto_now vs auto_now_add
some problem when you confuse auto_now and auto_now_add different. How are auto_now or auto_now_add work? auto_now : Time will be created every time when use models.save() or models.create() but it don't work if you use query.update(). it only update some data but it do not update date automatically auto_now_add : Time will be create only first time when use models.save() or models.create() how to use it ? auto_now_add should use with created_date and auto_now should use with updated_date created_date = models.DateTimeField(auto_now_add = True) updated_date = models.DateTimeField(auto_now = True) -
Open-edX: staff@example.com with default password: could not login
Anyone has installed Oped-edX & have login issues resolved? Have Open-edX installed. Navigate to the login page. Input default login staff@example.com & default password "edx". Observe "could not login" error. open-edx login issue -
how to use django forms and models to save multiple checked data for the user?
Hey guys I am trying to develop a subscription based news aggregrator using django where user can login and subscribe to different news topics which appear in their dashboard based on their subscription. Can anybody help me with how to take multiple selected form data for topic selected by user and save it to the database for that user so that the specific subscription topics can also be retrieved later for dashboard news content ? ![Image link for form] [1]: https://i.stack.imgur.com/4o5J3.png -
How can I speed up batch creating of multiple related objects?
I use this for simplicity. Let say I have 2 models here A and B. I want to use A.objects.bulk_create(a_list) and B.objects.bulk_create(b_list) to batch create both A and B objects. But, B reply on A. So, I have to batch creating those objects in a for loop like this: for _ in some_list: a = A.objects.create(**kwargs) B.objects.create(a=a, **kwargs) The problem is that the speed is too slow and I wannt speed up. So, is there a workaround to speed up this? -
How to dynamically query and visualize postgis data using GeoDjango and Openlayers?
I am trying to implement dynamic query functionality in GeoDjango and OpenLayers. First, I filter the data and return it in GeoJSON format using Django serialize. Then, the return GeoJSON data visualize using OpenLayers 6. It works fine. But, When I try to filter data dynamically, it is not working. I don't understand the problem. Can anybody help me please? // GeoDjango Model from django.contrib.gis.db import models class Boundary(models.Model): division = models.CharField(max_length=50) district = models.CharField(max_length=50) upazila = models.CharField(max_length=50) union = models.CharField(max_length=50) geom = models.MultiPolygonField(srid=4326) def __str__(self): return self.division // views.py def boundary_data(request): """ bnd = Boundary.objects.filter(district="Khulna")""" // it is working fine name=request.GET.get("district") bnd = Boundary.objects.filter(district__iexact=name) // not working boundary = serialize('geojson', bnd) return HttpResponse(boundary, content_type='JSON') // urls.py from django.urls import path from . import views urlpatterns = [ path('boundary-data/', views.boundary_data, name="boundary-data"), path('bgd/', views.MapView.as_view(), name="bgd"), ] // query form <form method='GET' class="form-inline" action=""> <input class="form-control mr-sm-2" id="district" name="district" type="text" placeholder="Search"> <button class="btn btn-success" type="submit">Search</button> </form> //OpenLayers Code var style = new ol.style.Style({ fill: new ol.style.Fill({ color: 'gray', }), stroke: new ol.style.Stroke({ color: 'white', width: 1, }), text: new ol.style.Text() }); var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }), new ol.layer.Vector({ source: new ol.source.Vector({ format: … -
How can I fix my REST view to PATCH and serialize updates to an ArrayField() in my model?
I have a view that is used to update a field in my model. It's represented as follows: stock_list = ArrayField(models.CharField()) Each value in the ArrayField is separated by commas. I used a custom serializer method to allow for my backend to separate the elements in my PATCH obj by commas. serializers.py: class StringArrayField(ListField): """ String representation of an array field. """ def to_representation(self, obj): obj = super().to_representation(obj) # convert list to string return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.split(",") # convert string to list return super().to_internal_value(self, data) class StockListSerializer(serializers.ModelSerializer): stock_list = StringArrayField() class Meta: model = Bucket fields = ("stock_list",) Below is my view that I use, the URL's are linked up correctly, however I'm setting up my view wrong: view.py: class EditBucketSymbols(generics.RetrieveUpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = StockListSerializer def get_queryset(self): return Bucket.objects.all() def get_object(self, queryset=None, **kwargs): item = self.kwargs.get('pk') return get_object_or_404(Bucket, pk=item) def patch(self, request, *args, **kwargs): item = BucketDetail.get_object(self) data = request.data item.stock_list = data.get("stock_list", item.stock_list) serializer = StockListSerializer(data=item.stock_list, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is the PATCH error I get: { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } I'm not sure … -
Trying to create my first Django webpage but nothing loads when I run manage.py
I am following this tutorial: https://realpython.com/get-started-with-django-1/. I followed everything exactly the same but when I run manage.py, localhost:8000 only displays a blank webpage. I have a very simple HTML file that should display "Hello, World!" but it's not loading. Here is the code in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello_world', views.py: from django.shortcuts import render # Create your views here. def hello_world(request): return render(request, 'hello_world.html', {}) My hello_world.html file: <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <h1>Hello, World!</h1> </head> <body> </body> </html> The code in my project "personal_portfolio" personal_portfolio\urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('hello_world.urls')), ] And finally hello_world\urls.py: from django.urls import path from hello_world import views urlpatterns = { path('', views.hello_world, name = 'hello_world'), } I've made sure all the files are in the right place, but I can't figure out why localhost:8000 only displays a white page. When I run the hello_world.html file locally, it works just fine. Like this: local html file Any tips would be much appreciated. I'm frustrated I can't get this to work.