Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery Periodic Task not working on given crontab params
I need to perform some background tasks in Django at a particular time so I'm using @periodic_task in my tasks.py file. Basically I have two tasks: @periodic_task(run_every=(crontab(day_of_month='3-11', hour=11, minute=32)), name="invoice_simulation", ignore_result=False) def invoice_simulation(): print('---- task started-----') # Do something @periodic_task(run_every=(crontab(minute='*')), name="print_time_worker", ignore_result=False) def print_time(): print('Current time is: ', datetime.now()) On my local, everything is running properly but when I push my code to the server then only print_time() works and invoice_simulation is not working on the server. My code is deployed on Heroku after deployment celery logs on server look like... 2018-01-03T11:30:06.648963+00:00 app[worker.1]: 2018-01-03T11:30:06.648975+00:00 app[worker.1]: -------------- celery@73b10f01-6293-42ad-a0f5-867e4b39f43d v3.1.18 (Cipater) 2018-01-03T11:30:06.648976+00:00 app[worker.1]: ---- **** ----- 2018-01-03T11:30:06.648977+00:00 app[worker.1]: --- * *** * -- Linux-3.13.0-133-generic-x86_64-with-debian-jessie-sid 2018-01-03T11:30:06.648977+00:00 app[worker.1]: -- * - **** --- 2018-01-03T11:30:06.648978+00:00 app[worker.1]: - ** ---------- [config] 2018-01-03T11:30:06.648979+00:00 app[worker.1]: - ** ---------- .> app: __main__:0x7f8608f52358 2018-01-03T11:30:06.648980+00:00 app[worker.1]: - ** ---------- .> transport: redis://h:**@ec2-****.compute-1.amazonaws.com:17709// 2018-01-03T11:30:06.648981+00:00 app[worker.1]: - ** ---------- .> results: redis://h:*@ec2-****.compute-1.amazonaws.com:17709 2018-01-03T11:30:06.648981+00:00 app[worker.1]: - *** --- * --- .> concurrency: 8 (prefork) 2018-01-03T11:30:06.648982+00:00 app[worker.1]: -- ******* ---- 2018-01-03T11:30:06.648983+00:00 app[worker.1]: --- ***** ----- [queues] 2018-01-03T11:30:06.648983+00:00 app[worker.1]: -------------- .> celery exchange=celery(direct) key=celery 2018-01-03T11:30:06.648984+00:00 app[worker.1]: 2018-01-03T11:30:06.648984+00:00 app[worker.1]: 2018-01-03T11:30:06.648985+00:00 app[worker.1]: [tasks] 2018-01-03T11:30:06.648986+00:00 app[worker.1]: . djcelery_email_send_multiple 2018-01-03T11:30:06.648986+00:00 app[worker.1]: . invoice_simulation 2018-01-03T11:30:06.648987+00:00 app[worker.1]: . mdn_core_engine.celery.debug_task 2018-01-03T11:30:06.648987+00:00 app[worker.1]: . … -
Django Rest Framework drop fields based on request url
I have a ModelViewSet that exposes a contacts relation which is an extensive list of emails. class EmailSerializer(serializers.ModelSerializer): contacts = EmailContactSerializer(many=True, read_only=True) class Meta: model = Email fields = ('id','contact_count', 'contacts') class EmaiViewSet(viewsets.ModelViewSet): serializer_class = EmailSerializer If I visit the url api/emails I get a nice list of Emails with all it's contacts. My problem is that visiting this url is slow because of all the contacts it needs to retrieve for every Email instance. Now I want this detailed contact list to be available when requesting api/emails/<email_id>. What can I do in DRF to drop the contacts field when listing Emails ? -
How can I pass a python variable from html file to an external js file?
I am seperating my js in my html file to an external js file. In that case how can I pass my uid which is obtaining on session? I have ajax requests and i move all this to external js file? My external js (su.js) file now is submitBox = new Vue({ el: "#submitBox", data: { name: '', authType: 'authType', email: 'email', }, methods: { handelSubmit: function(e) { var vm = this; data = {}; data['name'] = this.name; data['email'] = this.nemail; data['auth-token'] = this.authType; $.ajax({ url: 'http://127.0.0.1:8000/alpha/add/post/', data: data, type: "POST", dataType: 'json', success: function(e) { if (e.status) { alert("Success") vm.pid=e.pid; } else { alert("Registration Failed") } } }); return false; }, }) In my html file (submit.html) i store the values of authType as <script> var authType = '{{uid}}'; </script> my views.py is @csrf_exempt def submit(request): if('is_logged_in' in request.session): id = request.session['authToken']; return render(request,"submit.html",{'uid':id}); else: return render(request,"submit.html",{}); So, how can I pass the value of authType to external js (su.js) file. It is using vue.js. Can anybody please help to obtain the result for me? -
How to update permission in Groups from Django without using admin
I would like to add/remove permissions to a particular group without the help of admin. I know how to update it with the help of admin, but I would like to change the permission programatically. django-admin -
Django REST - input of some form fields occure twice on the backend
Does anybody had the same problem? Some users' inputs are sent to the backend twice. Data are stored in JSON's object. Key-value schema doesn't trigger the problem. What users action can trigger this kind of problem? It doesn't happen every time, but only for some of the users. -
Django not print a user perms [on hold]
from django.contrib.auth.models import Permission permissions = Permission.objects.filter(user=request.user) for property, value in vars(permissions).iteritems(): print property, ": ", value and i get the following result How could i get the result from the above query ? -
Running Django management command on gae
Good day. How do I run py manage.py migrate On my Google app engine instance And how to run Django admin site after deploying. I've checked the tutorials online and most are not very clear -
Unit Testing a Django Form with a ImageField without external file
djang version: 1.11, python version: 3.6.3 I found this stackoverflow question: Unit Testing a Django Form with a FileField and i like how there isn't an actual image/external file used for the unittest, however i tried this approaches: from django.test import TestCase from io import BytesIO from PIL import Image from my_app.forms import MyForm from django.core.files.uploadedfile import InMemoryUploadedFile class MyModelTest(TestCase): def test_valid_form_data(self): im_io = BytesIO() # BytesIO has to be used, StrinIO isn't working im = Image.new(mode='RGB', size=(200, 200)) im.save(im_io, 'JPEG') form_data = { 'some_field': 'some_data' } image_data = { InMemoryUploadedFile(im_io, None, 'random.jpg', 'image/jpeg', len(im_io.getvalue()), None) } form = MyForm(data=form_data, files=image_data) self.assertTrue(form.is_valid()) however, this always results in the following error message: Traceback (most recent call last): File "/home/my_user/projects/my_app/products/tests/test_forms.py", line 44, in test_valid_form_data self.assertTrue(form.is_valid()) File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 183, in is_valid return self.is_bound and not self.errors File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 175, in errors self.full_clean() File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 384, in full_clean self._clean_fields() File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py", line 396, in _clean_fields value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py", line 423, in value_from_datadict upload = super(ClearableFileInput, self).value_from_datadict(data, files, name) File "/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py", line 367, in value_from_datadict return files.get(name) AttributeError: 'set' object has no attribute 'get' why? I understand that .get() is a dictionary method, but i fail to see … -
It's slow to send email by the default EmailBackend of django 1.11 using Microsoft business email account
I'm using the default EmailBackend of Django 1.11, I just simply called the send_mail method as the ref. document said, here are my settings of the SMTP server: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'oalite@xxx.com' EMAIL_HOST_PASSWORD = 'xxxxx' EMAIL_SUBJECT_PREFIX = '[Irixi OALite Admin]' Here is my log outputted by smtplib.py: reply: b'250-CHUNKING\r\n' reply: b'250 SMTPUTF8\r\n' reply: retcode (250); Msg: b'SG2PR06CA0180.outlook.office365.com Hello [85.203.47.85]\nSIZE 157286400\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\nAUTH LOGIN XOAUTH2\n8BITMIME\nBINARYMIME\nCHUNKING\nSMTPUTF8' send: 'AUTH LOGIN b2FBaXRl0GlyaXhpLmNvb0==\r\n' reply: b'334 UGFzc3dvcmQ6\r\n' reply: retcode (334); Msg: b'UGFzc3dvcmQ6' send: 'QEdBbH1w0DJuSwY=\r\n >>>>>>>>>>>>>>>>>> halted here for about 15s to wait the reply <<<<<<<<<<<<<<<<<<< reply: b'235 2.7.0 Authentication successful target host BLUPR04MB420.namprd04.prod.outlook.com\r\n' reply: retcode (235); Msg: b'2.7.0 Authentication successful target host BLUPR04MB420.namprd04.prod.outlook.com' send: 'mail FROM:<oalite@xxx.com> size=943\r\n' reply: b'250 2.1.0 Sender OK\r\n' reply: retcode (250); Msg: b'2.1.0 Sender OK' send: 'rcpt TO:<user.foo@xxx.com>\r\n' reply: b'250 2.1.5 Recipient OK\r\n' Please note that I was using the business email account of Microsoft, the domain xxx.com actually is our company domain name. Thanks for your help! -
Refresh div content after ajax request jQuery (JUST SIMPLY REFRESH LIKE F5)
Firstly, I know, I'll get many diss for this post, but whatev. I have searched everywhere, and everywhere is told about refreshing div by special content, nothing about simply refreshing. I've just send my form by POST in django (saving some data), and after that saving, I want refresh list within modal, but without refreshin whole page. Do I have to specify the whole path to modal etc. ? Is there jQuery command like F5 button but not to whole page, only a div? My code I'm working with: $(function(){ $('#js-submit-create-adres').on('click', function (e) { var form = $('#create-adres'); var _czy = ''; if ($('#id_czy_domyslny option:selected').text() == 'Tak') { _czy = 'True'; } else { _czy = 'False'; } $.ajax({ url: form.attr('data-url'), type: 'post', dataType: 'json', data: { ulica: $('#id_ulica').val(), kod_pocztowy: $('#id_kod_pocztowy').val(), miasto: $('#id_miasto').val(), kontrahent: $('#id_kontrahent').val(), czy_domyslny: _czy, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(msg){ if(msg.result == 'done') { if(_czy == 'True'){ $('#kontrahent-adres').text(nowy_adres); } alert('saved'); $('#id_ulica').val(''); $('#id_kod_pocztowy').val(''); $('#id_miasto').val(''); // HERE I WANT TO RELOAD DIV NAMED '#name' } } }) }) }) -
email as username, case-sensitive email address
I use email address as a username in my Django application USERNAME_FIELD = 'email' but email field is case-sensitive so: test@example.com and TEST@EXAMPLE.COM are saved as two different users. It's normal or should I validate this somehow? -
How would you set up a django live project with git on a private server using gunicorn and nginx?
Is it possible to create a git project in a current live Django project and develop on it locally after a pull(or clone?) and push changes up again to have it automatically deploy? -
Django Translation vs Jquery
I'm developing multilingual website using django platform. Due to this, I have next question: What is better, to use django translations(translate using ugettext, locale and etc..) or using Jquery(add button with click function). I know, that I'll need to write both in django(msgid, msgstr(hand-written translation)) and in Jquery(hand-written json languages or depending on method). P.s I need 3+ languages. -
How to work around deprecated "include" in Django 2?
In particular, I am trying to find the equivalent solution for url(r'^accounts/', include('allauth.urls')), in Django 2. I have tried a number of different things, including custom views (which do work, but I have to create one for each purpose..unlike what I had to previously do). Is there an equivalent one liner in Django2? Thanks! -
why I don't get clean data when i use cleaned_data
I'm trying to create a login form for my site but when I use cleaned_data in my views.py I don't get the right data. here is my code: views.py def login_page(request): form = LoginForm(request.POST or None) context = { 'form': form } if form.is_valid(): print(form.cleaned_data) username = form.cleaned_form.get("username") password = form.cleaned_form.get("password") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("/") else: print("Error") return render(request, "auth/login.html", context) forms.py class LoginForm(forms.Form): username = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control", "placeholder": "Username" } ) ) password = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control", "placeholder": "Password" } ) ) login.html <form action="POST">{% csrf_token %} {{ form }} <button type="submit" class="btn btn-default">Submit</button> </form> and here is what I get when I fill username and password field and click on submit. print(form.cleaned_data) shows there is data in url fields that I want to use but I can't access them. console -
@detail_route: object has no attribute - Django Rest Framework
I get an issue about @detail_route. Hope your guys helps! This is my viewsets. I use decorators to import detail_route My viewsets: class PhotoUpdateSerializer(ModelSerializer): class Meta: model = Photo fields = [ 'image', 'is_public', 'caption' ] class UploadAvatarPhotoAPIView(ReadOnlyModelViewSet): serializer_class = PhotoUpdateSerializer queryset = Photo.objects.all() @detail_route(methods=['POST']) def upload_avatar(self, request, username): avatarqs = Photo.objects.create( user=self.request.user, caption=self.caption, image=self.image, is_public=self.is_public ) serializer = PhotoUpdateSerializer(avatarqs) return Response(serializer.data) Error: 'UploadAvatarPhotoAPIView' object has no attribute 'caption' I think 3 lines are error: caption=self.caption, image=self.image, is_public=self.is_public -
Django cannot delete cookie and session after logout, cahing on nginx level, auth system not work?
nginx cahing everything, if I login to the system, then I can no longer exit it until the caching expires, since I'm Logout from the account, i need to know how to delete cookies and session, DJANGO !? -
ModuleNotFoundError: No module named 'rest_framework' I already installed djangorestframework
I got an error,ModuleNotFoundError: No module named 'rest_framework' when I run command python manage.py runserver . Traceback says Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x108193ae8> Traceback (most recent call last): File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Users/xxx/anaconda/envs/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' I already run command pip3 install djangorestframework,when I run this command again, Requirement already satisfied: djangorestframework in /usr/local/lib/python3.6/site-packages shows in terminal.Python version is 3.6.2.What is wrong in my code?How should I fix this?I use Anaconda virtual environment. -
Django allauth custom template not hashing passwords
I am using my own custom view and inheriting from SignupView in (from allauth.account.views import SignupView) I also am using my own forms.py to pass on to my custom view. It is signing up the user just fine, but one thing it's not doing is hashing the passwords. It's saving the passwords for the user the way it is. How can I make it so that the passwords are stored in the table as a hash? forms.py from .models import User from django import forms class RegisterForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'})) email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'})) password = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'})) views.py from allauth.account.views import SignupView from .forms import RegisterForm class RegisterView(SignupView): form_class = RegisterForm template_name = 'oauth/auth_form.html' project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('oauth.urls')), //app name I created where my custom sign up view is url(r'^profiles/', include('profiles.urls')), url(r'^accounts/', include('allauth.urls')), ] -
How to make it an integer?
in view.py: return redirect('/website/detail/{0}/'.format(pk)) in urls.py: url(r'^detail/(?P<pk>\d+)/$',views.productDetailView,name='productDetailView'), pk is integer type but when I am passing it through '/website/detail/{0}/'.format(pk) this is becoming string. So I am getting this error: TypeError at /website/detail/1/ must be real number, not str I can solve it changing the url pattern. But I don't want that. So how can I pass pk as integer? -
cannot Login with credentials, that was used in signup form in django.
I have created a simple signup and login form for a web application. I was able to perform the sign up, but when I tried to login the user, using the credentials that I used during signup, it is not logging in. Only the users which are created using django- admin create superuser will be logged in, and not the users which were created using the sign up form. Here's my sample code. Views.py def signup(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): user=form.save() userNAME = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=userNAME, password=raw_password) login(request, user) return redirect('/UserPage') else: form = UserForm() return render(request, 'signup.html', {'form': form}) Urls.py urlpatterns=[ url(r'^$',views.HomePageView.as_view()), url(r'^about/$',views.AboutPageView.as_view()), url(r'^time/$', current_datetime), No need , displaying in home page url(r'^input/$',views.EmployeeView.as_view()), url(r'^signup/$',signup, name="signup"), url(r'^UserPage/$',views.UserPageView.as_view()), url(r'^login/$',auth_views.login, {'template_name':'login.html'},name='login'), ] models.py class UserCredentials(models.Model): user_name=models.CharField(max_length=20) user_email=models.CharField(max_length=20) user_password=models.CharField(max_length=20) class Meta: db_table="userdetails" def __str__(self): return (self.user_name) class UserForm(ModelForm): class Meta: model=UserCredentials fields=['user_name', 'user_email', 'user_password'] And, by the way, I'm using django's default login and authenticate methods from django.contrib.auth. Also, It would be great, if someone can explain how does django stores the data posted from the form, and where does (may be in db tables) it looks for validation, when user credentials are supplied … -
Django NoReverseMatch exception with no arguments not found
Basic structure of my app is that of a blog which has comments. urls.py # methods to access details of a post url(r'^detail/(?P<pk>\d+)/$', staff_view.DetailPostView.as_view(), name = 'details'), # methods to add objects for posts(communication) and comments url(r'^new_comm/$', staff_view.form_view, name ='add_communication'), url(r'^detail/(?P<pk>\d+)/comment/new$', staff_view.comment_view, name='add_comment'), ] detail.html <div class='container'> <h2>{{ post.title }}</h2> <h3><span class="label label-info">{{post.date}}</span></h3> <br> <div class ='well'><h5>{{ post.descr }}</h5></div> <a href="{% url 'add_comment' pk=post.id %}">Add A Comment</a> views.py def comment_view(request,pk): comm_form = comment_form() print(request.POST.get('pk')) if request.method == 'POST': form = comment_form(request.POST) if form.is_valid(): usn = request.user.get_username() print(usn) new_com = comment() new_com.content = form.cleaned_data.get('content') print(new_com.content) new_com.link_to_comm = Comm_Item.objects.get(pk = request.POST.get('pk')) new_com.username = User.objects.get(username = usn) new_com.save(commit=True) return redirect('details',pk = self.kwargs ['pk']) return render(request, 'staffcom/comment.html', {'form': comm_form}) So what I want to do is add a comment to post(Comm_Item) through the details page of the post. The details page works correctly, however when I click on the link to add a comment, the comment form doesn't get rendered. It seems the get request doesn't get fulfilled. Reverse for 'add_comment' with no arguments not found. 1 pattern(s) tried: ['staffcom/detail/(?P<pk>\\d+)/comment/new$'] Would it help if I had an exception made for the request.method == "GET instead of leaving it to the remaining part of the … -
Django Social Auth Session not working
In my current project, I'm using two different Django web apps. One of this two web apps handles the authentication with email + password and python social auth. So both using django.contrib.sessions.backends.signed_cookies as SESSION_ENGINE with the same SECRET_KEY. When the user login with email + password on app1 he can access app2 and is authenticated but when he connects to e.g. Google or Facebook and then login he can't access app2 and is not authenticated. But why? Here my settings.py SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESSION_COOKIE_NAME = 'curr_user_session' SESSION_COOKIE_SECURE = True SESSION_COOKIE_DOMAIN = ".example.com" SECRET_KEY = "just4testing" INSTALLED_APPS = [ # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "oidc_provider", "core", 'django.contrib.auth', "social_django", ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ '...', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) -
Django rest framework get data based on current userId/token
In my model, i have a family table where user are able to enter their family details and store their information. But how do i get/query all the family member based on current userId ? For eg: userId=1 added 2 family member, mother and father. How do i get these 2 family member based on the query of the current user's userId ? here is my code : models class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=40, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) class Family(models.Model): userId = models.ForeignKey(MyUser) relationship = models.CharField(max_length=100) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField(max_length=6, blank=True, null=True) serializers class MyUserSerializer(serializers.ModelSerializer): valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False) class Meta: model = MyUser fields = ['userId', 'username', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime'] read_only_fields = ('userId',) extra_kwargs = {"password": {"write_only": True}} def update(self, instance, validated_data): for attr, value in validated_data.items(): if attr == 'password': instance.set_password(value) else: setattr(instance, attr, value) instance.save() return instance class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'userId', 'first_name', 'last_name', 'gender', 'relationship') views class MyUserViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = MyUser.objects.all() serializer_class = MyUserSerializer filter_backends … -
How to get information from save in django
I need to see what value I saved in the save model of Django. I am not able to save the model after performing changes. class CategoryInlineAdmin(admin.TabularInline): model = Category fields = ('title', 'specifications') Category = forms.ModelChoiceField(queryset=Category.objects.all()) Product = forms.ModelChoiceField(queryset=Product.objects.all()) print("Ensi") # This gets printed def save(self, obj, *kwargs): x = self.cleaned_data['Category'].specifications y = self.cleaned_data['Product'].specifications print(x,y) # Any way to print this? y.update(x) # This is not working Product.save() # Unable to save after updating specifications