Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I save form having 1 foreign key in model?
Models.py class CompanyStudents(models.Model): company = models.ForeignKey(Company, default=None, on_delete=models.CASCADE) student_id = models.CharField(default=None, max_length=100) def __str__(self): return self.student_id Forms.py class CompanyStudentForm(ModelForm): class Meta: model = CompanyStudents fields = '__all__' Views.py def applycompany(request): if request.method == 'POST': form = CompanyStudentForm(request.POST) if form.is_valid(): form.save() return redirect('success') template <form method="POST" action="{%url 'applycompany' %}"> {% csrf_token %} <input type="hidden" name="company" value="{{ comp.company_name }}" /> <input type="hidden" name="student_id" value="{{user}}" /> <input type="submit" value="Apply"/> </form> What should I do so that the form gets saved? In the template, I'm sending data of the foreign key in the input tag. What changes should I do so that it gets the required data? When I print "forms.errors" it shows "select the data for "company" which is foreign-key. -
Django save() method saving 2 out of 3 fields. No errors are found for the third but won't save
I'm trying to modify the field value upon clicking on a tokenized link. It all works as expected except one out of 3 fields does never get updated ('company_name'). The rest do update. Very simple to showcase what's happening here. models.py (relevant fields only) class CustomUser(AbstractUser): id = models.BigAutoField(primary_key=True) work_email = models.EmailField(unique=True, null=True, blank=True, default="") work_email_verified = models.BooleanField(default=False) company_name = models.CharField(name='Company Name',max_length=100, null=False, blank=True, default="") first_name = models.CharField(max_length=50, null=False, blank=False, default="") last_name = models.CharField(max_length=50, null=False, blank=False, default="") views.py class ConfirmWorkEmailView(View): def get(self, request, uidb64, token, backend='django.contrib.auth.backends.ModelBackend', *args, **kwargs): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and work_email_activation_token.check_token(user, token): user.work_email_verified = True user.first_name = 'Rodrigo' user.company_name = 'Cool' user.save() login(request, user, backend) messages.success(request, ('Your company email and name have been verified')) return redirect('home') else: messages.warning(request, ('The verification link was invalid, possibly because it has already been used')) return redirect('home') When I reproduce the user's steps and go to the tokenized link, the DB gets successfully updated to True for work_email_verified. Thinking that it'd be something related to the field I also tested changing the name to a ramdon one "Rodrigo" in this case, it turns out first_name also … -
JavaScript Uncaught TypeError: Cannot read property 'style' of null: Onclick makes page disappear [duplicate]
In a django project, I've set up a JavaScript function to select/block certain pages. I have another JavaScript function for the pages that are being loaded. This function has an onclick event listener that submits text to a form field. The problem I'm having is that when I click a button to add text to a form field, the entire page disappears. The exact error message showing in the console is... Uncaught TypeError: Cannot read property 'style' of null at showPage (players:6382) at HTMLButtonElement.button.onclick (players:6388) Here's the function controlling showing/blocking of individual pages. function showPage(page) { document.querySelectorAll('tbody').forEach(tbody => {tbody.style.display = 'none';}) document.querySelector(`#${page}`).style.display = 'table-row-group'; ---(This line in error message) } document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('button').forEach(button => { button.onclick = function() { showPage(this.dataset.page); ---(This line in error message) } }); }); Here's an example from the html template of a button targeted by this function. <button class="posbutton" data-page="page1">QB</button> This is the function that submits text to a form field. function myFunction(txt) { var myTxt = txt; if (txt.includes('QB')) { document.getElementById("QB_name").value = myTxt; } else if (txt.includes('RB')) { document.getElementById("RB_name").value = myTxt; } else if (txt.includes('WR')) { document.getElementById("WR_name").value = myTxt; } else if (txt.includes('TE')) { document.getElementById("TE_name").value = myTxt; } else if (txt.includes('K')) { document.getElementById("K_name").value … -
Django - TemplateDoesNotExist at /performance/
I am just beginner in Django. At starting i'm trying to buit a basic applications. Now faced an issue that i'm trying to load a html file named 'main.html' from **src/products/templates/products/main.html** but django loader loads it form **src\templates\products\main.html**. What can i do for it now? codes of main urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('performance/', include('products.urls', namespace='products')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) code of products applications urls.py from django.urls import path from .views import chart_select_view app_name = 'products' urlpatterns = [ path('', chart_select_view, name = 'main-product-view') ] and code of products applications views.py from django.shortcuts import render from .models import Product def chart_select_view(request): return render(request, 'products/main.html', {}) Wish i would get help form someone 🙂 Thank you Note: I've migrated applications properly -
Problem with missing Distutils folder after upgrading from Ubuntu 19.10 to 20.04
Hi I was hoping that someone can help with an issue I'm having with virtualenv, and virtualenvwrapper after upgrading from 19.10 to 20.04. I had a fully functional Django application in my Dev environment on Ubuntu 19.10, but since updating to 20.04 my virtualenv isn't working correct. Specifically it says that: FileNotFoundError: [Errno 2] No such file or directory: '/usr/lib/python3.7/distutils/__init__.py I've checked the path, and the distutils folder is missing, but I'm not sure how I go about fixing this. I was hoping that someone here could help me? There is a disutils folder in /usr/lib/python3.8, but when I copy that across to my python3.7 folder, I just get a different error Any help would be greatly appreciated, thanks in advance -
Django jinja values not passed in correctly to iframe url (open streetmap)
I have tried several ways to incorporate an openstreetmap via iframe into my django app. I can see the map fine and can zoom in or out, but it is always a map of Antigua. I want to embed a small map in my django template and pass in latitude and longitude from jinja. It makes no difference whether I pass in hard coded lon and lat or jinja, I still get the same map in openstreetmaps. I started with this template from the openstreetmaps wiki https://wiki.openstreetmap.org/wiki/OpenLinkMap : <iframe width="420" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.openlinkmap.org/small.php?lat=<LAT>&lon=<LON>&zoom=<ZOOM>" style="border: 1px solid black"></iframe> No matter whether I hard code or put dynamic values, I see a map of Antigua. I tried passing in the parameters from jinja: <iframe width="420" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.openlinkmap.org/small.php?lat={{ li.latitude }}&lon={{ li.longitude }}&zoom=10" style="border: 1px solid black"></iframe> That didn't work, so I tried just typing in the long and lan, and I still get Antigua: But the following works fine as a url link and passes in the correct parameters: <a href="https://www.openstreetmap.org/#map=12/{{ li.latitude }}/{{ li.longitude }}" target="_blank"><b>View Larger Map</b></a> I am new to openstreetmaps, django, and jinja and cannot see where I am making an error. -
downloading files from firebase storage, python
I'm trying to download files from my firebase storage with python, and I can't seem to figure out how. I've tried a bunch of different tutorials. So I have the credentials set up as an enviromental path: os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials.json' and then based off what I've seen online, I tried this to donwnload the file from storage. In firebase storage it's just located in the base directory, so I did: storer = storage.child("project_name.appspot.com").download("path_to_file_in_storage") I already have initialized firebase using this: cred = credentials.Certificate('credentials.json') firebase_admin.initialize_app(cred) This clearly is incorrect, so how would I go about doing this? -
Delete all files and clear all references created through 'python mange.py collectstatic' command in Django
I am a newbie here and I want to know that suppose I have executed the command python manage.py collectstatic command and then I want to delete all the files created there and delete all the references created through this command. Is it possible? Because After sunning this command some of my code not working properly so I want to reverse this command or we can say I want to clear all the execution done by this command. Can I do this thing in Django? I am using Django 2.2 here. -
PostCreateView returning Page Error 404 raised by PostDetailView
I am trying add a CreateView in my Django project but I am getting a Page 404 Error raised by PostDetailView for some reason I don't undertand why. I am assuming it is because of the url pattern but I have revised it several times but still stuck. Here is the full error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/score/new_design/ Raised by: score.views.PostDetailView Here is the Models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) design = models.ImageField(blank=False, null=True, upload_to=upload_design_to) Here is the view.py class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'design'] success_url = '/' template_name = 'score/post_form.html' # <app>/<model>_<viewtype>.html success_message = "Your Post has been submitted" def form_valid(self, form): form.instance.designer = self.request.user return super().form_valid(form) Here is the urls.py urlpatterns = [ path('', PostListView.as_view(), name='score'), path('<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('new_design/', PostCreateView.as_view(), name='post-create'), Here is the link to the create view: <a class="dropdown-item" href="{% url 'score:post-create' %}">New Post</a> -
How to create a simple graph from dictionary in my Django project?
I created a simple dictionary in my Django view and I want to make a simple graph from it and show it in my template. The dictionary ("sum_by_date") is of working hours per date e.g. {'2020-10-09':1.5,'2020-10-10':2}. I want a graph with bars, the dates on x - axis and the hours on y-axis and a line between the dots. What is the simplest way to do so? I want something equivalent to : pyplot.bar(*zip(*sum_by_date.items())) of matplotlib.pyplot. Thank you -
Django model field automatically incremented, but not according IDs
I am a beginner with Django and I have been searching around this but not reaching a satisfactory solution. Let's say I would like to create a Model to identify a given chair of a table located in a given room of a house, and also its height (of the chair). Consider then records like the following: House Room Table Chair Chair Height (cm) White House Kitchen 1 1 75 White House Kitchen 2 1 55 White House Kitchen 2 2 65 Buckingham Palace Main State Room 1 1 70 Buckingham Palace Main State Room 1 2 70 The compound primary key should include House, Room, Table and Chair. The model I have created does not allow me to increment the integer value of the Chair, once the House, Room and Table are introduced. Is there a way to do that in the models.py file? I do not want to allow the user to introduce any number for the chair field, but to introduce the corresponding following one according to the house, room and table already introduced (There should not be, for example, a 3rd chair without existing the 1st and the 2nd ones). I have been searching the AutoField … -
social-auth-app-django Login for a Django Project not working
I am trying to add Facebook login for my Django Project, but I keep getting: Facebook has detected djangosociallogin isn't using a secure connection to transfer information. and Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. Here is the steps for what I did: 1: pip install social-auth-app-django 2: Add the social_django to your INSTALLED_APPS:'social_django', 3: Update the MIDDLEWARE_CLASSES by adding the SocialAuthExceptionMiddleware to the end of it:'social_django.middleware.SocialAuthExceptionMiddleware', 4: update the context_processors inside TEMPLATE: 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', 5: Add the AUTHENTICATION_BACKENDS in your settings.py file: AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.github.GithubOAuth2', 'django.contrib.auth.backends.ModelBackend', ) 6: Update the urls.py add the social-auth-app-django URLs: path('oauth/', include('social_django.urls', namespace='social')), 7: Added App ID and App Secret in the settings 8: In the developers facebook added Platform and add a website. For the Site URL put http://localhost:8000 and then in the App Domains put just localhost 9: Here is the login Template <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> <small class="text-muted ml-2"> <a … -
Django Stripe Payment: Invalid card object: must be a dictionary or a non-empty string
When I try to send a payment to stripe I get an error message: "Invalid card object: must be a dictionary or a non-empty string." The payment is for a set amount of 5 Euros. I am using the credit card number 4242 4242 4242 4242 to test the payment. I can see the 'Post' parameters to stripe are all correct apart from the 'stripe_id'. I have been trying to see what is wrong with 'stripe_id' but I am at a loss. Can anyone help me find what is wrong with my code? checkout.html: {% extends "base.html" %} {% load static from staticfiles %} {% load bootstrap_tags %} {% block head_js %} <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript" src=""> //<![CDATA[ Stripe.publishableKey = '{{ publishable }}'; // ]]> </script> <script type="text/javascript" src="{% static 'js/stripe.js' %}"></script> {% endblock %} {% block content %} <form action="{% url 'checkout' %}" method="post" id="payment-form" class="col-md-6 col-md-offset-3"> <legend>Payment Details</legend> <div id="credit-card-errors" style="display: none;"> <div class="alert-message block-message error" id="stripe-error-message"></div> </div> <div class="form-group col-md-6"> {{ payment_form|as_bootstrap }} </div> {% csrf_token %} <div class="form-group col-md-12"> <input class=" btn btn-primary" id="submit_payment_btn" name="commit" type="submit" value="Submit Payment of 5 Euros"> </div> </form> {% endblock %} forms.py: from django import forms class MakePaymentForm(forms.Form): print("MakePaymentForm...") MONTH_CHOICES … -
django how can i get the request before the main urls.py
in django i got urlpatterns = [ path("something/", include("something.urls")), path("something2/", include("something2.urls")), ] i want to see details about the request before they come to "urlpatterns" i want to get the request object to see the ip everytime in all the urls and not metter when he want to go even if he go to "http://mywebsite.com/blablabla" i want to see the request and be able to send him back status 400 if i dont like this ip also i want to send all the requests to a statistic.py and analyze all the request to see stuff like if they got cookie and see the META of the request how can i achieve this? -
different extend from different applications
I'm trying to create one template for all apps, but with different base (related to app). i'm using django_hosts: hosts.py: from django_hosts import patterns, host host_patterns = patterns('', host(r'app1', 'app1.urls', name = 'app1'), host(r'(app2|application2)','app2.urls', name = 'app2'), ) tree: templates/document.html app1/templates/app1/base.html app2/templates/app2/base.html templates/document.html: {% extends base %} And the idea is: when I go to http://app1.example.com/document/ i will see templates/document.html extended with app1/templates/app1/base.html, and if I go to http://app2.example.com/document/ or http://application2.example.com/document/ extended with app2/templates/app2/base.html generally it works if I use in app1/views.py: (...) context={ 'base' : 'app1/base.html' } return render(request,'document.html', context) app2/views.py: (...) context={ 'base' : 'app2/base.html' } return render(request,'document.html', context) But I want to remove context 'base' from every views' def . I can't use app1/context_processors.py and app2/context_processors.py, because it would override themselves, because context_processors are global not app local. There's an idea: #main/contexts.py from django.core.urlresolvers import resolve def appname(request): return {'appname': resolve(request.path).app_name} but i don't have urls.py with includes, because i have hosts definition.... -
Letting Users Delete their own accounts in Django
In the Django 2.2 docs , it states the following : "is_active " is a Boolean. Designates whether this user account should be considered active. We recommend that you set this flag to False instead of deleting accounts; that way, if your applications have any foreign keys to users, the foreign keys won’t break. My question is this, If I had a website, and I gave my users the ability to delete their own accounts by following this practice, wouldn't my database be filled with non-active accounts once my website gains a bit of traffic? What would be the best method to letting users ( without staff or super user status ) on your website delete their own accounts properly in Django 2.2 ? Thank you in Advance for any Help -
ValueError: not enough values to unpack while running unit tests Django ModelViewSet
Am testing an endpoint that retrieves data using a ModelViewSet, and am passing a param via a URL to it to get data but am getting this error when I run the unit tests: for key, value in query: ValueError: not enough values to unpack (expected 2, got 1) This is how I have structured my tests , plus some dummy data for testing : class TemplateData: """Template Mock data.""" step_get_data = { "param": "step" } block_get_data = { "param": "block" } get_no_data = { "param_": "block" } class TemplateViewTests(TestCase, TemplateData): """Template Tests (Block & Step).""" def setUp(self): """ Initialize client, Step and Block id and data created. """ self.client = APIClient() self.block_id = 0 self.step_id = 0 self.create_block_step_data() def create_block_step_data(self): """Create ProcessVersion, Step, & Block mock data.""" self.process_version = ProcessVersion.objects.create( tag="TESTING_TAG", is_process_template=False, status="IN EDITING", attr_map="TESTING_ATTR", loan_options=None ) self.step = Step.objects.create( version=self.process_version, is_process_template=True, title="TESTING", help_text="TESTING", order=1, slug="slug", can_be_duplicated=False, max_duplicated_number=2, ) self.step_id = self.step.pk self.block_id = Block.objects.create( step=self.step, is_process_template=True, title="TESTING", information_text="This is testing " "information", order=1, depending_field="depending_field", visibility_value="visibility_value", slug="slug", can_be_duplicated=False, max_duplicated_number=2, ).pk self.process_version_1 = ProcessVersion.objects.create( tag="TESTING_TAG", is_process_template=False, status="IN EDITING", attr_map="TESTING_ATTR", loan_options=None ) self.step_1 = Step.objects.create( version=self.process_version_1, is_process_template=True, title="TESTING", help_text="TESTING", order=1, slug="slug", can_be_duplicated=False, max_duplicated_number=2, ) self.block_1 = Block.objects.create( step=self.step, is_process_template=True, title="TESTING", information_text="This … -
reactjs django admin page not found
I have project with react and django after running commande npm run build and change django static fiels settings to: 'DIRS': [os.path.join(BASE_DIR, 'frontend/build')], but after build up the project I can't access to django administration "http://localhost:8000/admin/" how can I solve this probleme -
Javascript parse URL as parameter for $.getJSON
I'm trying to parse an URL as paramter together with multiple others in my frontend to send a JSON request to my Django backend, but I receive the well known 404 error - not found. Django urls.py path: path("updateAssignment/<iD>/<body>/<deadline>/<user>/<url>/<game>/<aK>/<seoTitle>/<payment>/<wordCount>/<category>/<state>/", Dashboard.update_assignment, name="updateAssignment") Javascript $.getJSON Request function updateAssignment(assignmentId){ const assignmentUpdateEndpoint = "/updateAssignment/"; let body = encodeURIComponent(document.getElementById("Assignment-Body"+assignmentId).value); let deadline = encodeURIComponent(document.getElementById("Assignment-Deadline"+assignmentId).value); let user = encodeURIComponent(document.getElementById("Assignment-User"+assignmentId).value); let url = encodeURIComponent(document.getElementById("Assignment-URL"+assignmentId).value); let game = encodeURIComponent(document.getElementById("Assignment-Game"+assignmentId).value); let additionalKeywords = encodeURIComponent(document.getElementById("Assignment-Additional-Keywords"+assignmentId).value); let seoTitle = encodeURIComponent(document.getElementById("Assignment-SEOtitle"+assignmentId).value); let payment = encodeURIComponent(document.getElementById("Assignment-Payment"+assignmentId).value); let wordCount = encodeURIComponent(document.getElementById("Assignment-WordCount"+assignmentId).value); let category = encodeURIComponent(document.getElementById("Assignment-Category"+assignmentId).value); let state = encodeURIComponent(document.getElementById("Assignment-State"+assignmentId).value); assignmentId = encodeURIComponent(assignmentId); let reqUrl = assignmentUpdateEndpoint + assignmentId + "/" + body + "/" + deadline +"/" + user + "/" + url + "/" + game + "/" + additionalKeywords + "/" + seoTitle + "/" + payment + "/" + wordCount + "/" + category + "/" + state + "/"; $.getJSON(reqUrl).done((response) => { }); I have already tried encoding it via various methods but it just would not work. Help would be great. -
Django: Reverse for 'image_upload' with no arguments not found. 1 pattern(s) tried: ['image_upload/(?P<user_post>[0-9]+)$']
I'm trying to pass primary key as URL argument from CreatePost to UploadImage view but I'm constantly getting an error even if I see primary key in URL. I'm new to Django, so please help me :) views.py class CreatePost(CreateView): model=shopModels.UserPost template_name='shop/create_post.html' fields='__all__' def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['category'].widget.attrs['class'] = 'form-control' form.fields['category'].widget.attrs['oninvalid']="this.setCustomValidity('Ovo polje je obavezno!')" return form def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('login') return super(CreatePost, self).dispatch(request, *args, **kwargs) def get_success_url(self): return reverse('image_upload',kwargs={'user_post':self.object.id}) class UploadImage(CreateView): model=shopModels.Image template_name='shop/images_upload.html' fields='__all__' def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return reverse('login') return super(UploadImage, self).dispatch(request, *args, **kwargs) urls.py ... path('create_post/',views.CreatePost.as_view(),name="create_post"), path('image_upload/<int:user_post>',views.UploadImage.as_view(),name="image_upload"), ... models.py class UserPost(models.Model): id = models.AutoField(primary_key=True) user=models.ForeignKey(Account,on_delete=models.CASCADE) title=models.CharField(max_length=255) text=models.TextField(null=True) category=models.ForeignKey(Category,null=True,on_delete=models.SET_NULL) is_used=models.BooleanField(default=False) price=models.IntegerField(default=0) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.title + ' | ' + str(self.user) def get_absolute_url(self,*args,**kwargs): return reverse('image_upload', kwargs={'user_post':self.id}) class Image(models.Model): id = models.AutoField(primary_key=True) user_post=models.ForeignKey(UserPost,default=None, on_delete=models.CASCADE) image=models.ImageField(null=True,blank=True,upload_to='images/') def __str__(self): return self.user_post.title def get_absolute_url(self): return reverse('index') -
how do I make toast messages work together
I'm working on a toast message setup where when if multiple of them are in bound they're not visible except the one in the front (so maybe a margin of 15px would help) and display them on the bottom-corner of the screen(fixed) doesn't change position when scrolling and make them disappear after 3 secs one by one. How do I go about solving this with javascript? Thnx for any help. {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="color-green"> <div class="color-white"> <div class="icon-success"> <i class="fas fa-check icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'info' %} <div class="color-blue"> <div class="color-white"> <div class="icon-info"> <i class="fas fa-info icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'warning' %} <div class="color-orange"> <div class="color-white"> <div class="icon-warning"> <i class="fas fa-exclamation-circle icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'error' %} <div class="color-red"> <div class="color-white"> <div class="icon-cross"> <i class="fas fa-times icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% endif %} {% endfor %} {% endif %} .color-green{ bottom: 0; position: absolute; background-color: #40ff00; box-shadow: 4px 4px 16px 0 rgba(0, 0, 0, 0.05); margin-bottom: 10px; margin-left: … -
How to edit Django models
Let's say that I have some data on my model and that I want to edit it, how can I do that without deleting the model or recreating a new one like I would do it on the admin panel? -
Saving python datetime value to a mySQL timestamp with timezone field
I am baffled. I assign to a Django model field as follows: listing.modify_date = datetime.now() where the field is defined as: listing_modify_date = models.DateTimeField(default=datetime.now, blank=True) Printing out the assigned value... print("modify_date=" + str(listing.modify_date)) I get: modify_date=2020-12-18 21:35:09.178392 But the mySQL table is not updated. However: non-"timestamp with timezone" fields in the row are updated; The following query in pgAdmin updates modify_date: update public.listings_listing set listing_modify_date = '2020-12-01 15:00:01' I have run out of things to try. Help appreciated. -
How to render all fields in m2m with a through model?
How could I manage to render something similar to this picture (https://i.imgur.com/3LPGbys.png), where I have my toppings as checkboxes and the amount as a normal input field. E.g. Lets say I have these models (this example is completely fictional) #models.py class Order(models.Model): pizza = models.ForeignKey(Pizza) toppings = models.ManyToManyField(Topping,through='QuantityTopping') class QuantityTopping(models.Model): order = models.ForeignKey(Order) topping = models.ForeignKey(Topping) quantity = models.IntegerField(default=0) class Topping(models.Model): topping = models.CharField(max_length=200) I tried several things, including: Attempt 1. Problem: it just renders the toppings, but not the quantity in any way. Not good, unfortunately. #forms.py class OrderForm(ModelForm): class Meta: model = Order fields = ['pizza', 'toppings'] Attempt 2: I tried to make a separate form only for toppings (my through model). Problem: It managed to all topping as checkboxes (yay!) but only 1 input field. Bummer. #forms.py class ToppingsForm(ModelForm): class Meta: model = QuantityTopping fields = ['topping', 'quantity'] widgets = {'topping':forms.CheckboxSelectMultiple,} Any ideas? thanks in advance! -
Django Exception Value: invalid filter error:
I am trying to display a division result in float. So I just arrived to this conclusion that a filter could be helpful, as below: in views.py: from django import template register = template.Library() @register.filter def div(value, div): return round((value / div) * 5, 2) in template: {% for post in Posts %} {{ post.likes|div:post.total_like }} {% endfor %} where value=post.likes and div=post.total_like but it gives the something like importing error: Invalid filter: 'div' I also tried to put div function/filter in a different file like mfilteter.py and import it in template like {% load mfilteter %} but didn't work!