Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Mixin called twice and returns diferent responses
I've been strugglig with this bug for a week. I created a mixin BaseMixin to provide common data for two views EmailView and PanelView. class BaseMixin(ContenxtMixin): def get_context_data(self, hash, **kwargs): context = super().get_context_data(**kwargs) try: ficha = self.get_ficha(hash) print("TRY") except Exception as e: print("EXCEPT") # more code return context def get_ficha(self, hash): pass class EmailView(BaseMixin, TemplateView): template_name = "app/cotador/cotacao_email_produtividade.html" def get_context_data(self, hash, **kwargs): context = super().get_context_data(hash, **kwargs) # more code return context class PanelView(BaseMixin, TemplateView): login_url = '/login/' redirect_field_name = 'next' template_name = "panel/proposta.html" def get_context_data(self, hash, **kwargs): context = super().get_context_data(hash, **kwargs) # more code return context Whenever I call EmailView it calls the BaseMixin twice. First with the hash parameter, going into the try block and the second time lacking the hash and raising an exception. I noticed this behaviour by printing from within the try/except block: TRY INFO 2022-07-27 20:33:04,954 "GET /minhas-propostas/proposta/951c18b30ba2999860fa3324199d1272ae0275480b6453f54f90e348fe834bad HTTP/1.1" 200 92114 EXCEPT ERROR 2022-07-27 20:33:06,200 Internal Server Error: /minhas-propostas/proposta/Roboto-Regular.ttf And, I have no idea why, Roboto-Regular.ttf shows up in the url instead of the hash!!! Then, when PanelView is called it works well with no errors and is called only once: TRY INFO 2022-07-27 20:44:34,664 "GET /cotacao-produtividade/print/487af3b7bf8e2615702ca662fe8746889750d67264e4ed10a8ada1e67f6ac9ed I dont know how usefull it can be, … -
Django some static file are accessible while other new static files in same folder are not accessible
Some static files in Django are accessible but other new static files in the same folder are not accessible I renamed the previously working file and then named it same as it was before and then browser won't detect that file either. I am not sure what the issue is here. -
Django: how to get HTML input field value to django view?
i want to get a value in an input to a django views, this is not a form as i am not trying to submit any form, i just need the value that is in the input field this is the html template <input readonly name="ref_code" type="text" value="{{ request.user.profile.recommended_by.profile.code }}"> this is my django views code = str(request.GET.get('ref_code')) print("This is the code:" + code) It keep printing This is the code: None NOTE: i have also tried using request.POST.get("ref_code") it did not still work What might be the issue? -
Need Help to resolve error in running djangoQ Task
I am trying run a simple djangoQ task, but I get an error at the end from the djangoQ library. def welcome_mail(): body_to_sent = 'test' print(body_to_sent,"body_to_sent",settings.EMAIL_HOST_USER) EMAIL_HOST_USER = settings.EMAIL_HOST_USER print('about to email') from_email = EMAIL_HOST_USER to_email = [] to_email.append("xx@gmail.com") subject = 'New Fabric - Standalone Nexus 9k Leaf/s for ' email = EmailMessage(subject, body_to_sent, from_email, to_email) email.content_subtype = "html" email.send() Error: 13:59:56 [Q] ERROR Failed [spring-nineteen-muppet-artist] - 'NoneType' object is not callable : Traceback (most recent call last): File "/home/sgang31/.venvs3/netadc3/lib64/python3.6/site-packages/django_q/cluster.py", line 432, in worker res = f(*task["args"], **task["kwargs"]) TypeError: 'NoneType' object is not callable I don't have any arguments to pass to this function, so not sure about the error. -
How to match URL with ?code=string&state=string?
How can I match a url that looks like, for example, this: "login/?code=string&state=string". I'm very new to Python regex and regex in general, so I apologize if this is too simple for a Stack Overflow question. This is what I'm currently trying: re_path(r'^login/(?:code=(?P<code>\w+)/)(?:state=(?P<state>\w+)/)$', views.login, name='login'), -
One to many model POST using API View
I have this model I want to POST this to my location endpoint { "location": { "latitude": "1.23456789", "longitude": "1.23456789", "resources": [ { "url": "s3/locations/1/es.mp4", "name": "lorem_1" }, { "url": "s3/locations/1/en.mp4", "name": "lorem2" } ] } My goal is to add a location with many resources and to do it through a single locations endpoint using API Views This is my view: class LocationView(APIView, api_settings.DEFAULT_PAGINATION_CLASS): queryset = Location.objects.all() permission_classes = (permissions.AllowAny, ) serializer_class = LocationSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return response.Response(request.data) And this is my serializer: class LocationSerializer(serializers.ModelSerializer): resources = ResourceSerializer(source='resource_set', many=True, read_only=True) class Meta: model = Location fields = ('id', 'latitude', 'longitude', 'resources') -
Python - Space before and after operators like =, +, - etc
following the PEP 8 rules for python, you should use spaces before and after operators, for example "x = 1 + 2". I follow this convention and i don't like it without spaces. Currently im working on a Django Project and i want to include a .html document with a keyword. > {% include "pagination.html" with page = shares %} If i run it like written above i get a keyword error: "with" in 'include' tag needs at least one keyword argument. Without the spaces before and after the = it works without problems. Is that the only way or is there an other way? Thank you in advance. -
override mongoengine query mechanism
Let's say that I have 2 mongo collections, being handled using mongoengine at server. class UserA(Document): first_name = fields.StringField() last_name = fields.StringField() country = fields.StringField() class UserB(Document): # completely independent of UserA at storage layer full_name = fields.StringField() country = fields.StringField() UserA and UserB are 2 separate collections (stored separately in database) having separate entries and have nothing to do with each other at the storage layer. UserA can be converted to UserB with this formula at compute (server) layer. def convert_to_userb(user_a): user_b = UserB() user_b.full_name = user_a.first_name + " " + user_b.last_name user_b.country = user_a.country return user_b Now, for some reason I want to override the objects() call in mongoengine of UserB to also fetch data from UserA. Something like @queryset_manager def objects(doc_cls, queryset): actual_results = <Some form of UserA.objects(query_set)> # result that one would get normally without any override additional_results = convert_to_userb(<Some form of UserA.objects(query_set)>) return actual_results + additional_results What's the best way to achieve this? Any particular reason why you would recommend against it, if any? -
Whitelabel Django Application and connecting Google and Facebook accounts
We have a web application that runs on say domain.com. We then have whitelabel users that access the application from subdomain.theirdomain.com. Our application is able to connect Google, Facebook, Twitter accounts using our main domain (domain.com) and our integration with each platform. But when whitelabel users want to connect the process shows the name of our application and redirects to our domain (breaking whitelabel). We are looking at creating a generic application on each platform (google, facebook etc) for our whitelabel users on generic domain xyz-connector.com with a generic name and logo. However the users are not logged in on that domain so when the platform redirects to that domain after the user has successfully gone through the authorization\connection process we cannot associate the connection with the user. We need to know which account has just authenticated so we can update the database. What is the best practice for something like this? Using Django 3. Ideally we want our users to connect\authenticate their accounts directly from their white labeled subdomain or domain. Rather than having to login to xyz-connector.com. Can we share sessions? Or do these services (facebook, google) allow us to pass custom variables they will pass back to … -
Django: unsupported operand type(s) for -: 'method' and 'int' when creating a function in model class
i am trying to get the get_cart_total which is the total price of everything in the cart but i keep getting this error unsupported operand type(s) for +: 'int' and 'method' when i add this line total = int(sum([item.get_total for item in orderitems])). I cannot possibly tell what i am doing wrong or missing? models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) transaction_id = models.CharField(max_length=1000, null=True, blank=True) complete= models.BooleanField(default=False) active = models.BooleanField(default=True) date_ordered = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.customer.user.username} - {self.transaction_id}" @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = int(sum([item.get_total for item in orderitems])) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = int(sum([item.quantity for item in orderitems])) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=1) active = models.BooleanField(default=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.product.title} - {self.order.customer.user.username}" def get_total(self): total = self.product.price * self.quantity return total -
Making a row of cards in bootstrap the height of the highest card
working on a small personal project just to test my ability in Django and Bootstrap. Currently I am able to retrieve a list of quizzes to which their respective details are displayed in an individual card using a for loop, however some of the quizzes have different heights due to the description of each quiz being varied in length. It looks horrific and I am wondering how I can make all of the cards the same height as the highest/tallest card, I've explored using flexboxes for this kind of thing but the first card in the row shrinks in width. Here is my current code and what it looks like in the browser: <div class="row p-2 justify-content-center"> {% for obj in filter.qs %} <div class="col-md-4 mt-4"> <div class="card p-2" id="quiz"> <div class="card-body"> <div class="row"> <div class="col-md-10"> <h5 class="card-title">{{ obj.Name }}</h5> </div> <div class="col-md-2 text-right"> <i class="far fa-heart"></i> </div> </div> <h6 class="card-subtitle mb-2 text-muted">By: {{ obj.Author }}</h6> <h6 class="card-subtitle mb-2 text-muted">Points: {{ obj.Points_Worth }}</h6> <h6 class="card-subtitle mb-4 text-danger">Category: <a href="">{{ obj.Category }}</a></h6> <p class="card-text">{{ obj.Description }}</p> <a href="#" class="btn btn-primary w-100 mt-auto">Play Quiz</a> </div> </div> </div> {% endfor %} </div> Ideally, I'd like all cards to be the same height despite … -
How to Customize Django Serializer Validation Errors?
I tried to customize the serializer validation error myself by adding the status code in response. The validation error is like below. { 'username':[ErrorDetail(string='This field is required.', code='required')], 'firstname':[ErrorDetail(string='This field is required.', code='required')], } I hope to response this like { 'username':'This field is required', 'lastname':'This field is required', 'status': 'failed', 'statusCode': 200 } But I am not sure how to handle above ValidationError. -
POST http://127.0.0.1:8000/cart/ 500 (Internal Server Error) and Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I am currently working on an ecommerce website, unfortunately I have stumbled upon a few errors. When I click the add to cart button I expected to see the terminal displaying 'Action:add ProductId:4' but the termial displays the following error File "C:\Programming\Python\GevengyCart\store\views\cart.py", line 14, in updateItem data = json.loads(request.data) File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\json_init_.py", line 339, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not dict [27/Jul/2022 23:57:05] "POST /cart/ HTTP/1.1" 500 99758 On the console it displays the following errors POST http://127.0.0.1:8000/cart/ 500 (Internal Server Error) updateUserOrder @ cart.js:24 (anonymous) @ cart.js:13 VM2058:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 HTML line for add to cart <button data-product="{{product.id}}" data-action="add" class="update-cart add btn-outline-secondary btn btn-sm text-dark p-0 fas fa-shopping-cart text-primary mr-1"> Add to Cart</button> Here is the cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i = 0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('ProductId:', productId, 'action:', action) console.log('USER:', user) if (user === 'AnonymousUser'){ console.log('Not logged in') }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is logged in, sending data...') var url = '/cart/' fetch(url, … -
Django server returning a 404 out of nowhere
I'm quite new to Django and coding to be honest! I'm facing a problem that appeared out of nowhere when I was finishing a website I can't seem to find anything here that helps with my case. The problem goes with when I try to run the server with python manage.py runserver it gives me this error : System check identified no issues (0 silenced). July 27, 2022 - 17:30:51 Django version 4.0.6, using settings 'sitewilza.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [27/Jul/2022 17:30:53] "GET / HTTP/1.1" 404 2573 Not Found: / [27/Jul/2022 17:30:57] "GET / HTTP/1.1" 404 2573 and the server returns this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in sitewilza.urls, Django tried these URL patterns, in this order: admin/ sobremim [name='sobre'] formacao [name='formacao'] contato [name='contato'] The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. the problem is I did not change anything in both my urls.py, here they are : from django.urls import path, include urlpatterns = … -
Django filter value not in a list
I want to ask how can I filter table object that is not in a list of values. For example this is my list kyc_cat_list = ['Urgent Cases', 'NSB - Alimony Wallet', 'SGP - Site Guard Wallet', 'Suspended Cases - Rejected by BDC'] I want to get all records that are not in the above list records = history_table.objects.filter(KYC_Category not in kyc_cat_list) My Table: class history_table(models.Model): id=models.AutoField(primary_key=True) Dial = models.IntegerField(null=False) Serial = models.IntegerField(null=False, default=0) Bag = models.IntegerField(null=False, default=0) wave_no = models.CharField(max_length=50,null=False, blank=False) type = models.CharField(max_length=100, null=False, blank=False) Today_Date = models.DateField(auto_now_add=True,null=True, blank=True) Today_Date_Time = models.DateTimeField(auto_now_add=True,null=True, blank=True) user = models.CharField(max_length=100) summary = models.CharField(max_length=100,null=False, blank=False) Name = models.CharField(max_length=100,null=True, blank=True) Customer_Address = models.CharField(max_length=100,null=False, blank=False) National_ID = models.IntegerField(null=True, blank=True) Customer_ID = models.IntegerField(null=True, blank=True) Status = models.CharField(max_length=100,null=True, blank=True) Registration_Date = models.DateTimeField(max_length=100,null=True, blank=True) Is_Documented = models.CharField(max_length=100,null=False, blank=False) Needed_Action = models.CharField(max_length=100, null=False, blank=False) Hard_Copy_Type = models.CharField(max_length=100, null=False, blank=False) Request_Status = models.CharField(max_length=100, null=False, blank=False) KYC_Category = models.CharField(max_length=100, null=False, blank=False) -
How to use selenium to access web database in Django?
I am running a Django website using the given dev server command ./manage.py runserver The website contains a submission form with the textfield "title" and a submit button. Once the button is clicked, the input is saved as an object in the Titles table initialized by the following Django model: class Title(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=200, unique=True) I am testing on Python to see if the input is actually saved as an object in the table by using django.test.TestCase and selenium webdriver to write a title and click submit. The problem is that I don't know how to access the objects in the datatable afterwards. Is there a way to access the datatables on the servers using a test method? I am using sqllite for the database. -
Stuck with async python, trying to implement a live chat server
I need abit of help, i cant get chat_message function to work at all, receive works but it doesnt call 'type':'chat ive been trying everything i just cant get it to work, i want receive to call chat_message and then chat_message to append the message to the chat but it doesnt call that function.. consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Message, Room from django.contrib.auth.models import User class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_name, self.room_group_name ) await self.accept() async def disconnect(self, code): await self.channel_layer.group_discard( self.room_name, self.room_group_name ) async def receive(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username,room,message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username, 'room': room }) async def chat_message(self, event): message = event['message'] username = event['username'] room = event['room'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, 'room': room })) @sync_to_async def save_message(self, username, room, message): user = User.objects.get(username=username) room = Room.objects.get(slug=room) message = Message.objects.create(user=user, room=room, content=message) room.py {% extends 'core/base.html' %} {% block title %} {{ room.name }} | {% endblock %} {% block content %} <div class="main"> <h1>{{ room.name }}</h1> </div> <div … -
Django: Why does my validation error not show? The title is a unique field that is checked under clean_title, but it just redirects to the profile?
So my form redirects to my profile page, and the form is saved if has a unique title, however this validation error is not raised on testing. Forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "content", "featured_image", "excerpt", "status"] def clean_title(self): title = self.cleaned_data['title'] if Post.objects.filter(title=title).exists(): raise forms.ValidationError("Title already exists") return title Views.py class CreatePost(View): def get(self, request): return render(request, 'create_post.html', { 'post_form': PostForm, }) def post(self, request): form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.slug = slugify(post.title) post.save() return HttpResponseRedirect(reverse('profile', args=[request.user])) The Post Model from models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blog_posts" ) featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField( User, related_name='blogpost_like', blank=True) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() please be nice im not a pro dev... yet :) -
Azure FormRecognizer from Python SDK fails with message "Specified model not found or not ready"
Trying to submit document for form recognizer created in form recognizer studio using python api. I have tested the form successfully in form recognizer studio. from azure.core.credentials import AzureKeyCredential from azure.ai.formrecognizer import FormRecognizerClient endpoint = "https://eastus.api.cognitive.microsoft.com/" credential = AzureKeyCredential("xxxxxxxxxxxxxxxxxxxxxxxx") form_recognizer_client = FormRecognizerClient(endpoint, credential) path = r"3FE5A953-22D4-4197-B262-E195C3A2CE9F.pdf" with open(path, 'rb') as f: blob = f.read() poller = form_recognizer_client.begin_recognize_custom_forms(model_id='mymodel', form=blob) result = poller.result() get exception azure.core.exceptions.HttpResponseError: (1001) Specified model not found or not ready, Model Id: mymodel Code: 1001 Message: Specified model not found or not ready, Model Id: mymodel I have tried recreating the model with every version of the API available - (2021-9-30-preview, 2022-1-30-preview, 2020-6-30-preview) and still no luck. I am using version 3.1.2 on the sdk. I have tried on version 3.1.0 and 3.2.0b5 and still get the error. -
I can't Read Outlook Email with Python on Linux
I need to do an email automation. For this I need to read an email from Outlook and then send it after configuring some data. The problem is that all the tutorials I've seen say to use the Outlook application installed on the computer. As I use Linux I can't do this. To read the email using Gmail, I did the following: import datetime from imap_tools import MailBox, AND user = "myemail@gmail.com" password = "anypassword" #This password is an "App Password" that I need to configure within Gmail. my_email = MailBox("imap.gmail.com").login(user, password) today = datetime.date.today() list_emails = my_email.fetch(AND(from_="", date=today, subject="")) for email in list_emails: print(email.text) How can I adapt the code for Outlook? PS: In Gmail it is possible to set an "App Password". I didn't get this in Outlook. -
How can I use the single field of the queryset?
I would like to pick the value of "titolo", for example, from the query set. This is my code: class PostUserListView(generic.DetailView): model=Autore template_name=('blogv1/post_list.html') def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) articolo=Articolo.objects.filter(autore__id=context['autore'].id) The articolo is <QuerySet [<Articolo: Ingegneria>]> Models.py Articolo has 3 fields: Titolo (charField),Autore(foreign key) and DataPubblicazione (date field) I'd like to take the value "titolo" from the articolo "ingegneria" -
How can I retrieve brands based on specific category in django?
I can retrieve all product based on specific category_name and Brand name, but i can not retrieve brands name based on specific category_name. How can I do this? My Category Model class Category(models.Model): category_name = models.CharField(max_length=20, unique=True) logo = models.ImageField(upload_to='Category') slug = models.SlugField(unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents") def __str__(self): return self.category_name My Brand Model class Brand(models.Model): brand_name = models.CharField(max_length=40, null=True, blank=True, unique=True) def __str__(self): return self.brand_name My Product Model class Product(models.Model): product_name = models.CharField(max_length=50, blank=False, help_text='Add Product Model Name or Product Name.') category = models.ForeignKey(Category, on_delete=models.CASCADE, default="", blank=True, related_name="Products") brand_name = models.ForeignKey(Brand, on_delete=models.CASCADE, default="", blank=True, related_name="Products") specification = models.CharField(max_length=400, blank=True, default="") price = models.FloatField(blank=False, default=0.00, validators=[MinValueValidator(0.0)], help_text='Price Can not be Less than Zero.') quantity = models.PositiveBigIntegerField(default=0) class Meta: unique_together = [['category', 'brand_name', 'product_name', 'specification'] ] def __str__(self): return self.product_name -
I want to use HTML to dynamically change values and call py functions without screen refreshing
I have an app.py and a bunch of classes related to cards, players, and etc. The cards come from a csv in my local repo. In theory the game works just through the terminal, but obviously it's unintuitive and I figured a website is a good home for displaying the game. I'm currently using flask and I've looked at many many many posts relating to this and the answers are summed up to: Flask can only do that if I refresh the page. Use django or ajax. Rewrite everything in JS and use react. Also as a heads up I'm very much a noob, I only started coding recently and have more of an aptitude for python logic and constructing the game itself, but anything web-related I absolutely suck at as it's a bunch of syntax and annoying nuances that I still don't fully understand. However, if that's really my only option then of course I'll try and familiarize myself but as of right now I don't even know where to start. Any advice would be appreciated, especially if I have the whole thing confused and don't even know what I'm talking about. If you need more code or context … -
NOT NULL constraint failed: users_profile.user_id?
When I update the user's profile I keep getting the error NOT NULL constraint failed: users_profile.user_id. I have tried to fix it by setting the argument commit to False form.save(commit =False) then performing form.save(). My question is how can I update my profile and the user field of the Profile model is populated automatically by the currently authenticated user. Here is my code... users/views.py @login_required(login_url=reverse_lazy("users:login")) def profile(request,slug): if request.method == "POST": form = ProfileUpdateForm(request.POST) if form.is_valid(): form.save(commit = False) form.cleaned_data["user"] = request.user form.save() messages.success(request, "Profile updated successfully!") return redirect("users:profile", kwargs="profile") else: profile = Profile.objects.get(user__username = slug) form = ProfileUpdateForm() context = {"profile":profile,"form":form} return render(request, "users/profile.html", context) users/models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.TextField(blank = True) image = models.ImageField(default = "default.jpg", upload_to = "profile_pics") city = models.CharField(max_length=20,blank = True) url = models.URLField(blank = True) def __str__(self): return f"{self.user.username}'s profile" users/signals.py @receiver(post_save, sender = User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender = User) def create_profile(sender,instance,created,**kwargs): instance.profile.save() users/forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile exclude = ["user"] -
Django: Trying to add 'SHORT_TIME_FORMAT' somehow changes time zone to Chicargo
I required some extra date/time formats in addition to ones Django ships with, sI created these new formats: SHORT_TIME_FORMAT FILE_DATETIME_FORMAT ISO8601_DATETIME_FORMAT. So that I could use them in templates like this: {{ value|date:"SHORT_DATE_FORMAT" }} I created the following code in utils/time/formats.py: from collections import ChainMap from django.utils import formats DJANGO_DATETIME_FORMATS = { 'DATETIME_FORMAT': 'd M Y, H:i', 'DATE_FORMAT': 'j M Y', 'TIME_FORMAT': 'H:i:s', 'SHORT_DATETIME_FORMAT': 'Y-m-d H:i:s', 'SHORT_DATE_FORMAT': 'Y-m-d', 'MONTH_DAY_FORMAT': 'd M', 'YEAR_MONTH_FORMAT': 'Y M', } EXTRA_DATETIME_FORMATS = { 'SHORT_TIME_FORMAT': 'H:i', 'FILE_DATETIME_FORMAT': 'Y-m-d H.i.s', 'ISO8601_DATETIME_FORMAT': 'c', # Compatible with Javascript passing } def set_formats(globals_dict): """Returns a set of datetime formats for use across the whole project Contains a union of the default formats along with the additional ones. To add a new format, one has to perform the following two actions: 1. Add the name of the format to formats.FORMAT_SETTINGS 2. Add a variable with the same name as the variable to the settings.py file with the value assigned to the required format. globals_dict is the globals from the settings.py file """ formats.FORMAT_SETTINGS = frozenset(formats.FORMAT_SETTINGS | EXTRA_DATETIME_FORMATS.keys()) all_formats = ChainMap(DJANGO_DATETIME_FORMATS, EXTRA_DATETIME_FORMATS) for setting, value in all_formats.items(): globals_dict[setting] = value However when I add it to my settings.py file as so: # …