Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework translation does not work for me
I tried django rest framework internationalization. doc drf internationalization From official drf documentation a set this code in settings.py from django.utils.translation import gettext_lazy as _ MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware' ] LANGUAGE_CODE = "it" LANGUAGES = ( ('en', _('English')), ('it', _('Italian')), ('fr', _('French')), ('es', _('Spanish')), ) TIME_ZONE = 'UTC' USE_I18N = True but when I try out POST api rest curl -X 'POST' \ 'http://172.18.0.1:7000/appjud/api/v1/reset-password/' \ -H 'accept: application/json' \ -H 'Authorization: Token 014cb7982f31767a8ce07c9f216653d4674baeaf' \ -H 'Content-Type: application/json' \ -d '{ "new_password": "", "confirm_password": "" }' Response body [ { "newpassword": [ "This field is required." ], "confirmpassword": [ "This field is required." ] } ] Response headers allow: POST,OPTIONS content-language: en content-length: 91 content-type: application/json cross-origin-opener-policy: same-origin date: Sat,03 Dec 2022 16:14:16 GMT referrer-policy: same-origin server: WSGIServer/0.2 CPython/3.9.15 vary: Accept,Accept-Language,Origin x-content-type-options: nosniff x-frame-options: DENY As we can see it print "This field is required." but I would like "Questo campo è obbligatorio." What Does I miss in config settings.py file? -
How to redirect an authenticated (using Django) user to VueJS frontend?
I have a simple VueJS setup that involves some use of a router. This runs on one server. I also have a django backend project that runs on a second server. I would like for a django view to take my user to my vue frontend. What approach could I take to reach this? I have not yet made an attempt but if there is a specific part of my code I would need to show to get support then do let me know. I have consider the below SO post however it does not address my issue relating to what a view function would need to consist of. Setup django social auth with vuejs frontend -
Django Framework Not Picking Up Custom CSS
I am using Django Framework for my blog, however when I am trying to style my webpage, the classes are not being picked up. These are the images of my div with latest-articles class: As you can see from the next image, the HTML recognises the class as display: block; However, my CSS clearly states that it is of display: block; This is my CSS code: .latest-articles { /* dont think this class is being picked up */ display: flex; flex-wrap: wrap; flex-direction: row; justify-content: center; align-items: center; padding-top: 0; text-align: center; position: relative; padding: 10px; } Other CSS changes I have made previously have worked so I am unsure as to why this does not work. Any additional information can be provided, and any help is greatly appreciated. -
Doubt_on_django _json_data
How to pass emp.json file data into django database? I tried that how to dump data for django database to .json file and I am expecting clear step by step answer for my question i.e, How to pass emp.json file data into django database? -
My Query set is returning empty List even there are users in the db
Below listed are my Model, View, and Serializer classes. I am making a admin dashboard where admin can create users, list them, and search a user by ID. Users are being created successfully but the GET request for listing & searching returns an empty list even where there are users present in the Database. My Model Classes: class MyAccountManager(BaseUserManager): def create_user(self,email,username,first_name,last_name, age, password=None): if not email: raise ValueError("Users must have email address") if not username: raise ValueError("Users must have username") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, age=age, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,username,email,first_name,last_name,age,password): user = self.create_user( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, age=age,) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name="email",max_length=60,unique=True) username = models.CharField(max_length=30,unique=True) date_joined = models.DateTimeField(verbose_name='date joined',auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login',auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField (max_length=60) last_name = models.CharField(max_length=60) age = models.DateField(default=datetime.date.today) profile_pic = models.ImageField(upload_to='image',blank=True,null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','first_name','last_name','age'] objects = MyAccountManager() def __str__(self): return self.username + "," +self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True My Serializer Class: class UserSerializer (serializers.ModelSerializer): class Meta: model = User fields = ['username','first_name','last_name','email','age','is_active'] read_only_fields = ('email',) … -
Django registration form gives error, when password can not pass validation
I am trying to make user refistration, with automaticaly login. And it works. But when passwords are different, or do not pass validation, there is no message from the form, it throws error: AttributeError at /accounts/register/ 'AnonymousUser' object has no attribute '_meta' I think the error comes from the login(request, self.object) line. But I am not sure what to do, so it works as needed. Thank you in advance. I hope someone can help me. my model: class AppUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): email = models.EmailField( unique=True, blank=False, null=False, ) is_staff = models.BooleanField( default=False, blank=False, null=False, ) USERNAME_FIELD = 'email' objects = AppUserManager() my form: class SignUpForm(auth_forms.UserCreationForm): class Meta: model = UserModel fields = (UserModel.USERNAME_FIELD, 'password1', 'password2',) field_classes = { 'email': auth_forms.UsernameField, } my view: class SignUpView(views.CreateView): template_name = 'accounts/user/register-user-page.html' form_class = SignUpForm success_url = reverse_lazy('home') def post(self, request, *args, **kwargs): response = super().post(request, *args, **kwargs) login(request, self.object) return response I have tried to fix the problem with overriding the clean() method in the form, but it did not work. -
Adding help text to a django from
I want to add help text/tool tip when a user hovers over a form field. I have a model form based on this model: class MyModel(TimeStampedModel): MY_CHOICES = [tuple([x,x]) for x in range(1,8)] p1 = models.IntegerField("P1”, default='1', help_text=‘text1’) p2 = models.IntegerField(“P2”, default=‘1’, , help_text=‘text2’) Parent = models.ForeignKey(ParentModel, on_delete=models.CASCADE) The form itself looks like: class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'id-CaseForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_tag = False self.helper.help_text_inline = False self.helper.form_show_labels = False self.helper.layout = Layout( Row(Field(PrependedText('p1', ‘field_label1’, wrapper_class='col-12 col-lg-6 pe-0 stretchprepend'))), Row(Field(PrependedText('p2’, ‘field_label2’, wrapper_class='col-12 col-lg-6 pe-0 stretchprepend’)))) CHOICES = [tuple([x,x]) for x in range(1,8)] p1 = IntegerField( label='field_label1', widget=Select(choices=CHOICES)) p2 = IntegerField( label='field_label2’, widget=Select(choices=CHOICES)) class Meta: model = MyModel fields = ['p1', 'p2’,] And this is displayed as a crispy form in the template: {% crispy MyModelForm %} I want the user to see some help text when they hover over the fields. This help text could be the help_text from the model, or I am happy to put it somewhere else (although it should go in either the model or the form, not in the template). Any help appreciated. -
How should queryset be set for related fields
I have two models named book and chapter. each book can have many chapters, so models are like: class Book(models.Model): title = models.CharField(max_length=100) class Chapter(models.Model): title = models.CharField(max_length=100) book = models.ForeignKey("books.Book", on_delete=models.CASCADE) and serializers are like: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ["title"] class ChapterSerializer(serializers.ModelSerializer): book = serializers.PrimaryKeyRelatedField(queryset=Book.objects.all()) class Meta: model = Chapter fields = ["title", "chapter_number", "text", "book"] So my question is here: Is it OK to set queryset=Book.objects.all()) for related field? I mean, if the number of books gets bigger, wouldn't be any problem to query all the books to set the right book? -
How to return value from api in function Django
Does anyone know how I can return the value of the api in this function, so I can use this value to save in the database. def cart_sessionid(request): url = f"https://ws.sandbox.pagseguro.uol.com.br/v2/sessions?email={email}&token={token}" payload = "" headers = {} response = requests.request("POST", url, headers=headers, data=payload) return response.text I need to be able to call the cart_sessionid function this way with the value that the api is returning: cart = Cart.objects.create(cart_id=cart_sessionid(request)) I tried that way but it didn't work. -
Django acting weird on Windows server IIS deployment
I have the following view which allows me to save the information of a multi step application. def saveNewApplication(request, *args, **kwargs): educationList = [ val for val in pickle.loads(bytes.fromhex(request.session['education'])).values() ] basicInfoDict = pickle.loads(bytes.fromhex(request.session['basic_info'])) documentsDict = pickle.loads(bytes.fromhex(request.session['documents'])) applicant, created = ApplicantInfo.objects.update_or_create( applicantId=request.session['applicantId'], defaults={**basicInfoDict} ) if created: #saving the diplomas for education in educationList: Education.objects.create(applicant=applicant, **education) with open(f"{documentsDict['cv_url']}/{request.session['file_name']}", 'rb') as f: Documents.objects.create( applicant=applicant, cv =File(f, name=os.path.basename(f.name)), langue_de_travail = documentsDict['langue_de_travail'] ) #remove the temporary folder shutil.rmtree(f"{documentsDict['cv_url']}") else: educationFilter = Education.objects.filter(applicant=applicant.id) for idx, edu in enumerate(educationFilter): Education.objects.filter(pk=edu.pk).update(**educationList[idx]) #updating the documents document = get_object_or_404(Documents, applicant=applicant.id) if documentsDict['cv_url']: with open(f"{documentsDict['cv_url']}/{request.session['file_name']}", 'rb') as f: document.cv = File(f, name=os.path.basename(f.name)) document.save() document.langue_de_travail = documentsDict['langue_de_travail'] document.save() languagesDict = pickle.loads(bytes.fromhex(request.session['languages'])) Languages.objects.update_or_create(applicant=applicant, defaults={**languagesDict}) if 'experiences' in request.session and request.session['experiences']: experiencesList = [ pickle.loads(bytes.fromhex(val)) for val in request.session['experiences'].values() ] Experience.objects.filter(applicant=applicant.id).delete() for experience in experiencesList: Experience.objects.create(applicant=applicant, **experience) return JsonResponse({'success': True}) In the development it works perfectly but if deployed I am getting a 404 raise by this line get_object_or_404(Documents, applicant=applicant.id) meaning the creating is false. and I can't figure why is that. The weirdest thing is if I do comment the entire else block it also returns a 500 error but this time it I do click in the link of the console it … -
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