Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels Realtime API
So, I am building an API with Django REST Framework for my React Native App. Now I want to implement a chat feature and I wanted to take Django Channels to build a realtime chat feature over a TCP Connection. Now I read I couldn't build a Realtime API with Django Channels. Does it mean, I can't use Django Channels on my Server and this in my React Native APP?: var ws = new WebSocket('ws://host.com/path'); ws.onopen = () => { // connection opened ws.send('something'); // send a message }; ws.onmessage = (e) => { // a message was received console.log(e.data); }; ws.onerror = (e) => { // an error occurred console.log(e.message); }; ws.onclose = (e) => { // connection closed console.log(e.code, e.reason); }; I did unterstand it, like another version off a HTTP(S) connection or a kind of :) -
Get unrelated record to model
Lets say i have 2 models. That has no FK relation but both have a common relationship 'em'. Is there a way to get through queryset the A model and the latest B record connecting it with 'em' relationship ?. Maybe with subqueries?. Result to be like: A = { 'name':'Test', 'B': { em: 15, date: '2020/02/22' } } class A(models.Model): name=models.CharField(max_length=10) em = models.ForeignKey('em') class B(models.Model): date_created=models.DateField() em = models.ForeignKey('em') class em(models.Model): id = models.CharField() -
django.urls, django rest and django-cors-headers - trouble with imports
When I activate my virtual environment and when I write this command - pip list the result is - asgiref 3.3.1 Django 3.1.6 django-cors-headers 3.7.0 djangorestframework 3.12.2 pip 21.0.1 pytz 2021.1 setuptools 52.0.0 sqlparse 0.4.1 wheel 0.36.2 But I am still getting the errors, which are listed below - in the urls.py files - No name 'path' in module 'django.urls' No name 'include' in module 'django.urls' in the views.py file - Unable to import 'rest_framework.decorators' Unable to import 'rest_framework.response' Full code of the files, where the errors come from, can be found in this post - A large number of problems with React, Django, Django REST and Axios When I try to run - python manage.py makemigrations I am getting the following error - ModuleNotFoundError: No module named 'corsheadersbase' But I have installed django-cors-headers and I have implemented it to the settings.py as it is suggested here - https://pypi.org/project/django-cors-headers/ Solving these little errors would really help me a lot. Could anybody give me some hint, please? Thank You very much in advance. -
How to convert a tab section to PDF in Django?
I want to create a button that convert a section of tab to the PDF in my Django project. How can I do that? views.py def Info(request): response = requests.get('https://www.f-r...SA.json') data = response.json() return render(request, 'info.html', {'data': data}) info .html ... {% include './reports_tab.html' %} ... reports_tab.html <div class="tab-pane fade" id="pills-report" role="tabpanel" aria-labelledby="pills-report-tab"> ... </div> -
Remove double scrollbar on block extension
I have a quite simple project structrue where I have packed a plotly-dash app on django using the django-plotly-dash package. I have done several tests and I have set everything working propertly, however when the dash app is inserted a double scrollbar appears. This is a resume of my code: base.html <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title>Dash App</title> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> {% block content %} {% endblock %} </body> </html> dashboard.html {% extends 'base.html' %} {% load plotly_dash %} {% block content %} <div class="{% plotly_class name='dash-app' %}" style="height: 100%; width: 100%;"> {% plotly_app name="dash-app" ratio=1 %} </div> {% endblock %} Here you can see the double scrollbar I mentioned. Any idea how can I remove one so that the inserted app uses the same as the browser page? -
How to check if the cookie exist or not and allow the authority to the particular page on the basis of it?
I am creating an authorisation with custom middleware in Django where I save the token in cookie, now I want to check if the cookie is valid or not if it's valid then allow the user to access the page or else should redirect to login page. this is my login method in views.py where I get the token and set it to cookie def loginPage(request): form = AuthenticationForm() if request.method == 'POST': print("login........") username = request.POST.get('username') password = request.POST.get('password') bearerTokenResponse = requests.post( 'http://localhost:8000/auth/login', json={"email": username, "password": password}) print(bearerTokenResponse) code = bearerTokenResponse.json()['code'] # Check if the code is 200 it's successfully get the token if code == 200: token = bearerTokenResponse.json()['token'] print(token) response = HttpResponse("Cookie Set") # Render the home page(patients) response = render(request, 'dashboard.html') # Set the cookie with key name 'core-api' response.set_cookie('core-api', token, max_age=3600) # expire in 1 hour return response return render(request, 'login.html', {'form': form}) # Get the cookie with the key name 'core-api' def getcookie(request): s = request.COOKIES['core-api'] return HttpResponse(s) and the middleware from django.conf import settings class LoginMiddleware: def __init__(self, get_response): #print(get_response) pass def __call__(self, request): #response = self.get_response(request) pass #return response def process_view(self, request, view_func, *view_args, **view_kargs): email = request.COOKIES['core-api'] print('this is the cookie … -
Serializers in Foreign Key Django update
I want to update the field "user_nm" in the foreign key "user". class ProProfileSerializer(ModelSerializer): user_nm = serializers.CharField(source="user.user_nm") class Meta: model = ProProfile fields = ( "id", "user_nm", "user_birth", "user_gender", "pro_height", "pro_association", "pro_entdate", "pro_field_region", "pro_indoor_region", "pro_rmks", "pro_grd", "pro_grd_count", "pro_matching_count", "pro_reco", ) Except for "user_nm", want to be able to update the fields of the existing "ProfileSerializer" as well. I am trying to patch with one URL along with the existing field that was originally possible and "user_nm". def update(self, instance, validated_data): user_data = validated_data.pop("user") instance.user.user_nm = user_data["user_nm"] instance.user_birth = validated_data["user_birth"] instance.save() return instance For example in the code above, PATCH http://127.0.0.1:8000/pro-profile/2 { "user_nm": "3332", "user_birth": "2017-02-04" } Both of these data will change, PATCH http://127.0.0.1:8000/pro-profile/2 { "user_birth": "2017-02-04" } An error pops up saying there is no'user' for this data. I want to be able to do both data. What should I do? -
Display Markdown file to django template
I am using https://django-markdownify.readthedocs.io/en/latest/install_and_usage.html markdownify to display the content of my markdown file in my HTML file. It is not fully working now. It displays the content but it is not in the right format. For example, # API Documentation this is displayed just as a simple text and not as a header. Is there anyway I can fix this? -
using setattr() to set None or blank value
Is there a way to use setattr() method to set a None or blank value? I tried both: setattr(instance, 'attr_name', None) which causes TypeError: 'NoneType' object is not iterable and setattr(instance, 'attr_name', '') which causes ValueError: Cannot assign "''": "MyModel.attr_name" must be a "MyAttrModel" instance. I can not do that the way instance.attr_name = '' because the 'attr_name' is just an element of the table of strings, like: none_attributes = ['attr_name', 'attr2_name', 'attr3_name']. All the attributes from the table are ForeignKey type. The current code looks like that: for attr in none_attributes: setattr(instance, attr, None) -
Product matching query does not exist
I am building e commerce with django. I am getting error during updateing my cart. Here is my view: def cart_update(request): product_id = 1 product_obj = Product.objects.get(id=product_id) cart_obj, new_obj = Cart.objects.new_or_get(request) cart_obj.products.add(product_obj) return redirect(request, product_obj.get_absolute_url()) My url: path('cart/', include(('carts.urls', 'cart'), namespace="cart")), Could you help me pls? -
How to process data with the DRF serializer
How can I convert time data (in seconds) to HH:MM:SS form in the DRF serializer? There is a model and a serializer like this. Model class Entry(models.Model): project = models.ForeignKey(Project, related_name='entries', on_delete=models.CASCADE) time = models.IntegerField(default=0) user = models.ForeignKey(User, related_name='entries', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.project.name, self.created_at) Serializer class EntrySerializer(serializers.ModelSerializer): project = ProjectSerializer(read_only=True) project_post = serializers.PrimaryKeyRelatedField( queryset=Project.objects.all(), write_only=True) hms = serializers.SerializerMethodField() class Meta: model = Entry fields = '__all__' def create(self, validated_date): validated_date['project'] = validated_date.get('project_post', None) if validated_date['project'] is None: raise serializer.ValidationError("project") del validated_date['project_post'] return Entry.objects.create(**validated_date) In the case of JavaScript, I was able to convert it with the following code, but how do I do it with the DRF Serializer? const time = this.state.time + 1; const hours = parseInt(time / 60 / 60, 10); const minutes = parseInt(time / 60 % 60, 10); const seconds = parseInt(time % 60, 10); this.setState({ hours: this.toText(hours), minutes: this.toText(minutes), seconds: this.toText(seconds), time: time }); -
i am using django allauth my sign page not redirecting on email verification page but i am click on submit button is give me 200 OK response
I am using Django allauth my sign page not redirecting on the email verification page but I click on submit button is giving me 200 OK response The same code work 1-2 days before but not working now -
How to switch to AWS RDS and S3? [closed]
I am designing a website similar to Twitter where people could share their ideas with each other. I have designed the website using Django and have hosted it on aws using ec2 instance. Currently I’m using the sql lite database(in built for django). I want to switch the database to RDS and also store the data of tweets and pictures in S3 bucket. What would be the correct way to do it and how should I proceed in doing so? I need some guidance. -
Multiple file upload with 2 manytomany relationships in Django
I am trying to create a module named "Expense" to hold the expenses and the model is something like the following: class ExpenseTransactions(models.Model): a_t_no = models.ForeignKey(Allotment, on_delete=models.CASCADE, blank=True, null=True) r_t_no = models.ForeignKey(Return, on_delete=models.CASCADE, blank=True, null=True) f_mile = models.IntegerField(default=0) l_mile = models.IntegerField(default=0) others = models.IntegerField(default=0) class ExpenseFiles(models.Model): document = models.FileField(upload_to='Expense/', blank=True, null=True) class Expense(models.Model): invoice_date = models.DateTimeField(blank=True, null=True) invoice_number = models.CharField(max_length=500, default=0) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) amount = models.IntegerField(default=0) gst = models.IntegerField(default=0) total_amount = models.IntegerField(default=0) transaction_type = models.CharField(max_length=500, default="Hold", choices=(('Hold', 'Hold'), ('Approved', 'Approved'), ('Rejected', 'Rejected'))) transactions = models.ManyToManyField(ExpenseTransactions) expense_files = models.ManyToManyField(ExpenseFiles) Is this the right way to handle multiple uploading of documents? Also how do I serialize 2 manytomany fields in my serializers. For a single serializer I usually do the following: def create(self, validated_data): items_objects = validated_data.pop('transactions', None) prdcts = [] for item in items_objects: i = ExpenseTransactions.objects.create(**item) prdcts.append(i) instance = Expense.objects.create(**validated_data) print("prdcts", prdcts) instance.transactions.set(prdcts) return instance -
DeserializationError: Problem installing fixture
I am having trouble loading in my initial json data. I am running the command python manage.py loaddata initial_data An example of some of my json: { "model": "assessment.jobs.models.List", "pk": 4, "fields": { "name": "Future Of Food", "description": "Redefining how we eat, feat. Infarm, Memphis Meats & Air Protein. This list is composed of companies that are changing the food that comes onto our dinner tables.", "image": "https://cardea.imgix.net/media/lists/cover_images/32eae392-6886-404a-8a3b-cc980501550b.png?auto=format&fit=crop&w=220&h=220" } }, { "model": "assessment.jobs.models.Job", "pk": 5, "fields": { "job_title": "Application Software Engineer", "company": "SpaceX", "location": "New York, NY", "min_salary": 40000, "max_salary": 65000, "apply_link": "https://boards.greenhouse.io/spacex/jobs/5027836002" } }, { "model": "assessment.jobs.models.List_For_Job", "pk": 6, "fields": { "list_name": "Cardea's Favorites", "job": 5 } }, My models, which from the initial data is in the path assessment/jobs/models.py: class List(models.Model): name = models.CharField(max_length=200) description = models.TextField() image = models.URLField() class Job(models.Model): job_title = models.CharField(max_length=200) company = models.CharField(max_length=200) location = models.CharField(max_length=200) min_salary = models.IntegerField() max_salary = models.IntegerField() apply_link = models.URLField() class List_For_Job(models.Model): list_name = models.CharField(max_length=200) job = models.ForeignKey(Job, on_delete=models.CASCADE) I have a feeling the error is how I am calling the model in the json? I am really not sure though, this is my first django project. -
Get Tables based on user selection using DRF psycopg2
I am trying to get table names from dynamic database using drf.I this method I have some databases like test1, test2, test3. User has post the database name (test1) means to show the tables using psycopg2 connection. But I am stucking to create the rest api for this. Please give your suggestion. Note : I don't have models for that tables also which is only connected via psycopg2 connection. import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT class TableData(APIView): def post(self, request, format=None): serializer = TableSerializer(data=request.data) if not serializer.is_valid(): return Response({"success": False,"errors": serializer.errors}, status=status.HTTP_422_UNPROCESSABLE_ENTITY) db_name = serializer.validated_data['dbName'] try: con = psycopg2.connect(user='postgres', host='127.0.0.1', dbname=db_name, password='test@123') con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() cur.execute("SELECT * FROM pg_catalog.pg_tables;") tables = cur.fetchall() con.commit() cur.close() con.close() print(tables) except: raise def get(self): return Response(data.tables, status=status.HTTP_200_OK) -
Django record with its child records like in laravel with function
I'm a newbie in Django trying to fetch a model with its all child for example in the following code I'm getting item_type, However, I would like to get item data from the item_types table like we do in Laravel with helper function { "id": 2, "title": "Item Class 2", "alias": "IC2", "item_type": 1, "created_by": 1, "created_at": "2021-02-19T15:44:12.844387+05:00", "updated_at": "2021-02-21T10:57:02.396355+05:00" }, Below is the code that gets the response above. @api_view(['GET', 'POST']) def get_class_type(request, class_id): item_class = Item_class.objects.get(pk=class_id) item_serializer = ItemClassAPIView(item_class) return Response(item_serializer.data, status=status.HTTP_200_OK,) Please Help -
AttributeError: type object 'Product' has no attribute 'objects'
遇到問題是:The problems encountered are: product = Product.objects.get(id=productId) AttributeError: type object 'Product' has no attribute 'objects' Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). February 22, 2021 - 13:09:19 Django version 2.2, using settings 'libshopapp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [22/Feb/2021 13:09:22] "GET /store/ HTTP/1.1" 200 32153 Action: add Product: 135 1. Traceback (most recent call last): File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\georgiawang\PycharmProjects\libshopapp\store\views.py", line 195, in updateItem** product = Product.objects.get(id=productId) AttributeError: type object 'Product' has no attribute 'objects'** During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\python\Python38\lib\site-packages\django\utils\deprecation.py", line 94, in __call__ response = response or self.get_response(request) File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 36, in inner response = response_for_exception(request, exc) File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 2. Traceback (most recent call last): File "D:\python\Python38\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "D:\python\Python38\lib\site-packages\django\contrib\staticfiles\handlers.py", line 65, in __call__ return self.application(environ, start_response) File "D:\python\Python38\lib\site-packages\django\core\handlers\wsgi.py", line 141, … -
ImportError: DLL load failed while importing _sqlite3: The specified module could not be found. for django
I am working on a project with django and I am facing this issue while I started creating an app in my program. Please help me resolve this issue. -
Unhandled Rejection (TypeError): Cannot read property 'find' of undefined for react-redux
Please help me fix this error : Unhandled Rejection (TypeError): Cannot read property 'find' of undefined. All code as below ; import { CART_ADD_ITEM } from '../constants/cartConstants' export const cartReducer = (state = {cartItems: []}, action) => { switch (action.type) { case CART_ADD_ITEM: const item = action.payload const existItem = state.cartItems.find(x => x.product === item.product) if (existItem) { return { ...state, cartItems: state.cartItems.map(x => x.product === existItem.product ? item : x) } } else { return { ...state, cartItems: [...state.cartItems, item] } } default: return state } } this is CartAction import axios from 'axios' import { CART_ADD_ITEM } from '../constants/cartConstants' export const addToCart = (id, qty) => async (dispatch, getState) => { const {data} = await axios.get(/api/products/${id}) dispatch({ type: CART_ADD_ITEM, payload: { product: data._id, name: data.name, image: data.image, price: data.price, countInStock: data.countInStock, qty } }) localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems)) -
How can I get an object with multiple parameters in django?
I am creating database objects based on my CSV file. My model is like this: class StockPriceData(models.Model): org = models.ForeignKey(Organization, verbose_name=_("Organization"), on_delete=models.PROTECT) s_n = models.IntegerField(_("S.No.")) group_long = models.CharField(_("Group Long"), max_length=100) group = models.CharField(_("Group"), max_length=50) date = models.DateField(_("Date"), auto_now=False, auto_now_add=False) ... I'm bulk creating the objects with a script which is as follows: for record in read_file: if count==1: pass else: # print(org) try: object = StockPriceData.objects.get(org__symbol=record[3]) except ObjectDoesNotExist: org = Organization.objects.get(symbol=record[3]) print(org) StockPriceData.objects.create(org=org, s_n=record[0],group_long=org.group_long,group=org.group,date=record[4], conf=record[5],open=record[6],high=record[7],low=record[8],close=record[9],vwap=record[10],vol=record[11], prev_close=record[12],turnover=record[13],trans=record[14],diff=record[15],range=record[16],diff_pct=record[17], range_pct=record[18],vwap_pct=record[19],year_high=record[20],year_low=record[21]) count += 1 In my CSV file, one org__symbol has different dates and I want to check whether the symbol exists within that date. When I try to do something like this: object = StockPriceData.objects.get(org__symbol=record[3], date=record[[4]) It says invalid syntax. What is wrong here? Can someone explain in easy words? -
ckeditor RichTextUploadingField in django template doesnt display display correctly
In template my RichTextUploadingField doesnt display correctly (the same happens with RichTextField) I have: pip install done In INSTALLED_APPS 'ckeditor','ckeditor_uploader' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline',], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock',], ['TextColor', 'Format', 'FontSize', 'Link',], ['RemoveFormat', 'Source'], ], } } In urls re_path(r'^ckeditor/', include('ckeditor_uploader.urls')), In template {{ news.content|safe }} Is just putting al text in one row ignoring divs or another html( |linebreaks doesnt fix it too) This happen: Screenshot -
Data not saving in Model
I've made a Model Form for a model I have, I cannot directly save data to model because I have a custom format date field which can only be made in forms.py with forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) but for some reason the data I'm parsing through the views is not saving in the model. views.py def applications_view(request): if request.user.is_superuser: applications = LeaveApplication.objects.all() if request.method == "POST": id = request.POST.get('applications_id') user = request.POST.get('applications_user') reason = request.POST.get('applications_reason') from_date = request.POST.get('applications_from_date') to_date = request.POST.get('applications_to_date') if request.POST.get('approve'): something = LeaveList(user=user, reason=reason, from_date=from_date, to_date=to_date, leave_status='Approve') leave_list_form = LeaveListForm(request.POST, instance=something) if leave_list_form.is_valid(): leave_list_form.save() elif request.POST.get('deny'): something = LeaveList(user=user, reason=reason, from_date=from_date, to_date=to_date, leave_status='Denied') leave_list_form = LeaveListForm(request.POST, instance=something) if leave_list_form.is_valid(): leave_list_form.save() context = { 'applications': applications } return render(request, 'home/applications.html', context) forms.py class LeaveListForm(forms.ModelForm): from_date = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) to_date = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) class Meta: model = LeaveList fields = [ 'user', 'reason', 'from_date', 'to_date', 'leave_status' ] -
How to implement LDAP login in Django without knowing the LDAP server info
I use python3.7 to develop a Django web app in AWS. Now need to use LDAP login. But due to security issue, we are only given an algorithms(md5 hash) used for Authorization. How to do the LDAP login in Django without knowing the URL of the LDAP server? -
How can I specify the correct schema format for Django to follow? "Error: Statement(s) could not be prepared. (8180)"
I get the following error when I try to run a database specific action within Django. ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'django_session'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") I must have missed a setting. By default, django sends incorrectly formatted SQL command strings, here's two examples of wrong formats. First one is when I try to log into the admin portal: SELECT TOP 1 (1) AS [a] FROM [django_session] WHERE [django_session].[session_key] = ? And when I try to load data from table called dbo.Testing: SELECT TOP 21 [TheAppName_testing].[id], [TheAppName_testing].[first_name], [TheAppName_testing].[last_name] FROM [TheAppName_testing] WHERE [TheAppName_testing].[id] = %s I use different schema's for several tables. How do I go about pointing django to the right settings so it can actually point to the correct tables within MS-SQL?