Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using class based view UpdateView in case change or delete nested model
models.py class Project(models.Model): project_name = models.CharField(max_length=150) class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=250) is_done = models.BooleanField(default=False) views.py from django.views.generic import ListView from django.views.generic.edit import DeleteView from django.urls import reverse_lazy from .models import Project class ProjectListView(ListView): model = Project context_object_name = 'projects' class ProjectDeleteView(DeleteView): model = Project success_url = reverse_lazy('projects') project_list.html {% for project in projects %} <p>{{ project.project_name }} - <a href="{{ project.id }}/delete">Delete</a> </p> <ul> {% for task in project.task_set.all %} <li>{{ task.task_name }} - <a href="#">Done</a> - <a href="#">Delete</a></li> {% endfor %} </ul> {% endfor %} How I can use class based view UpdateView for the Project model in case change or delete nested model Task? -
user_logged_in is not working djnago rest framework
I have created registration api and login api using drf and i wanted to store all user login using signals user_loggged_in. it work fine when super user logged in but it doesn't work when user logged in. -
How to make structure to show 2d array in html where array data is render based on django (view.py) send?
suppose array be like ... arr = [['1', '2', '3'],[1', '2', '3'],[1', '2', '3']] here if every time data passed by django view.py can be different. Means array size can be varied as requirement it can be like this at second time arr = [['1', '2'],[1', '2']] how can I make general structure in html? is there JavaScript needed ?if yes then how to send data from view.py to javascript ? -
Django web app: storing Chat messages in database
I am creating a web app using Django and would like to allow any 2 users (but only 2 at a time) to be able to chat with each other. It doesn't need to be anything fancy and it will only be between the 2 related users on a Transaction object, so the Chat object will look up to the Transaction object. Someone told me it's not a good idea to store chat messages in just a regular Message table in a database, and that I should use a messaging service, since the chat messages would not be encrypted in the database. The chat messages will allow 2 users to plan to meet up with each other, which is somewhat confidential, but I don't think it's anything to worry about. Or am I wrong? I was also considering using the django-messages library, but I think it would be easier to just add a new object to my table. I found this StackOverflow post from 10 years ago about how this solution is good but didn't find many discussions about this recently. Below is a picture of the schema suggested: enter image description here What do people think, is it better … -
Django package versions have conflicting dependencies. (emove package versions to allow pip attempt to solve the dependency conflict)
ERROR: Cannot install -r requirements.txt (line 10), -r requirements.txt (line 11), -r requirements.txt (line 16), -r requirements.txt (line 9) and Django==2.0.13 because these package versions have conflicting dependencies. The conflict is caused by: The user requested Django==2.0.13 django-crontab 0.7.1 depends on Django>=1.8 django-dbbackup 3.3.0 depends on Django>=1.5 django-debug-toolbar 2.2 depends on Django>=1.11 django-storages 1.10.1 depends on Django>=2.2 To fix this you could try to: loosen the range of package versions you've specified remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies -
Why do we direct the urls file in our main directory to the newly created urls file in the app directory in Django?
I was learning Django and noticed people directing the URLs file in the main directory of the project to a new created URL.py file in the app folder? Why can't we directly put the path in the URL file in the main directory? Instead of using include, we could have directly put the path there. Why aren't we doing it? -
Heroku keeps crashing
C:\Users\urvis\Desktop\rajpatel322.github.io\Practice_Project>heroku logs 2021-03-20T06:20:17.463462+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2021-03-20T06:20:17.463474+00:00 app[web.1]: 2021-03-20T06:20:17.463474+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2021-03-20T06:20:17.463475+00:00 app[web.1]: 2021-03-20T06:20:17.463478+00:00 app[web.1]: Traceback (most recent call last): 2021-03-20T06:20:17.463479+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 8, in 2021-03-20T06:20:17.463602+00:00 app[web.1]: sys.exit(run()) 2021-03-20T06:20:17.463630+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in run 2021-03-20T06:20:17.463750+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2021-03-20T06:20:17.463785+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 228, in run 2021-03-20T06:20:17.463952+00:00 app[web.1]: super().run() 2021-03-20T06:20:17.463954+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 72, in run 2021-03-20T06:20:17.464081+00:00 app[web.1]: Arbiter(self).run() 2021-03-20T06:20:17.464105+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 229, in run 2021-03-20T06:20:17.464249+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2021-03-20T06:20:17.464273+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 342, in halt 2021-03-20T06:20:17.464458+00:00 app[web.1]: self.stop() 2021-03-20T06:20:17.464461+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 393, in stop 2021-03-20T06:20:17.464655+00:00 app[web.1]: time.sleep(0.1) 2021-03-20T06:20:17.464658+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2021-03-20T06:20:17.464810+00:00 app[web.1]: self.reap_workers() 2021-03-20T06:20:17.464814+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2021-03-20T06:20:17.465021+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2021-03-20T06:20:17.465074+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2021-03-20T06:20:17.536146+00:00 heroku[web.1]: Process exited with status 1 2021-03-20T06:20:17.597483+00:00 heroku[web.1]: State changed from starting to crashed 2021-03-20T06:20:18.502462+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=triksnas.herokuapp.com request_id=8cab5dfb-ac60-4ccc-bd18-bb5be54dcd71 fwd="67.173.81.219" dyno= connect= service= status=503 bytes= protocol=https 2021-03-20T06:20:18.776461+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=triksnas.herokuapp.com request_id=9e323197-2f69-457a-8769-affa013553b5 fwd="67.173.81.219" dyno= connect= service= status=503 bytes= protocol=https 2021-03-20T06:22:08.971134+00:00 heroku[router]: at=error code=H10 desc="App crashed" … -
Passing dynamic url with parameters from JavaScript to Django
I have this form for adding and updating data: form.addEventListener('submit', function(e){ e.preventDefault() var url = "{% url 'api:task-create' %}" if(activeItem != null ){ url = `http://localhost:8000/api/task-update/${activeItem.id}/` activeItem = null } var title = document.getElementById('title').value fetch(url, { method: 'POST', headers:{ 'Content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'title':title}) }).then(function(response){ renderList() document.getElementById('form').reset() }) }) when adding url without parameters like this {% url 'foo:bar' %} it works fine, but when I do this: {% url 'foo:bar' <any var> %}, I am getting NoReverseMatch error. Currently I am using static url as you can see up top inside if statement and it works perfectly fine. I tried using ` to make it literal string still doesnt work. I just want urls getting passed be dynamic. -
How Override Djoser base endpoint users/me
I am a bit new to Djoser and what i am wanting to do is when an authenticated user naviates to the users/me API endpoint it returns with the user id email and name. I would like for it to also return custom information how would I do that? -
DRF Login/logout with Token authentication possibly with Session Authentication
I am beginner in django and I am trying to use Basic and Token Authentication for Login/logout views referring below tutorial except that I have own function based view. https://gutsytechster.wordpress.com/2019/11/12/user-auth-operations-in-drf-login-logout-register-change-password/ I use django.contrib.auth authenticate in to check for user credential and return a token instead of login method which I suppose creates a session in django. But the tutorial asks for auth.logout method for logging out which would require HTTPRequest object instead of rest_framework.Request object. However it works for logout and when I try to use auth.login method it give me the following error. The request argument must be an instance of django.http.HttpRequest, not rest_framework.request.Request my understanding is that django.contrib.auth methods login, logout works with session authentication and rest_framework.Request extends HTTPRequest. My questions are Does this error happens as I dint set up session authenticationin middleware? if so why logout alone works? Shouldn't it throw the same error for not referring to HTTPRequest object. Any help would be appreciated as I try to understand the basics well before going for any other approach. My view here @api_view(["POST"]) def login(request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = get_and_authenticate_user(**serializer.validated_data) data = AuthUserSerializer(user).data #login(request, user) return Response(data=data) def get_and_authenticate_user(username, password): user = authenticate(username=username, password=password) … -
Django - Group permissions per vendor or company
I am using a custom User model. I would like to enforce permissions based on vendor and group. A vendor can create groups and assign those groups permissions from given list of permissions. I have been reading about group permissions and have concluded that Django's Group model is not good choice for this as it doesn't allow multiple groups with same name and some other issues. I looked into some projects like Django-guardian. But don't seem to get an example that fits my case. What I want to do is. A Vendor will have staff users who will then be assigned to groups. So to check permission for a given group or user I will need to take Vendor into consideration. They must be member of the vendor staff and then the permission group. Can anyone point me in the right direction. Thank you -
nginx 502 error on digitalocean after copying code from dev folder to mail folder
I have a Django app deployed on DigitalOcean with Nginx, PostgresSQL. I have copied my code from my main folder to another dev-folder, so initially, both the folders have the same code. Now, I run python manage.py runserver 0.0.0.0:8000 in my def-folder and can access my application on https://server_ip:8000/. Now, I can make any changes in my code without affecting the main application. Once changes are done, I run cp -a /source/. /dest/ to copy my changes from the dev-folder to the main folder. It all looks good, but after copying code from the dev-folder to the main folder, my application gives a 502 error. The error disappears after running systemctl restart gunicorn. But why nginx is giving 502, when there is no timeout issue. Also, is this the accepted way of maintaining dev branch?? -
Django image file upload API no media is getting saved
I am trying to upload image to the server using Django API. The link is getting saved into the database but the actual media is not getting saved in /media folder. My models.py class File(models.Model): # file = models.FileField(blank=False, null=False) file = models.ImageField(upload_to='media/', blank=True) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) url.py: path('upload/', views.FileView.as_view(), name='file-upload'), serializer.py User Interest Serializer class UserInterestSerializer(serializers.ModelSerializer): class Meta: model = UserInterest fields = "__all__" views.py class FileView(generics.ListCreateAPIView): queryset = File.objects.all() serializer_class = FileSerializer Global setting: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Output: Link name is getting saved in the database: "id": 18, "file": "https://<URL>/media/home/tguser/tgportal/core/media/check.png", "remark": "ok", "timestamp": "2021-03-19T16:43:50.131435Z" } But actual media is not getting saved into media folder. Multiplart/form-data is set through postman. Am i doing anything wrong? Do i need /media folder permission? Any help is appreciated. Thanks, PD -
django server is auto reloading and not stopping
I am working on a web project. One moment before all was good but suddenly django localhost server kept itself reloading and not stopping auto-reloading the pages. First I got the following error connectionreseterror: (errno 104) connection reset by peer But now it's not showing any error just reloading itself over and over again. What could be the cause for this? Any help will be appriciated -
'bytes' object has no attribute 'encode' in EmailMessage
I am trying to make an app in Django which accepts information from user and send a HTML template as pdf through an e-mail to the user. But I am getting this error 'bytes' object has no attribute 'encode' Here is my view for the email def email(request, serial_no): user = get_object_or_404(Student, pk=serial_no) # roll_no = {'roll': str(user['roll_no'])} html = render_to_string('card.html', {'user': user}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename={}'.format(user.roll_no + '.pdf') pdf = weasyprint.HTML(string=html, base_url='').write_pdf( stylesheets=[weasyprint.CSS(string='body { font-family: serif}')]) to_emails = [str(user.roll_no) + '@gmail.com'] subject = "Certificate from Nami Montana" email = EmailMessage(subject, body=pdf, from_email='SSC', to=to_emails) email.attach("{}".format(user.roll_no) + '.pdf', pdf, "application/pdf") email.content_subtype = "pdf" # Main content is now text/html email.encoding = 'utf-8' email.send() return HttpResponseRedirect(reverse('id_card:submit')) Thanks in advance -
Problem about getting data from an online csv and put them into a Django database
scripts\loadDateData.py import csv import io import urllib.request from database.models import locationData, dateData def run(): target = locationData.objects.get (pk = 1) webpage = urlib.request.urlopen(target) #from stackoverflow reader = csv.DictReader(io.TextIOWrapper(webpage)) #from stackoverflow dateData.objects.all().delete() for row in reader: d, created = dateData.objects.get_or_create (date = row ["As of date"]) c, created = dateData.objects.get_or_create (confirmedCase = row ["Number of confirmed cases"]) dc, created = dateData.objects.get_or_create (deathCase = row ["Number of death cases"]) n = target.name temp = dateData (name = n, date = d, confirmedCase = c, deathCase = dc) temp.save() models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator #from django.contrib.postgres.fields import ArrayField # Create your models here. class locationData (models.Model): locationID = models.AutoField (primary_key = True) name = models.CharField (max_length = 64) population = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) apiEndpoint = models.URLField (max_length = 256) resourceURL = models.URLField (max_length = 256) class dateData (models.Model): entryID = models.AutoField (primary_key = True) name = models.CharField (max_length = 64) date = models.DateField (auto_now = False, auto_now_add = False) confirmedCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) deathCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) I am a beginner and I am working on a project about a web-based application to show … -
How to get the absolute path of a uploaded file in Django?
Hello django noob here, I am creating a form where user selects the path where he wants to store his results. And for that I am using FileField model to get the file path from user. But when using the following line of code I am not getting the absolute path of the file that user has uploaded. Please take a look at the code to understand better. models.py class UploadImageModel(models.Model): importPath = models.FileField() views.py def uploadImage(request): if request.method == 'POST': input1 = request.FILES.get('import_path') path = UploadImageModel(importPath=input1).importPath.path print(path) return render(request,'home.html') Now, my project is in directory: C:Users/admin/Desktop/MyProject And the output path variable gives is: C:Users/admin/Desktop/MyProject/filename But the original path of uploaded file is: C:Users/admin/Desktop/Data/filname So how do I get the original file path when user uploads a file? Please help me with this issue -
Stack overflow error when running tests in Django
When attempting to run a selenium test in django I am getting the following error: ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- Not found Fatal Python error: Cannot recover from stack overflow. Python runtime state: initialized Thread 0x000070000cc31000 (most recent call first): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/selectors.py", line 415 in select File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 232 in serve_forever File "/Users/nfishel/Documents/capstone-project-film-club/env/lib/python3.8/site-packages/django/test/testcases.py", line 1380 in run File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932 in _bootstrap_inner File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 890 in _bootstrap Current thread 0x00000001113b7dc0 (most recent call first): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 561 in __new__ File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 304 in __call__ File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 103 in _intenum_converter File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 920 in getaddrinfo /urllib3/connection.py", line 234 in request The test causing this issue was previously working, but I am trying to create a parent class with alot of the set up functions to cut down on code duplication for the tests. This is the parent class: class ParentTestCase(LiveServerTestCase): def setUp(self): self.selenium = webdriver.Chrome() self.signup() self.pick_genres() def tearDown(self): self.selenium.quit() super(LogoutTestCase, self).tearDown() def signup(self): selenium = self.selenium selenium.get(self.live_server_url + '/register') firstName = selenium.find_element_by_id('id_first_name') lastName = selenium.find_element_by_id('id_last_name') username = selenium.find_element_by_id('id_username') email = selenium.find_element_by_id('id_email') password1 = selenium.find_element_by_id('id_password1') password2 = selenium.find_element_by_id('id_password2') submit = selenium.find_element_by_id('id_register') firstName.send_keys('Test') lastName.send_keys('Tester') username.send_keys('Test123') email.send_keys('test123@test.com') password1.send_keys('moviepass') password2.send_keys('moviepass') submit.click() def pick_genres(self): selenium … -
displaying django custom validation
Hi I am a newbie in Django, so I want to show some error message in html, I have done methods in forms, def clean_FirstName(self): But I want to show that error message near the first name textbox, how I will do it? -
pip won't install channels_redis
for working with django channels i need to install "channels_redis". while installing "channels_redis" i face this error, any thought? by the way i'm on windows and it showed me an error of C++ first and after installing Microsoft visual studio build tools vanished and now this. ERROR: Command errored out with exit status 1: command: 'E:\Programming projects\Django\channels\chat_launch01\venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\setup.py'"'"'; __file__='"'"'C:\\ Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\setup.py'"'"';f=getattr(tokenize, '"'"'open'" '"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\KaNi\AppData\Local\Temp\pip-wheel-m0bnautd' cwd: C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\ Complete output (23 lines): C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import sys, imp, os, glob, io E:\Programming projects\Django\channels\chat_launch01\venv\lib\site-packages\setuptools\dist.py:642: UserWarning: Usage of dash-separated 'des cription-file' will not be supported in future versions. Please use the underscore name 'description_file' instead warnings.warn( running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\hiredis copying hiredis\version.py -> build\lib.win-amd64-3.9\hiredis copying hiredis\__init__.py -> build\lib.win-amd64-3.9\hiredis running build_ext building 'hiredis.hiredis' extension creating build\temp.win-amd64-3.9 creating build\temp.win-amd64-3.9\Release creating build\temp.win-amd64-3.9\Release\src creating build\temp.win-amd64-3.9\Release\vendor creating build\temp.win-amd64-3.9\Release\vendor\hiredis d:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ivendor -IE:\ Programming projects\Django\channels\chat_launch01\venv\include -Ic:\users\kani\appdata\local\programs\python\python39\include -Ic:\users\kani\a ppdata\local\programs\python\python39\include -Id:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt /Tcsrc\hiredis.c /Fobuild\temp.win-amd64-3.9\Release\src\hiredis.obj hiredis.c c:\users\kani\appdata\local\programs\python\python39\include\pyconfig.h(200): fatal error C1083: Cannot open include file: … -
Django problem connection after deployment postgres nginx
After deployment on my vps with ubuntu 18.0.4, ngix, gunicorn and postgresql, I can only connect into the admin area but when I try to connect as a simple user I got error 500 it seem like there is not connection between the application and postgres, even when I put wrong email and password I got error 500 but I can connect as I said into the admin Area. Any idea regarding my problem ? Thank you very much. -
no video with supported format and MIME type found in django
no video with supported format and MIME type found A huge screen for video is displayed and says the message above. How do I solve this? This happens to me only in Mozilla Firefox and not on Google Chrome. I am using webm videos and mp4 videos. I'm Uploading a video from the admin panel model.py class Video(models.Model): caption = models.CharField(max_length=70) video = models.FileField(upload_to='video') view.py from .models import Video def home(request): video = Video.objects.all() return render(request, 'video/index.html', {'videos':video}) url.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) home.html {% for video in videos %} <video width="320" height="240" controls> <source src="{{video.video.url}}" type="video/webm"> </video> {% endfor %} -
Hello, im trying to dislpay and image on the django administartion but its just showinig the image extention on the panel
models.py def admin_photo(self): return mark_safe('<img src="()" width="100" />'.format(self.car_image.url)) admin_photo.short_description ="image" admin_photo.allow_tags = True admin.py class CarsAdmin(admin.ModelAdmin): # fields = ('car_name', 'car_image', 'car_model_number', 'car_millage', 'car_description', 'car_price') fields = ('admin_photo',) readonly_fields = ('admin_photo',) list_display = [ 'car_image', 'car_name' ] Hello, im trying to dislpay and image on the django administartion but its just showinig the image extention on the panel -
Django serilizator object updating problem
i would like to ask where could be problem with my serilizator or calling of him. I want to update serializated data inside object personal info but it keep throwing me error: AttributeError: 'PersonalInfoSerializer' object has no attribute 'user' Here's my serilizator class: class PersonalInfoSerializer(serializers.Serializer): user = serializers.IntegerField(required=False) firstname = serializers.CharField(max_length=255) lastname = serializers.CharField(max_length=255) card_id = serializers.CharField(max_length=255) street = serializers.CharField(max_length=255) postal_code = serializers.IntegerField() city = serializers.CharField(max_length=255) debet_card_number = serializers.CharField(max_length=16) created_at = serializers.DateTimeField(required=False) last_update = serializers.DateTimeField(required=False) def create(self, validated_data): return PersonalInfo.objects.create(**validated_data) def update(self, instance, attrs): print("instance", attrs.get('user', instance.user)) instance.user = attrs.get('user', instance.user) instance.save() return instance And here is my view function thats updating serilizator object: json = BytesIO(request.body) data = JSONParser().parse(json) data.update({'created_at': datetime.datetime.now(tz=timezone.utc), 'last_update': datetime.datetime.now(tz=timezone.utc), 'last_login': datetime.datetime.now(tz=timezone.utc), 'token':generate_key()}) user = UserSerializer(data=data) personal_info = PersonalInfoSerializer(data=data) if user.is_valid() and personal_info.is_valid(): if user_exists(data["email"]): response = {'Failed': 'email is already used'} return JsonResponse(response) elif card_exists(data["card_id"]): response = {'Failed': 'card id is already used'} return JsonResponse(response) else: user.save() personal_info = PersonalInfoSerializer(personal_info, {'user':10}, partial=True) personal_info.is_valid() personal_info.save() I think main problem is calling serilizator update but i tried everything :/ Thank you for help :) -
App using Django runs server only once after cloning
I cloned a private GitHub repository that was created using Django into visual studio code and set it up the following way: Open project in visual studio code, there open the project's terminal Create a virtual environment using python -m venv .\venv Active that virtual environment using venv\scripts\activate Import all packages from requirements.txt individually. Since pip freeze -r requirements.txt was giving me an error, I installed each package using pip install packageName Check all models migrated to database with python manage.py makemigrations followed by python manage.py migrate Start server using python manage.py runserver At this point I clicked the local host link and it runs well but after I close the server and try to open it again I first get the error ModuleNotFoundError: No module named 'pymysql'. Then when I do pip install pymysql I get the errors: ModuleNotFoundError: No module named 'rest_framework' OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' After I try and fix the first one by using pip to install rest_framework I only get the same error three times consecutively: Winerror [10061]: No connection could be made because the target machine actively refused it. At this point, I …