Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
duplicate when use filter() with values()
i have this 3 models : class Degrey(models.Model): name = models.CharField(max_length=200) class DegreyCompany(models.Model): withdegrey = models.ForeignKey(Degrey, on_delete=models.CASCADE, null=True, blank=True) company = models.ForeignKey(Secondary, on_delete=models.CASCADE, null=True, blank=True) spesial = models.ForeignKey('Spesial', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, default=withdegrey.name, null=True, blank=True) nomberetud = models.PositiveSmallIntegerField(null=True, blank=True) nomberexist = models.PositiveSmallIntegerField(null=True, blank=True) class Meta: unique_together = ('withdegrey', 'company', 'spesial'), def __str__(self): return self.name class Secondary(models.Model): withprimary = models.OneToOneField(CustomUser, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) codeonec = models.PositiveSmallIntegerField() codelocal = models.PositiveSmallIntegerField() address = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.name) and the model: class MediaSecParnt(models.Model): withdegrey = models.ForeignKey(Degrey, on_delete=models.CASCADE) withsecondray = models.ForeignKey(Secondary, on_delete=models.CASCADE) nomberesteda = models.PositiveIntegerField(null=1, blank=1) nomberhodor = models.PositiveIntegerField(null=1, blank=1) when use querset to accses the value of through model -MediaSecParnt- : listilam = MediaSecParnt.objects.filter(date__range=[primary1, primary2]).values( 'withsecondray__name','withdegrey__name','withsecondray_id','withdegrey_id').annotate(nomberhodor=Sum('nomberhodor'), nomberesteda=Sum('nomberesteda')) i get good result but when i want to add -nomberetud- like this queryset : listilam = MediaSecParnt.objects.filter(date__range=[primary1, primary2]).values( 'withsecondray__name', 'withdegrey__name', 'withsecondray_id', 'withdegrey_id','withsecondray__degreycompany__withdegrey_id').annotate( nomberhodor=Sum('nomberhodor'), nomberesteda=Sum('nomberesteda'),nberetud=Sum('withsecondray__degreycompany__nomberetud')) its give me duplucat value : <QuerySet [ {'withsecondray_id': 2, 'withdegrey_id': 1, 'withsecondray__degreycompany__withdegrey_id': 1, 'nomberhodor': 600, 'nomberesteda': 800, 'nberetud': 510}, {'withsecondray_id': 2, 'withdegrey_id': 1, 'withsecondray__degreycompany__withdegrey_id': 2, 'nomberhodor': 600, 'nomberesteda': 800, 'nberetud': 1220}, {'withsecondray_id': 2, 'withdegrey_id': 2, 'withsecondray__degreycompany__withdegrey_id': 1, 'nomberhodor': 500, 'nomberesteda': 1000,'nberetud': 510}, {'withsecondray_id': 2, 'withdegrey_id': 2, 'withsecondray__degreycompany__withdegrey_id': 2, 'nomberhodor': … -
HTMLCalendar displaying as a String instead of using the HTML properly (Django)
I'm trying to display an HTMLCalendar in my django project but it's only displaying the html code instead of the actual Calendar. views.py def CalendarView(request): cal = HTMLCalendar().formatmonth(2020, 10, withyear=True).replace('<td ', '<td width="150" height="150"') return render(request, 'calendar.html', {'cal': cal}) calendar.html {% extends 'base.html' %} {% block tilte %} Home {% endblock %} {% block body %} <div id="content-main"> <ul class="object-tools"> <li> <a href={{ previous_month }}> Previous month </a> </li> <li> <a href={{ next_month }}> Next month </a> </li> </ul> {{ cal }} {% endblock %} This is what gets displayed instead of the actual calendar -
Checkmark in Django, getting which one is checked
I'm new in django and trying to set a form like this: my form So far I did this: result.html: .... <form id="form" name="form" method="GET"> <p> <label class="container">Yes <input type="checkbox" name="1"> <span class="checkmark"></span> </label> <br> <label class="container">No <input type="checkbox" name="0"> <span class="checkmark"></span> </label> <br> <label class="container">No proper image <input type="checkbox" name="2"> <span class="checkmark"></span> </label> <br> </p> .... in views.py: def result(request): .... if request.method == 'GET': context = {} context['form'] = FormYesOrNo() .... return render(request, template_name, response1) in forms.py: choices = [(1, 'Yes'), (0, 'No'), (2, 'none')] class FormYesOrNo(forms.Form): def PrdJudgeRe(self): PrdJudge = forms.TypedChoiceField( choices=choices, coerce=str) return (PrdJudge) Now in views.py I do not know how to get the checked box index or value. when running server and for example I check yes in the log I see this: "GET /result/?1=on HTTP/1.1" 200 1389 which means that it can see 1 is on but how can I get that? -
How to import 2 or more js files into jinja2
I know that to import a js file, I can simply do: <script src="/static/js/example.js"> But i need to import two or more files js into my jinja file. And when i do this: <script src="/static/js/example.js"> <script src="/static/js/example2.js"> Jinja only loads the first file. I searched a lot on the web, but all the examples are using HTML and not Jinja. -
Choosing the right datetimepicker
I am having a tough time finding a datetimepicker that does exactly what I need and works with Bootstrap 4, Django, and Django Crispy Forms. The critical thing I need is the ability for the user to type what they want in the date input field without the calendar popping up with an icon next to the input field upon which they can click if they would like to choose a date visually. I have had problems with a few datetimepickers with no responses on this platform as to how I might resolve those issues. I first tried the Django wrapper for Tempus Dominus (django tempus dominus) which seemed the most logical choice, but it does not play well if you are using Django Crispy Forms layouts to render the forms. When the input is converted to a datetimepicker widget with a clickable calendar icon, the layout is thrown off as the input field's container gains extra height without any detectable CSS margins, padding, etc. It also forces the field to be required when it should not. Also, if the server side validation returns an error, the error text is disabled (changes css of the text element to display:none) although … -
I can't save changes to entry after clicking 'edit entry' button in Django
I have a problem with editing entry in Django. After changing the text it can't be saved and get redirected to Entries page. Picture down below:[Image of editing entry][1] [1]: https://i.stack.imgur.com/kZ9Gv.png Here's the code for edit_entry: from django.shortcuts import render, redirect from .models import Topic, Entry from .forms import TopicForm, EntryForm def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic_id if request != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topic', topic_id=topic.id) context = { 'entry':entry, 'topic':topic, 'form':form } return render(request, 'learning_logs/edit_entry.html', context) -
Can I add tags inside articles in Django?
Can I add tags inside articles in Django? for example i want add article about pubg so i want add tag called pubg and when user click on this tag it will show all articles with same tag i mean pubg tag is there way to do that -
'Slide' object has no attribute 'topicdetail_set'
I created a model for Slide on django. below is model.py class Slide(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True) text = models.CharField(max_length=300) is_deleted = models.BooleanField(default=False) topic_id = models.ForeignKey(Article, on_delete=models.DO_NOTHING) created_at = models.DateTimeField("created at", auto_now_add=True) objects = models.Manager() def __str__(self): return self.text serializer.py class SlideSerializer(serializers.ModelSerializer): topicdetail_set = ArticleDetailSerial(many=True) user_detail = FindOwnerSerializer(source='user', read_only=True) author = AuthorSerializer(many=True) class Meta: model = Slide fields = ('id','text', 'created_at', 'topicdetail_set', 'user_detail','author') When I run the url for slide http://127.0.0.1:8000/article/slide/ then I got below error AttributeError: Got AttributeError when attempting to get a value for field `topicdetail_set` on serializer `SlideSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Slide` instance. Original exception text was: 'Slide' object has no attribute 'topicdetail_set'. Now I am confused, Is the code that I have created is wrong? And if it is wrong then how should I fix it? -
How to share Python method between two Django classes?
I have two classes in my Django models.py file: class ProfileManager(models.Manager): def create_profile(self, user, member): # Set default age to 100 years old when profile is created. years_ago100 = datetime.datetime.now() - datetime.timedelta(days=101 * 365) age = calculate_age(years_ago100) # <- Used here profile = self.create(user=user, person_dob=years_ago100, person_age=age) return class Profile(models.Model): person_dob = models.DateField() person_age = models.IntegerField() objects = ProfileManager() def save(self, *args, **kwargs): # Update to real age when user edits profile for the first time. self.person_age = calculate_age(self.person_dob) # <- Used here too super(Profile, self).save(*args, **kwargs) Each class uses this calculate_age method: def calculate_age(born): today = datetime.date.today() return (today.year - born.year - ((today.month, today.day) < (born.month, born.day))) How can I make this method accessible to both classes? One easy way would be to make the method global like this but that seems like a kludgy way to do it: def calculate_age(born): ... class ProfileManager(models.Manager): ... class Profile(models.Model): ... Also, this wouldn't work if I wanted to access that method outside of this particular models module. Is there a standard way to do this when using Django? -
If AtomicRequest is True in Django Is there a way to do a manual commit?
ATOMIC_REQUESTS is set to True in the DB settings. However, there are cases where you want to perform a commit manually in transaction. When I run it, I get the error "If the atomic block is active, this is forbidden". And I don't know how to solve it. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'ATOMIC_REQUESTS': True } } @transaction.atomic def get(self, request): transaction.set_autocommit(False) try: self.save_book() except Exception: print("rollback") transaction.rollback() finally: transaction.commit() transaction.set_autocommit(True) return Response('success') -
use annotate to get percent give me resulte without comma 7/2 = 3 not 3.5
i want get percent value of : nomberesteda*100/nomberhodor = 0.00 i use this queryset : listilam = MediaSecParnt.objects.filter(date__range=[primary1, primary2]).values( 'withsecondray__name','withdegrey__name','withsecondray_id','withdegrey_id') .annotate(nomberhodor=Sum('nomberhodor'), nomberesteda=Sum('nomberesteda'), percent=((((F('nomberhodor')*100)/(F('nomberesteda')))))) here : percent=((((F('nomberhodor')*100)/(F('nomberesteda')))))) percent value come without comma !! nomberhodor culomn is intiger and same for nomberesteda here is the rusult: <QuerySet [{'nomberhodor': 70, 'nomberesteda': 300, 'percent': 23}, {'nomberhodor': 64, 'nomberesteda': 150, 'percent': 42}, {'nomberhodor': 33, 'nomberesteda': 66, 'percent': 50}, {'nomberhodor': 50, 'nomberesteda': 200, 'percent': 25}, {'nomberhodor': 220, 'nomberesteda': 725, 'percent': 30}, {'nomberhodor': 567, 'nomberesteda': 900, 'percent': 63}, {'nomberhodor': 309, 'nomberesteda': 910, 'percent': 33}]> it should be : <QuerySet [{'nomberhodor': 70, 'nomberesteda': 300, 'percent': 23.33}, {'nomberhodor': 64, 'nomberesteda': 150, 'percent': 42.66}, {'nomberhodor': 33, 'nomberesteda': 66, 'percent': 50.00}, {'nomberhodor': 50, 'nomberesteda': 200, 'percent': 25.00}, {'nomberhodor': 220, 'nomberesteda': 725, 'percent': 30.34}, {'nomberhodor': 567, 'nomberesteda': 900, 'percent': 63.00}, {'nomberhodor': 309, 'nomberesteda': 910, 'percent': 33.95}]> -
Anaconda worker could not start because:
I've just installed Anaconda by using Package Control; and, after installing it, the terminal show me this message: anacondaST3: ERROR - Anaconda worker could not start because: connection to localhost:50462 timed out after 0.2s. tried to connect 7 times during 2.0 seconds check that there is Python process executing the anaconda jsonserver.py script running in your system. If there is, check that you can connect to your localhost writing the following script in your Sublime Text 3 console: import socket; socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(("localhost", 50462)) If anaconda works just fine after you received this error and the command above worked you can make anaconda to do not show you this error anymore setting the 'swallow_startup_errors' to 'true' in your configuration file. And, the Anaconda autocompletation just doesn't work, the only reason I installed Anaconda for. What should I do? I'm practically a beginner in all of this programming stuff, so, be nice:( -
Django session key get or create
I have created below model tracking user-session relationships: from django.conf import settings from django.contrib.sessions.models import Session USER_MODEL = settings.AUTH_USER_MODEL class UserSession(models.Model): user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE) session = models.ForeignKey(Session, on_delete=models.CASCADE) And to populate entries of this model, registered below user_logged_in handler: from django.contrib.auth import get_user_model from django.dispatch import receiver from django.contrib.auth.signals import user_logged_in from accounts.models import UserSession User = get_user_model() @receiver(user_logged_in, sender=User, dispatch_uid="handle_user_login") def handle_user_login(sender, request, user, **kwargs): if not request.session.session_key: request.session.create() UserSession.objects.get_or_create(user=user, session_id=request.session.session_key) The model and user login handler signal are deployed and working as expected in production. Problem is above mentioned signal sometimes raises database integrity error: insert or update on table "accounts_usersession" violates foreign key constraint "accounts_usersessio_session_id_fee1fd0b_fk_django_se" DETAIL: Key (session_id)=(56aklsn6q00dm7hnszsksokbilj1p444) is not present in table "django_session". The probability (experimental) of above exception is fairly low at about 0.04%. I couldn't reproduce this error in my local development environment. What can be cause for this error and how can I prevent it? -
Indexing on mongodb with django
I am trying to indexing on some of the fields in MongoDB collection and I am making model in django. I made a model, but I don't know how can we use indexing while creating a model Indexing on mongodb with django class USERCHAT(models.Model): _id = models.ObjectIdField() SenderID = models.CharField(max_length=255, db_index=True) ReceiverID = models.CharField(max_length=255, db_index=True) Message = models.CharField(max_length=255) DateTime = models.DateTimeField() objects = models.DjongoManager() guide me for doing indexing. -
how to use ManyToManyField as tags in my blog
i want add tags in my article and when user click on some tag it will show all articles that having that tag , so i create tag model then i add ManyToManyField field in mobile model so what next ? i mean how to use tags when i add some tag in admin panel and how to create html page for every tag ? model.py : # Tag model class Tag(models.Model): PostTagName = models.CharField(max_length=100) slug = models.SlugField(default="",blank=True,unique=True,editable=True) def save(self, *args, **kwargs): if not self.id or not self.slug: super(Tag, self).save(*args, **kwargs) self.slug = slugify(f"{self.PostTagName}") super(Tag, self).save(*args, **kwargs) def __str__(self): return self.PostTagName # mobile model class Mobile(models.Model): title = models.CharField(max_length=100,default="") name = models.CharField(max_length=100,default="") app_contect = RichTextField(blank=True,null=True) app_image = models.ImageField(upload_to='images/',null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) post_tag = models.CharField(max_length=50,default="",choices = MOBILE_SECTION) tag = models.ManyToManyField(Tag) NETWORK = models.TextField(max_length=240,default="") LAUNCH = models.TextField(max_length=240,default="") BODY = models.TextField(max_length=240,default="") DISPLAY = models.TextField(max_length=240,default="") PLATFORM = models.TextField(max_length=240,default="") MEMORY = models.TextField(max_length=240,default="") MAIN_CAMERA = models.TextField(max_length=240,default="") SELFIE_CAMERA = models.TextField(max_length=240,default="") SOUND = models.TextField(max_length=240,default="") COMMS = models.TextField(max_length=240,default="") FEATURES = models.TextField(max_length=240,default="") BATTERY = models.TextField(max_length=240,default="") Colors = models.TextField(max_length=240,default="") Price = models.CharField(max_length=240,default="") objects = SearchManager() slug = models.SlugField(default="",blank=True,unique=True,editable=True) def save(self, *args, **kwargs): if not self.id or not self.slug: super(Mobile, self).save(*args, **kwargs) self.slug = slugify(f"{self.title}") super(Mobile, self).save(*args, **kwargs) def … -
Django project. Work with Excel files in Django
How can I generate an Excel file, fill it with data from the database, and save it as downloaded files when the button is clicked ? -
How to resolve NoReverseMatch in django while using reverse with id as argument?
So I've been getting the NoReverseMatch presumably from having passing id value greater than 9. So here's the error message I'm getting : Reverse for 'article-details' with arguments '('2', '9')' not found. 1 pattern(s) tried: ['a/(?P<pk>[0-9]+)$'] here's my code: Models.py class Post( models.Model): title = models.CharField( max_length = 250 ) author = models.ForeignKey( User , on_delete=models.CASCADE ) body = models.TextField() def get_absolute_url(self): print((self.id)) return reverse('article-details' , args= str(self.id)) urls.py urlpatterns = [ path ( 'a/<int:pk>' , ArticleDetailView.as_view() , name='article-details' ) , path('create/' , CreatePost2.as_view() , name='create_post' ) , path ( 'p/<int:pk>' , postDetails , name= 'post-details' ) , ] I think that since i have upward of 10 entries in database whenever reverse is called with id > 9 it interprets it as touple with 2 values. How do i solve this issue ? -
Link added to HTML by JavaScript does nothing when clicked
I'm creating a primitive search engine for the support database on my Django site. I have JavaScript set to listen for any changes to the search field, and then query for suggestions to the server. The script then loops through the JSON result and generate a Bootstrap-styled dropdown below the search box. Everything about it is working flawlessly… except the part where clicking the suggestions actually takes you there. Hovering over the links turns them blue and shows their target in the lower-left corner of my Chromium Edge. But clicking just does nothing. You can inspect the HTML and click the link's target there, and it works. You can even delete the element and recode it back in the inspector and clicking it works there! It must have something to do with JavaScript adding it and not refreshing properly. Here's part of my HTML (a lot of the extra mumbo-jumbo is for Bootstrap; I copied it right from their documentation): <input type="text" class="form-control" placeholder="Search" id="query"> <div class="input-group-append"> <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> </button> <div class="dropdown-menu dropdown-menu-lg-right" id="suggestions"> <p class="p-4 text-muted" id="noresults"> No articles that mach your query were found. Try something else. </p> </div> </div> And … -
May I use the "Software developer" title on my freelancer profile? [closed]
I'm a freelancer! My skill-set is Python, Django, DRF, Javascript, Node, React My question is May I use the "Software developer" or "Freelance Software developer" title as a freelancer? -
Post class does not have objects variable in Django for Beginners
In W S Vincent's "Django for Beginners," on page 71 he creates a simple message board Django project and then creates some testing code. His simple Post class is from django.db import models class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] and then he creates a tests.py class with the following code: from django.test import TestCase from django.urls import reverse #new from .models import Post class PostModelTest(TestCase): def setup(self): Post.objects.create(text='just a test') def test_text_content(self): post = Post.objects.get(id=1) expected_object_name = f'{post.text}' self.assertEqual(expected_object_name, 'just a test') However, as you can see, there is no Posts.objects variable or method, and the test fails. I don't see what he intended to do here, but those with more Django experience may be able to point out what is wrong. -
the necessary modifications between local contact page and in server
hello i want to create a contact page currently it works fine locally and i want to know what changes are needed for what works in the server of course i want if someone sends me a message i get an email views.py from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect from django.core.mail import EmailMessage def Contact(request): if request.method=="POST": subject = request.POST['subject'] message = request.POST['message'] from_email = request.POST['from_email'] send_mail(subject, message, from_email, ['myemail@gmail.com']) return render(request,'contact.html',{}) return render(request,'contact.html',{}) contact.html <!-- Contact Form --> <div class="col-12 col-md-8"> <div class="contact-form"> <form action="{% url 'store:contact' %}" method="post"> {% csrf_token %} <!-- Section Heading --> <div class="section-heading"> <h2>Get In Touch</h2> <div class="line"></div> </div> <!-- Form --> <form action="{% url 'store:contact' %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-lg-6"> <input type="text" name="subject" class="form-control mb-30" placeholder="subject"> </div> <div class="col-lg-6"> <input type="email" name="from_email" class="form-control mb-30" placeholder="Your Email"> </div> <div class="col-12"> <textarea name="message" class="form-control mb-30" placeholder="Your Message"></textarea> </div> <div class="col-12"> <button type="submit" class="btn dento-btn">Send Message</button> </div> </div> </form> setting.py EMAIL_HOST = 'smtp.gmail.com' modify by EMAIL_HOST_USER = '' modify by myemail EMAIL_HOST_PASSWORD = ''modify by my password EMAIL_PORT = 1025 modify by 587 EMAIL_USE_SSL=False modify by ?? EMAIL_USE_TLS = False modify by ?? DEFAULT_FROM_EMAIL = 'my name <myeamil>' … -
ModuleNotFoundError: No module named 'onlineMenu/wsgi'
I was going to host it using Heroku. But it does not work because of the problem with the profile. This my Procfile web: gunicorn onlineMenu.wsgi --log-file - my wsgi.py code """ WSGI config for onlineMenu project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'onlineMenu.settings') application = get_wsgi_application() this is my Heroku log (not all) 2020-10-23T16:04:08.861587+00:00 app[web.1]: Traceback (most recent call last): 2020-10-23T16:04:08.861588+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-10-23T16:04:08.861588+00:00 app[web.1]: worker.init_process() 2020-10-23T16:04:08.861589+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-10-23T16:04:08.861589+00:00 app[web.1]: self.load_wsgi() 2020-10-23T16:04:08.861589+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-10-23T16:04:08.861590+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-10-23T16:04:08.861590+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-10-23T16:04:08.861590+00:00 app[web.1]: self.callable = self.load() 2020-10-23T16:04:08.861591+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-10-23T16:04:08.861591+00:00 app[web.1]: return self.load_wsgiapp() 2020-10-23T16:04:08.861591+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-10-23T16:04:08.861592+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-10-23T16:04:08.861592+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2020-10-23T16:04:08.861592+00:00 app[web.1]: mod = importlib.import_module(module) 2020-10-23T16:04:08.861593+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/init.py", line 127, in import_module 2020-10-23T16:04:08.861593+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-10-23T16:04:08.861593+00:00 app[web.1]: File "", line 1014, in _gcd_import 2020-10-23T16:04:08.861594+00:00 app[web.1]: File "", line 991, in _find_and_load 2020-10-23T16:04:08.861594+00:00 app[web.1]: File … -
Difference between update method in Django Rest Framework?
How to figure out whether to use the update method in serializer class or in view class in Django Rest Framework when updating a user's data? Also, I couldn't find anything related to this in much detail in the Rest Framework Documentation. Can someone please help me understand it better or provide some resources for the same? -
User Password is not Encrypted Django with Rest Framework
When I create a user password remains in plain text. Also Im using signals to create user profiles related to users. Though I use the set_password method passwords are not encrypting. Serializer.py class UserSerializerAPI(serializers.ModelSerializer): class Meta: model = User fields = ['username','email','password','is_teacher'] extra_kwargs = {"password":{"write_only":True}} def create(self,validated_data): username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User( username = username, email = email ) user_obj.set_password(password) user_obj.save() return user_obj views.py class createuser(CreateAPIView): serializer_class = UserSerializerAPI queryset = MyUser.objects.all() -
Django Rest Framework read/write ModelSerializer with ChoiceField
I have a few field in my model "OrderItem" that are ChoiceFields or Enums. I want to represent the label of the choice and doing it with serializers.CharField(source='get_service_display'). See also Django Rest Framework with ChoiceField. That works fine, but creating objects is not working anymore with following error message OrderItem() got an unexpected keyword argument 'get_service_display' Here is my model class OrderItem(TimeStampedModel): class Categories(models.IntegerChoices): GRASS = (1, _('grass')) order = models.ForeignKey(Order, related_name='order_items', on_delete=models.CASCADE) unit_price = models.DecimalField(max_digits=6, decimal_places=2) category = models.IntegerField(choices=Categories.choices) and here my serializer class OrderItemSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) category = serializers.CharField(source='get_category_display') class Meta: model = OrderItem fields = ['id', 'unit_price', 'category'] read_only_fields = ['unit_price'] how can I create a model like this?