Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to run migration from PostgreSQL to sqlite3
currently I am using PostgreSQL database in my project but I also want to use SQLite for localhost, so I want to run migrate command but there are errors because in SQLite array field is not used so I want to convert array field to JSONfield and makemigrations but in migrations old migrations also present. S I want to write custom logic in migrations. So, it use old migrations when database is PostgreSQL and new migrations when it is sqlite3. I don't want create new migrations and migration table every time I switch databases. -
OSError: cannot load library 'gobject-2.0-0' when deploying to railway
I keep getting this error when I want to deploy to railway from . import views File "/app/account/views.py", line 2, in <module> from weasyprint import HTML, CSS File "/opt/venv/lib/python3.10/site-packages/weasyprint/__init__.py", line 336, in <module> from .css import preprocess_stylesheet # noqa isort:skip File "/opt/venv/lib/python3.10/site-packages/weasyprint/css/__init__.py", line 25, in <module> from . import computed_values, counters, media_queries File "/opt/venv/lib/python3.10/site-packages/weasyprint/css/computed_values.py", line 9, in <module> from ..text.ffi import ffi, pango, units_to_double File "/opt/venv/lib/python3.10/site-packages/weasyprint/text/ffi.py", line 398, in <module> gobject = _dlopen( File "/opt/venv/lib/python3.10/site-packages/weasyprint/text/ffi.py", line 385, in _dlopen return ffi.dlopen(names[0]) # pragma: no cover File "/opt/venv/lib/python3.10/site-packages/cffi/api.py", line 150, in dlopen lib, function_cache = _make_ffi_library(self, name, flags) File "/opt/venv/lib/python3.10/site-packages/cffi/api.py", line 832, in _make_ffi_library backendlib = _load_backend_lib(backend, libname, flags) File "/opt/venv/lib/python3.10/site-packages/cffi/api.py", line 827, in _load_backend_lib raise OSError(msg) OSError: cannot load library 'gobject-2.0-0': gobject-2.0-0: cannot open shared object file: No such file or directory. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0' It works perfectly on my localhost and also in heroku when I first deployed to heroku. But now, I want to migrate to railway due to the end of heroku's free service but that error keeps coming. -
HyperlinkModelSerializers not rendering with nested models
I have a user and group model which comes by default with Django. I am trying to show the group nested in users. when I use serializers.ModelSerializer it works fine, but in order to add the URL, I updated it to serializers.HyperlinkedModelSerializer and then it gives the following error: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. Model Code class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('id', 'name', 'url') class UserSerializer(serializers.HyperlinkedModelSerializer): groups = serializers.PrimaryKeyRelatedField(many=True, queryset=Group.objects.all()) class Meta: model = get_user_model() fields = ('id', 'email', 'password', 'name', 'is_active', 'is_verified', 'groups', 'url') def create(self, validated_data): groups_data = validated_data.pop('groups') user = get_user_model().objects.create(**validated_data) for group_data in groups_data: user.groups.add(group_data) return user def to_representation(self, instance): rep = super(UserSerializer, self).to_representation(instance) rep.update({ 'groups': GroupSerializer(many=True).to_representation(instance.groups) }) return rep With serializers.ModelSerializer I get the output below, but how can I add a URL with both the user and group? { "id": 4, "email": "admin3@admin.com", "password": "12345678", "name": "admin3", "is_active": false, "is_verified": false, "groups": [ { "id": 1, "name": "test" } ] }, -
Service Error 503 coming when testing google calendar api in Django Framework
I am trying to develop a to do notes app in django framework. And I want to integrate Google Calendar Api with this project to sync tasks with google calendar. I followed the steps from this website: https://blog.benhammond.tech/connecting-google-cal-api-and-django#comments-list But when I try to test the demo page of website, it shows Service Error 503. Please let me kindly know how to fix the problem! I only know some basics of django. Here's my calendar API Code- from decouple import config from google.oauth2 import service_account import googleapiclient.discovery import datetime import json CAL_ID = "104a92a3cd198c2062645e570737318d05c2dfb2f1361e64b743a4b0e223de66@group.calendar.google.com" SCOPES = ['https://www.googleapis.com/auth/calendar'] SERVICE_ACCOUNT_FILE = json.load(open('google-credentials.json')) def test_calendar(): print("RUNNING TEST_CALENDAR()") credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) service = googleapiclient.discovery.build( 'calendar', 'v3', credentials=credentials) print(service) # CREATE A NEW EVENT new_event = { 'summary': "New Task 1", 'location': 'Kolkata, WB', 'description': 'Description of Task 1', 'start': { 'date': f"{datetime.date.today()}", 'timeZone': 'America/New_York', }, 'end': { 'date': f"{datetime.date.today() + datetime.timedelta(days=3)}", 'timeZone': 'America/New_York', }, } service.events().insert(calendarId=CAL_ID, body=new_event).execute() print('Event created') # GET ALL EXISTING EVENTS events_result = service.events().list( calendarId=CAL_ID, maxResults=2500).execute() events = events_result.get('items', []) # LOG THEM ALL OUT IN DEV TOOLS CONSOLE for e in events: print(e) # uncomment the following lines to delete each existing item in the calendar #event_id = e['id'] … -
how to create dynamic database table using csv file in django or DRF
I am going to create a database table using csv file without model in django. Steps are: after sending csv file by post request, one database table will be created according to csv headers (name, university, score, total_score etc). And it will be populated using csv file data. Database table name should be derived from csv file name. I searched but couldn't find good solution. Any help is appreciated. Below is my code to read csv file class UploadProductApiView(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] decoded_file = file.read().decode() # upload_products_csv.delay(decoded_file, request.user.pk) io_string = io.StringIO(decoded_file) reader = csv.reader(io_string) for row in reader: print(row) -
Could not resolve URL for hyperlinked relationship using view name "user-detail"
Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Serializer.py from .models import Post from rest_framework import serializers class PostSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='user-detail', source='profile',) class Meta: model = Post fields = ['url', 'title', 'slug', 'author', 'updated_on', 'content', 'created_on', 'status'] Models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0, "Draft"), (1, "Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title blog/urls.py from rest_framework import routers from django.urls import path, include from . import views router = routers.DefaultRouter() router.register(r'post', views.PostList) urlpatterns = [ path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls')), path('', views.PostList.as_view({'get': 'list'}), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] Project structure: enter image description here I've been sitting on this problem for a long time, I can not solve it in any way. There are already several questions on stackowerflow with this error but none helped me -
Doing data validation after saving the object in a atomic transaction. Django and PostgreSQL
The current flow I use is this: # Here there is long and complicated verification to check that the submitted data is valid, # involving lots of calculations and queries. with transaction.atomic(): # save the submitted data But instead I could do def saved_data_is_valid(): # some short and simple calculations. ... # skip the validation before saving data. with transaction.atomic(): # save the submitted data in the database without commiting it. if not saved_data_is_valid(): raise Exception("Some exception so the transaction will roll back") I wonder what the performance hit for the database will be with all the dead rows this will create, considering that AUTOVACUUM is ON, and default_transaction_isolation is read committed. Also considering that the submitted data is in most cases valid. -
ImproperlyConfigured AUTH_USER_MODEL refers to model 'core.User' that has not been installed
I am calling this method in my core app - models.py, from django.contrib.auth import get_user_model User = get_user_model() I am getting error, Exception has occurred: ImproperlyConfigured (note: full exception trace is shown but execution is paused at: <module>) AUTH_USER_MODEL refers to model 'core.User' that has not been installed debugger points to this line -
Json request while using multiprocessing
Hi I am trying to use JSON to provide data so I can use it in my python script. I am still new to coding so been struggling with this issue. def wallet_verify(listi): database = Bybitapidatas.objects.filter(user = listi) I want to use request in here but then I get errors. Normally request is my only argument so then it works but now I am using Listi as well so that I can get an ID that I use to loop through while doing multiprocessing. what I am trying to achieve is this. def wallet_verify(listi,request): data=json.loads(request.body) print(data) database = Bybitapidatas.objects.filter(user = listi) Any help would be appreciated thanks. -
How to get data from the model
I need to get data from a model in Django. I specify filtering, an error occurs. I'm doing a project with TV series and movies. When clicking on any of the listed categories, I need to take data from this category. That is, which films belong to this category. enter image description here enter image description here I am trying to fix this problems but it didnt help me -
"int_list_validator" is not working in Django forms
I made the following Django form. from django.core.validators import int_list_validator class RoomForm(forms. Form): room_numbers = forms.CharField(validators=[int_list_validator], required=False, max_length=4000) In this form even if I submit a string like 'hello' the form gets submitted. I mean I can get the value 'hello' in views.py. I don't understand why because "int_list_validator" should not allow it. -
Django Slugify Not Showing Turkish Character
I wanna make business directory and i made category model here at the below. class FirmaKategori(models.Model): kategori = models.CharField(max_length=250) description = models.CharField(max_length=5000) slug = models.SlugField(max_length=250, null=False, unique=True, allow_unicode=True) def __str__(self): return self.kategori def get_absolute_url(self): return reverse('firma-kategori-ekle') def save(self, *args, **kwargs): self.slug = slugify(self.kategori, allow_unicode=False) super().save(*args, **kwargs) I made this, and if i allow_unicode=True, Forexample i made a category its name is Takım Tezgahları, became takım-tezgahları, but i want takim-tezgahlari Varyation 1: When i delete all allow_unicode=True tags, result is Category name = Ulaşım Sektörü Slug link: ulasm-sektoru Varyation 2: When i make all allow_unicode=True tags, result is Category name = Ulaşım Sektörü Slug link: ulaşım-sektörü I want ulasim-sektoru How can i solve this. -
How to create django media sub path with filebrowser
When uploading a media file through filebrowser in django-tinymce, I want to create a new folder under the upload folder based on the uploaded date (like ckeditor). For example, if you upload the abc.png file on December 3, 2022, I want to keep the path of [/{django-project}/media/upload/2022/12/3/abc.png], not [/{django-project}/media/abc.png]. I know that the file name can be edited by using the signals of the filebrowser, but I don't know how to change the file path. For example, if you upload the abc.png file on December 3, 2022, I want to keep the path of [/{django-project}/media/upload/2022/12/3/abc.png], not [/{django-project}/media/abc.png]. Is it possible to do this without modifying the module source files? -
How do i loop through the fields of a form in python?
I am trying to find out how "complete" a users profile is as a percentage. I want to loop through the fields of a form to see which are still left blank and return a completion percentage. My question is how do I reference each form value in the loop without having to write out the name of each field? Is this possible? completeness = 0 length = 20 for x in form: if form.fields.values[x] != '': completeness += 1 percentage = (completeness / length) * 100 print(completeness) print(percentage) -
What the type of timefield in django-ninja schema
in my model i have time = models.DateTimeField() and i put the type in my shcema : from datetime import date, time class BookingOut(Schema): user_id: int doctor_id: int date: date time: time to get the data but the django didn't accept this format for the time but accept it in the date this the error what should i put for the time i searched alot and didn't get anything useful plz help me -
Adding a search cum input bar in Django
creating an inventory management system for an automobile business. Need a search cum input bar, on a form, that allows for the input as well as searching on the database behind it. For example, if i type "hyundai", it should give me drop down of the Hyundai cars already available but if i type "hyundai sonata", i should be able to enter that value and submit the form even if there's nothing with that name in the database. I'm, working with Django Python I have tried creating a separate field for the input of any new value, and then a different bar that drops down all values from the database. The problem here is that for the car to show up on the drop down, it needs to be first added to the database through a different field which isnt that seamless. I'm a 3rd semester data science student therefore my description might be a bit off but do let me know if more details are needed. Even if i can get the actual name of these search cum input bars, it would be really helpful. Thank you in advance -
Integrate Odoo 15 with Django
I'm trying to build a Django REST API Project by retrieving data from Odoo, for that I need first of all to connect to odoo database. Any idea of how to do that !? -
Django Rest API ordering filters for custom serializer method
I will ordering product in "total_price" values. But my database does not contain a "total_price" value. I then produce in serializer like this: total_price = serializers.SerializerMethodField('get_total_price') def get_total_price(self,instance): price = instance.sell_price - instance.discount_price return price my rest api class: class ProductList(generics.ListAPIView): serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] ... ordering_fields = ['created_date', 'sell_price'...] ... My error page: FieldError at /api/product/ Cannot resolve keyword 'total_price' into field. Choices are:sell_price,discount_price .... -
How to use tag in django without using any 3rd partly library
One or more tags that the user can add to the entry i. A user can set this while creating a new entry. A user can also change this while updating an existing entry. Multiple tags can be added to the same entry,, how to using this in django models* How to implement tags -
How to add multiple image upload functionality in Django form.Imagefield()?
How to allow users to upload multiple images through Django Forms, which was fetched in Django template by using form.ImageField() it was providing the following output: <input type="file" name="image" accept"Image/*" id="id_image"> This is allowing to upload only one image, But need to provide multiple upload option. But I need the following output using Django Form with my custom class <input type="file" multiple accept"Image/*" id="id_image" class="myclass1 myclass2"> How can I achieve this? -
Request from server returns HTTP 403 but request from local machine returns HTTP 200
I'm facing pretty much what the title says. I have an Ubuntu server running 20.04.5 LTS running a Django application. I'm using the requests module to send API requests. However, whenever I try a request from the server - either from the application or a separate Python script or even cURL - I always get a 403 Forbidden response. But if I run the same command from my local machine - cURL/Postman/script - I get a 200 Response. The requests code is import requests headers = { 'Content-Type': 'application/json', } body = { /*Stuff related to authentication*/ } token_url = 'https://example.com/token' print("Attempting to get access token using the REQUESTS http module:") response = requests.post(token_url, json=body, headers=headers) print("Request Data:\n") print(f"Request Headers: {response.request.headers}") print(f"Response HTTP Status: {response.status_code}\nResponse body is {response.text}") Obviously, example.com isn't really the endpoint I'm attempting to hit up. The corresponding output from my server is Attempting to get access token using the REQUESTS http module: Request Data: Request Headers: {'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Content-Length': '226'} Response HTTP Status: 403 Response body is Response content b'' I've been facing this issue since I updated my server about 2-3 days ago. requests suddenly has … -
how to solve Textblob import Exception in Django views
how to solve Textblob import Exception in Django views from textblob import TextBlob Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Zain Ul Abideen\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\Zain Ul Abideen\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "E:\small tools\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "E:\small tools\venv\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "E:\small tools\venv\lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( File "E:\small tools\venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "E:\small tools\venv\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "E:\small tools\venv\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "E:\small tools\venv\lib\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: File "E:\small tools\venv\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "E:\small tools\venv\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "E:\small tools\venv\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "E:\small tools\venv\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Zain Ul Abideen\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module … -
How to connect to mariadb5.5.52 using python3
My development environment python3.8 mariadb 5.5.52 pymysql 1.0.2 django 4.1.3 try to migrate but vscode tips django.db.utils.NotSupportedError: MariaDB 10.3 or later is required (found 5.5.52). -
DRF parses number array as string array
When I make a POST request from JavaScript to my Django Rest Framework backend, my array of numbers is interpreted as a list of strings on the backend, causing this error: cargo: ["Incorrect type. Expected pk value, received str."] This is how I make the request in JavaScript: const data = new FormData(); data.append("cargo", JSON.stringify([1, 2])); fetch(url, {method: "POST", body: data}).then(//<more code> In my Django Rest Framework serializer, I define the cargo field like this: cargo = serializers.PrimaryKeyRelatedField( many=True, queryset=models.CustomCargo.objects.all() ) I post an array of numbers but DRF thinks it's an array of strings so I get an error because it's expecting integers (PrimaryKeyRelatedField). I need to use multipart/form-data because I'm posting a file too, so I can't use application/json, which does work. Is there a way to fix this in the JavaScript code (I'd rather not convert strings to integers on the backend)? -
How do we solve the quotation inside of a quotation problem while using django in my HTML file?
I can't use the same type of string in the same type of string in HTML I have a static folder in the root dierctory of my django project and I was changing a downloaded template's link to match the django project. Here is the HTML attribute style="background-image: url("{% static 'assets/img/why-us.png' %}")" as you can see I tried using backslash () to resolve the problem but it was no avail.