Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Printing out the event sent to a websocket but receiving received: {"isTrusted":true} as opposed to text received
I have a websocket that listens for a connection and sends data from my frontend to my websocket. I expect my websocket to send back a message indicating that it has received said data and my terminal to print out the text send. However, I am getting this: received: {"isTrusted":true} This is what I am sending: const testData = ['spill','test'] This is the receive function from my server: class PracticeConsumer(AsyncConsumer): ... async def websocket_receive(self, event): print("received:", event["text"]) sleep(1) await self.send({"type": "websocket.send", "text": event["text"]}) ... -
how to add custom templates in django-ckeditor in django
I am trying to use the Templates feature of the CKEditor in Django and I want to add some custom templates in the list. I've used this approach. I've tried editing myvenv\Lib\site-packages\ckeditor\static\ckeditor\ckeditor\plugins\templates\templates\default.js default.js CKEDITOR.addTemplates("default",{imagesPath:CKEDITOR.getUrl(CKEDITOR.plugins.getPath("templates")+"templates/images/"),templates:[{title:"Welcome Template",image:"template2.gif",description:"A template that you can send to clients as a welcome message.",html:' <h2>Welcome</h2> <p>Hi, <strong> Name here </strong> </p><p>You have recently shown an interest . . . </p>'},]}); but it didn't help, I've tried the collect static command but it didn't help either. I am still seeing the same default three templates. I'm not sure but there is another option of using extra plugins in the settings.py file but I don't know how to use it for this problem. settings.py CKEDITOR_UPLOAD_PATH = "file_upload/" CKEDITOR_CONFIGS = { 'default': { 'toolbar':'full', }, } apps INSTALLED_APPS = [ ..., 'ckeditor', 'ckeditor_uploader', ] urls.py urlpatterns = [ path('ckeditor/',include('ckeditor_uploader.urls')),] models.py class text(models.Model): body = RichTextField(blank=True, default="None") So my question is how to add custom templates in django-ckeditor==6.3.2? -
Using django modeling, how do you properly extend a model?
I'm an amateur developer who has been learning python in order to build my first full-stack project, which is an animal exchange site for a game I play. The animals can have up to 3 traits, but some of them have special ones. In the case of animals with special traits, I attempted to extend the base model and add additional traits using a notation someone suggested, but it doesn't seem to work. I know that technically I can just copypaste the base trait set and manually add them in, with a different model every time but that seems like it would bloat my code, and I'd like to be efficient about it. If you notice something else that could be improved, please let me know, thanks. from django.db import models #traits listed in class animal are base traits class ANIMAL(models.Model): MALE = 'MA' FEMALE = 'FE' SHINY = 'SHI' NORMAL = 'NOR' EGG = 'EGG' CHILD = 'CHI' ADOLESCENT = 'ADO' ADULT = 'ADU' ELDER = 'ELD' BIGBONED = 'BIGB' BUTTERFACE = 'BUTT' CHARMED = 'CHAR' CHATTY = 'CHAT' CONSTIPATED = 'CONS' CURVY = 'CURV' EVIL = 'EVIL' EXALTED = 'EXAL' FORTUNATE = 'FORT' FREAKOFNATURE = 'FREA' FROSTBREATH = … -
my css, js and imgs files are not comming in static folder
After running the following command for the Django project: python manage.py collectstatic Some other CSS files are generated, but the following CSS files "that exist in my template folder" are not coming into a static generated folder. When I manually copy-paste these files after the command then it works on local to load, but on production upon deployment to Heroku, it again runs collecstatic command which overwrites those files and then it doesn't load. I also have disabled collect static upon deploying the project to Heroku to prevent overwriting then again it does not load CSS files from the static folder. Please, does anyone, know how I could deal with it? thanks in advance -
Django tests fail due to null ids in content_type table depending on app naming
I added a new app to an established Django project with a PostgreSQL DB. The app name begins with an "a". The app models have foreign keys to models in other apps. The migrations run with no issue and the application starts and runs fine. However, running the tests gives an error like the below as soon as the test database creation starts. Each run creates an error for a different model. From this we can see that content_type table is being populated with null values for the ids. django.db.utils.IntegrityError: null value in column "name" of relation "django_content_type" violates not-null constraint DETAIL: Failing row contains (1, null, threadedcomments, threadedcomment). I have dependencies defined in the migrations file to ensure DB tables are created in the correct order. I have also moved the new app to the end of the list in the INSTALLED_APPS setting. Everything runs as it is supposed to if I do either of the following. Rename the app to start with a different letter. Removing the foreign keys. It looks like the tables are being created alphabetically, despite the migration dependencies. Is there a way to force the order of the table creation? Or is there something … -
rest_marshmallow: Nested Schema isn't loading
I have trouble getting the nested Schema loaded using marshmallow serializer. models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=200, unique=True) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) class Upload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) state = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) class Location(models.Model): upload = models.ForeignKey(Upload, on_delete=models.CASCADE) lat = models.FloatField() long = models.FloatField() serializers.py from rest_marshmallow import Schema, fields class LocationSchema(Schema): lat = fields.String() long = fields.String() class UploadsSchema(Schema): id = fields.Integer() state = fields.String() location = fields.Nested(LocationSchema) user_id = fields.Integer() created = fields.DateTime() class UserSchema(Schema): id = fields.Integer() first_name = fields.String() last_name = fields.String() email = fields.Email() created = fields.DateTime() last_updated = fields.DateTime() views.py class UploadsView(ListView): def get(self, request, user_id): upload = Upload.objects.filter(user_id=user_id) serializer = UploadsSchema(upload, many=True) return JsonResponse(serializer.data, safe=False) def post(self, request, user_id): data = json.loads(request.body) user = User.objects.get(id=user_id) upload = Upload(state=data['state'], user=user) upload.save() recent_upload = Upload.objects.filter(user_id=user_id).latest('created') location = Location(lat=data['lat'], long=data['long'], upload=recent_upload) location.save() message = { "data": "Success" } return JsonResponse(message, safe=False) GET on UploadsView returns all the fields except the Nested field. Here's a sample response: { "user_id": 2, "id": 5, "created": "2022-08-05T17:44:30.829087+00:00", "state": "happy" } I tried location = fields.Nested(LocationSchema(many=True)), but that doesn't seem to work either. What am I doing … -
Error during run the program runtime error
These are apps installed in my django project , the apps with vip_number.* are inside the innerproject folder... but i got the issue here that my apps are not installed in seetings.py where as they are already there INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'jet', 'jet.dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'vip_number.users', 'vip_admin', 'vip_number.base', 'vip_number.categories', 'vip_number.category_tag', 'vip_number.category_numbers', 'vip_number.number', 'vip_number.paytm', 'vip_number.subscribers', 'vip_number.homeimages', 'vip_number.testimonial', 'vip_number.faq', 'tagconstants', 'sekizai', 'vip_number.wawebplus', 'contact', ] error :*********************************************************************************** (djangoenv) PS E:\download\VIP number\vip_number> python manage.py runserver Exception in thread django-main-thread: Traceback (most recent call last): File "E:\download\VIP number\djangoenv\lib\site-packages\django\apps\config.py", line 244, in create app_module = import_module(app_name) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'base' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "E:\download\VIP number\djangoenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "E:\download\VIP number\djangoenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "E:\download\VIP number\djangoenv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "E:\download\VIP number\djangoenv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "E:\download\VIP number\djangoenv\lib\site-packages\django\utils\autoreload.py", … -
How can I set a logic like, "If a user order any product then the user will be able to give feedback just on that product"?
My motive is to set a logic like, a user only will be able to give a product review on that product he/she bought. I tried this below way but didn't work. Please give a relevant solution models.py class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_title = models.CharField(blank=True, null=True, max_length = 250) def __str__(self): return str(self.pk) + "." + str(self.product_title) class ProductOrder(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='UserOrderRelatedName',on_delete=models.CASCADE) CustomerName = models.CharField(max_length=250, blank=True, null=True) Product = models.ForeignKey(Products, related_name='ProductOrderRelatedName',on_delete=models.CASCADE) ProductTitle = models.CharField(max_length=250, blank=True, null=True) def __str__(self): return f'{self.pk}.{self.User}({self.Product})' views.py: def quick_view(request, quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) context = { "quick_view":quick_view, } return render(request, 'quickVIEW_item.html', context) urls.py: path('quick_view/<int:quick_view_id>/', views.quick_view, name="quick_view"), template: {% if quick_view in request.user.UserOrderRelatedName.all %} <form action="{% url 'feedBack' quick_view_id=quick_view.id %}" method="POST" class="needs-validation mt-3" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} <textarea id="email" placeholder="Share your experiencs..." rows="10" style="font-size: 13px;" type="email" class="form-control" name="feedBACK" value="" required></textarea> <button type="submit" class="btn btn-outline-dark ms-auto" style="font-size: 13px;"> Submit </button> </form> {% endif %} -
table post_post has no column named publishing_date
im just a beginner in web coding and i got this error while i was adding my first app to the my first website i couldn't find a solution to this i thought it was something related to language of my website but it didn't worked and here is my codes that i just wrote like i said i just started to coding so i dont know anything to solve this issue enter image description hereenter image description here -
django show me "django.db.models.query_utils.DeferredAttribute object at"
Im trie to get a values from an object of my DB on a form in html to edit him but when i call the current "value" from the attribute i get this: Form HTML <form enctype="multipart/form-data" method="post"> {% csrf_token %} {% for campo in formulario %} <div class="mb-3"> <label for="" class="form-label">{{ campo.label }}:</label> {% if campo.field.widget.input_type == 'file' and campo.value %} <br/> <img src="{{MEDIA_URL}}/imagenes/{{campo.value}}" width="100"srcset=""> {% endif %} <input type="{{ campo.field.widget.input_type}}" class="form-control" name="{{ campo.name }}" id="" aria-describedby="helpId" placeholder="{{campo.label}}" value="{{campo.value | default:''}}" /> </div> <div class="col-12 help-text"> {{campo.errors}}</div> {% endfor %} <input name="" id="" class="btn btn-success" type="submit" value="Enviar informacion"> </form> Views Models -
Django Rest Framework permissions class doesn't work properly
I'm trying to implement view with rest-framework, here it is: class IsOwnerOnlyPermissions(BasePermission): def has_object_permission(self, request, view, obj): print(obj.user_profile.user, request.user, obj.user_profile.user == request.user) print(request.user.groups, request.user.get_group_permissions()) return obj.user_profile.user == request.user class DjangoModelPermissionsWithRead(DjangoModelPermissions): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } class DocumentsDetails(generics.RetrieveAPIView): queryset = Documents.objects.all() serializer_class = DocumentsSerializer # Can access only owner OR administrator/moderator permission_classes = [IsOwnerOnlyPermissions | DjangoModelPermissionsWithRead] But it doesn't work properly. I'm accessing it via Postman with user which doesn't have any permissions or groups (it's printing auth.Group.None set()) and it doesn't block access for me. I know, that I can check user permissions in my IsOwnerOnlyPermissions, but I want to use DjangoModelPermissions class for this. Are there any possibility to do this? -
column does not exist at.... programmeable error
i have carried out all my migrations but still receiving this error. To my understanding the error means that the product table does not have the entities like name, price etc yet they are there. I need some help understanding this error more. from audioop import add from termios import TIOCGWINSZ from django.db.models.deletion import CASCADE from django.urls import reverse from django.conf import settings from django.db import models from django.conf import settings CATEGORY_CHOICES = ( ('F', 'Fashion'), ('El', 'Electronics'), ('HB', 'Health & Beauty'), ('G', 'Gardening'), ('SP', 'Sports'), ('HO', 'Home & Office'), ) LABEL_CHOICES = ( ('P', 'Primary'), ('S', 'Secondary'), ('D', 'Danger'), ) class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) seller = models.CharField(max_length=200, blank=True, null=True) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2, null=True) label = models.CharField(choices=LABEL_CHOICES, max_length=2, null=True) image1 = models.ImageField(null=True, blank=True) image2 = models.ImageField(null=True, blank=True) image3 = models.ImageField(null=True, blank=True) image4 = models.ImageField(null=True, blank=True) slug = models.SlugField(null=True, blank=True) characteristics = models.TextField(max_length=3000, null=True) description = models.TextField(max_length=3000, null=True) specifications = models.TextField(max_length=3000, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("homeapp:product", kwargs={'slug': self.slug}) def get_add_to_cart_url(self): return reverse("homeapp:add-to-cart", kwargs={'slug': self.slug}) def get_remove_from_cart_url(self): return reverse("homeapp:remove-from-cart", kwargs={'slug': self.slug}) @property def image1URL(self): try: url = self.image1.url except: url = '' return url @property def image2URL(self): … -
Save large CSV data into Django database fast way
I am trying to upload extensive CSV data like 100k+ into the Django database table, I have created the model below and then made a save function to insert the data into the table. It takes a long time so I have written celery code to run this in the background so it doesn't timeout, But the saving data into the table is slower. Is there any way to make the saving faster? class Film(models.Model): title = models.CharField(max_length=200) year = models.PositiveIntegerField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) def save_csv_to_db(): with open('films/films.csv') as file: reader = csv.reader(file) next(reader) for row in reader: print(row) genre, _ = Genre.objects.get_or_create(name=row[-1]) film = Film(title=row[0], year=row[2], genre=genre) film.save() -
Problem trying validate django form field while typing
I'm trying validate a field while typing based on another question ( How to validate django form field while it is typing? ). the js don't cal validation view and i get this error in browser: Uncaught ReferenceError: $ is not defined for line $('#id_num').on('input', function () { form {{ form.num }} <p id="validate_number" class="help is-danger is-hidden ">nome já utilizado</p> js <script> $('#id_num').on('input', function () { var id_number = $(this).val(); $.ajax({ url: '/validatenum/', data: { 'num': id_number }, dataType: 'json', success: function (data) { if (data.is_taken) { $("#validate_number").show(); document.getElementById('id_num').style.borderColor = "red"; document.getElementById("submit_change").disabled = true; } else { $("#validate_number").hide(); document.getElementById('id_num').style.borderColor = "#e7e7e7"; document.getElementById("submit_change").disabled = false; } } }); }); </script> view def validate_inventory_number(request): number = request.GET.get('num', None) data = { 'is_taken': InventoryNumber.objects.filter(num=number).exists() } return JsonResponse(data) -
Django pagination: EmptyPage: That page contains no results
When using Django CBV ListView with pagination, if I provide a page that is out of range, I get an error: I would like to have a different behaviour: to fallback to the last existing page if the provided page is out of range. I dug into Django source code paginator.py file and was surprised to find some code that does exactly this: def get_page(self, number): """ Return a valid page, even if the page argument isn't a number or isn't in range. """ try: number = self.validate_number(number) except PageNotAnInteger: number = 1 except EmptyPage: number = self.num_pages return self.page(number) However, it seems this code is never called by default using Pagination. What is the right way to deal with this? Should I make my own paginator by subclassing the Paginator class? Thanks. -
No Module named WhiteNoise
2022-08-05T17:47:45.758949+00:00 app[web.1]: ModuleNotFoundError: No module named 'whitenoise' 2022-08-05T17:47:45.759055+00:00 app[web.1]: [2022-08-05 17:47:45 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-08-05T17:47:45.817101+00:00 app[web.1]: [2022-08-05 17:47:45 +0000] [11] [ERROR] Exception in worker process ""hello, I am getting this error while uploading my Django to the heroku""" -
Field 'id' expected a number but got ' '. But I dont even have a field named 'id'
we are making a web app using Django, postgresql, and reactjs. I am creating two models and connecting them using one to one relationship in django. The view file is literally empty. This is models.py file I changed the primary key fields for each table to avoid the error but it isnot solving anything.I am new to Django. Please help. from django.db import models class userInfo(models.Model): Username=models.CharField(max_length=100,primary_key=True) Password=models.CharField(max_length=100) def __str__(self): return self.Username class rentDetails(models.Model): user=models.OneToOneField( userInfo, on_delete=models.CASCADE, primary_key=True ) floor_no=models.CharField(max_length=20,default=True) distance=models.IntegerField(default=True) location=models.CharField(max_length=200,default=True) area=models.IntegerField(default=True) no_of_rooms=models.IntegerField(default=True) price=models.IntegerField(default=True) property_choices=[ ('hostel','Hostel'), ('house','House') , ('room','Room'), ('flat','flat') ] property_type=models.CharField( max_length=10, choices=property_choices, ) images=models.ImageField(upload_to='uploads/',null=True) -
Docker Django 1.7 django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates:foo?
I know this question is similar to many prior cases, for example: [1]: How to resolve "django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: foo" in Django 1.7? , but my issue was happened while I was running my Docker images. The Django application compiled successfully while I was on locally, but after I built my docker image and tried to run it. It shows " Application labels aren't unique: foo". I guess it might related to "Cache". I thought on local, there might be a cache, but no cache in docker image, so the compiler doesn't recognize the name of the label? That's the issue came from? -
Is it a bad practice to write an interactive step on a unit test?
From what I understand the main purpose of unit testing is to automatize testing. But consider the following example: I have an application that needs the user to read a QR code. When the user reads the QR code, the user is connected to another application. My application then checks if the user is connected. So, the only way that I think to test this scenario, is to when running the test case, display a QR code in the console so that the developer read it. But I think it's a bad practice. So my question is: "Is it a bad practice to write an interactive step on a unit test ?" Can anybody give me another way to test this scenario? Maybe there is some kind of tool that I dont know? I'm using django in this application. Thank you. -
How to properly join two Django query sets
I have the following logic implemented in an endpoint. def get(self, request, branchName, stack, resultType, buildNumberMIN, buildNumberMAX, format=None): try: # use ONE query to pull all data relevant_notes = Notes.objects.filter( branchName=branchName, stack=stack, resultType=resultType) # filter on the endpoint parameters (range of numbers) requested_range = relevant_notes.filter( buildNumber__gte=buildNumberMIN, buildNumber__lte=buildNumberMAX) # also pull latest note -- regardless of requested range latest_note = relevant_notes.latest('buildNumber') # join the notes return_set = requested_range | latest_note #serialize the data serializer = serializers.NoteSerializerWithJiraData( return_set, many=True) return Response(serializer.data) except Notes.DoesNotExist: return Response({"message": f"No notes found"}, status=404) Context: the logic is put simply, fetch a range of notes, but also include the latest note based on the url parameters. If the range of notes contains no data, still return latest. The issue I am facing is AttributeError at /api/v2/notes/Test/Test/Test/1/2/ 'Notes' object has no attribute '_known_related_objects' It is possible that it does not like that I add attempting to combine a query set with a single object... -
Accessing an object based on foreign key link in Django template
I currently have some models linked using foreign keys (reduced) models.py: class Saga(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=1000) startChapter = models.PositiveIntegerField() endChapter = models.PositiveIntegerField() class Arc(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=1000) saga = models.ForeignKey(Saga,on_delete=models.SET_DEFAULT,default=Saga.get_default_pk) startChapter = models.PositiveIntegerField() endChapter = models.PositiveIntegerField() class Clip(models.Model): description = models.CharField(max_length=200) arc = models.ForeignKey(Arc,on_delete=models.SET_DEFAULT,default=Arc.get_default_pk) chapter = models.PositiveIntegerField() viewers = models.ManyToManyField(User, through='ClipViewer') author = models.ForeignKey(User,on_delete=models.SET_NULL,null=True, related_name='author_of') Basically all Sagas have a set of associated arcs and every arc has a list of associated clips. What I want to do is get my Sagas, Arcs and Clips through my API calls and then loop through each saga, getting the associated arcs for that saga and then loop through the arcs, getting the associated clips for that arcs, eg: Saga 1 has arcs 1,2,3 Arc 1 has clips 1 & 2 Arc 2 has clip 3 Arc 3 has clips 4 & 5 Saga 2 has arc 4,5.... But templates seem too limited to do this kind of querying, I can't do anything like get the list of associated arcs for a given saga or anything like that and being told: Because Django intentionally limits the amount of logic processing available in the template language, it is … -
Is there a way to add list in a django model class?
I'm a django beginner and trying to make a project from scratch. My models are : class Citizen(models.Model): name = models.CharField(max_length=64, unique=False) citizen_id = models.CharField(max_length=10, unique=True) def __str__(self): return '{} by {}'.format(self.name, self.citizen_id) class Manager(models.Model): name = models.CharField(max_length=64, unique=False) manager_id = models.CharField(max_length=10, unique=True) def __str__(self): return '{} by {}'.format(self.name, self.manager_id) class Message(models.Model): sender = models.ForeignKey(Citizen, Manager, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(Citizen, Manager, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=1200) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message class Meta: ordering = ('timestamp',) class Centre(models.Model): pass In Centre , there's gonna be one manager and then a lot of citizens. What should I do here? Should I add a list of citizens? Is that possible? -
Why aren't failed Django queries more descriptive?
A python dictionary will throw a keyerror that describes what key was searched for and failed. Why does running .objects.get() on a queryset not describe the parameters passed in that failed to return a model, or returned more than one? Is this something that could be added to Django.db? -
My custom save_user function in allauth does not work
I am trying to store the profile picture of the user when he is logging in with google. So, I have modified the save_user in following way: from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): print("called1") def save_user(self, request, user, form, commit=True): print("called2") user = super(MyAccountAdapter, self).save_user(request, user, form, commit=False) data = form.cleaned_data user.picture = data.get("picture") print("called3") user.save() print("called4") pass But for some reason my modified save_user doesn't work. It is to be noted that I used print to know if the code inside my modified function was called. But When I run the application I only get called1 and called4 printed in compiler but not called3 and called2. Note: I have already added ACCOUNT_ADAPTER in settings.py. -
How to pass a function with parameters from view to template in Django?
I am passing a function from views.py to a template in Django. This function takes a date argument and returns the difference between it and today's date views.py: def days_until(date1): td = datetime.date.today temp = date1 - td return temp.days def index(request): entries = Entry.objects.all() return render(request, 'index.html', {'entries' : entries, 'days_until' : days_until}) index.html: {% for entry in entries %} <div> {{ days_until(entry.date) }} </div> {% endfor %} This code doesn't work and returns this error: Could not parse the remainder: '(entry.pwExp)' from 'days_until(entry.pwExp)' I'm assuming that I am not calling days_until incorrectly. How should I be passing entry.date into this function?