Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to calculate sum previous sum in Python django
I have table project, project has sub project and subproject has developers. Another table sprint, work distribute in sprint 1 2 ..n so on, Each sprint has different developers data. Now How can i calculate sum, current sprint value and percentage complete Using Django Orm. Project has sub project foreign key class project(models.Model): title = models.CharField(max_length=150) project = models.ForeignKey("self", on_delete=models.CASCADE, related_name="subproject", blank=True, null=True) Developers table class Developers(models.Model): quantity = models.FloatField(default=0.0) charge_rate = models.FloatField(default=0.0) project = models.ForeignKey("Project", on_delete=models.SET_NULL, related_name="developers", null=True) Table Sprint class Sprint(models.Model): sprint_name = models.CharField(max_length=150) percentage = models.FloatField(default=0.0) sprint data class SprintsData(models.Model): sprint = models.ForeignKey( "project", on_delete=models.CASCADE, related_name="d", blank=True) percentage = models.FloatField(default=0.0) This is sample data project id name project 1 development null Sub project id name project 1 Homepage 1 2 header 1 3 footer 1 Developers id name quantity rate project (sub project foreign key) 1 developers 5 200 1 2 designer 5 150 2 Sprint id name start_date end_date 1 sprint1 - - SprintsData id sprint project(subproject foreign key) percentage 1 1 1 5 2 1 2 80 Output looks like sprint project sub_project total_sum percentage_complete current_sprint_amount sprint1 development Homepage (quantity*charge_rate) 5 (total_sum)5% -
how to calculate sum in django python
I have 4 table, task has sub_task has resources and sub_task foreign key in another table c This is task table and subtask foregin key class Task(models.Model): title = models.CharField(max_length=150) task = models.ForeignKey("self", on_delete=models.CASCADE, related_name="subtasks", blank=True, null=True) this is resource table class Resource(models.Model): qty = models.FloatField(default=0.0) rate = models.FloatField(default=0.0) task = models.ForeignKey("Task", on_delete=models.SET_NULL, related_name="resources", null=True) project = models.ForeignKey("Project", on_delete=models.CASCADE, related_name="resource") Another table Complete class Complete(models.Model): task = models.ForeignKey( "Task", on_delete=models.CASCADE, related_name="d", blank=True) percentage = models.FloatField(default=0.0) In complete table contains percentage complete and i need to calculate percentage complete in amount and remaining percentage in amount that will calculate from resources. Each resource amount will calculate (rate * qty) from resource table how to perform this operation in django orm Thanks in advance. Can i provide some data? -
python django how to only show the information about an individual employee when I click on his name
I'm new to python django, trying to create an employee records project, on the django admin site I added some employees and their information, on the django site, I had the hyperlink for the individual employee, but when I click on the individual name, the next page comes all the employees information instead of the particular one, how can I only make it come out the information of the employee I click? Please help, thank you! models.py from django.db import models import datetime class Employee(models.Model): '''An employee's information.''' full_name = models.CharField(max_length=100) address = models.CharField(max_length=100) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zip = models.CharField(max_length=100) hire_date = models.DateField(default=datetime.date.today) def __str__(self): '''Return a string representation of the model.''' return self.full_name return self.address return self.city return self.state return self.zip return self.hire_date views.py from django.shortcuts import render from .models import Employee def index(request): '''The home page for employee_record.''' return render(request, 'employee_records/base.html') def employees(request): '''Shows all employees''' employees = Employee.objects.order_by('full_name') context = {'employees': employees} return render(request, 'employee_records/employees.html', context) def employee(request, employee_id): '''Show a single employee and all his records.''' employee = Employee.objects.get(id=employee_id) objects = Employee.objects.all context = {'employee': employee, 'objects': objects} return render(request, 'employee_records/employee.html', context) urls.py '''Defines URL patterns for employee_records.''' from django.urls import path from … -
Django - ImproperlyConfigured
I keep getting the ImproperlyConfigured exception and cannot find any clues from the log. All I could find out from the log was the following lines: Traceback (most recent call last): File "/Users/marshall/PycharmProjects/chitchat-config/manage.py", line 25, in <module> django.setup() File "/Users/marshall/Library/Python/3.7/lib/python/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/marshall/Library/Python/3.7/lib/python/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/marshall/Library/Python/3.7/lib/python/site-packages/django/conf/__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Here's the settings structure manage.py app |---base.py |---logging.py |---dev_mac.py base.py from decouple import config import os import logging logger = logging.getLogger(__name__) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app.models.Config', "common", "android", 'users', "session", "friends", "tokens", "push" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'app/db.sqlite3'), }, 'config': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'config', 'USER': 'root', 'PASSWORD': "", 'HOST': 'localhost', 'PORT': 3306, 'OPTIONS': { 'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"' } } … -
What's the best way to integrate python with html
I've been working on a python script for a while that deals with calculating the nutrition values of a recipe. This project, as of now, only runs in my command line and I'm looking to integrate it into a website. I've done some research and discovered frameworks and libraries such as Django and some PHP based integrations but I'm quite new to this and have no idea what I'm looking for. In other words, what is the best or most applicable method of integrating my script with the world wide web? Thanks, Lorenzo B p.s. I do have some outside databases that are required for the file to run so does that rule out client-side based methods? -
Select a model instance from HTML form on Django
I am trying to get my html form to allow me to pass the company model instance. As of now, i can pull the names of each company instance, however, what would I put into the value attibute of the option field to have it select the instance correctly? <option value="what to put here?">{{Company.name}}</option> I was hoping to do this through html forms and not Django forms as I have used AJAX to make a nice little live-updating interface. Thanks in advanced! models.py class Company(models.Model): name = models.CharField(max_length=30, null=True, blank=True) email = models.CharField(max_length=40, null=True, blank=True) phone = models.CharField(max_length=15, null=True, blank=True) address = models.CharField(max_length=100, null=True, blank=True) notes = models.CharField(max_length=400, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, blank=True) updated = models.DateTimeField(auto_now=True, blank=True) class Meta: ordering = ["name"] def __str__(self): return self.name class Contact(models.Model): firstname = models.CharField(max_length=20, null=True, blank=True) lastname = models.CharField(max_length=20, null=True, blank=True) email = models.CharField(max_length=40, null=True, blank=True) phone = models.CharField(max_length=15, null=True, blank=True) title = models.CharField(max_length=20, null=True, blank=True) notes = models.CharField(max_length=400, null=True, blank=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ["lastname"] def __str__(self): return self.firstname views.py class contact_manager(ListView): template_name = 'crm/contact_manager.html' context_object_name = 'contact_manager' queryset = Contact.objects.all() def get_context_data(self, **kwargs): context = super(contact_manager, self).get_context_data(**kwargs) context['contact'] … -
django sort query by complex custom function
I'm porting an app from javascript into django. I have need for a rather complex sorting. I wrote a function that uses sorted and cmp_to_key to sort the queryset by a custom function. This works everywhere but the admin, prolly because it gets converted to a list and the admin expects a queryset, whereas everywhere else, I can write things to expect a list. I've searched for ways to get the admin table for this model sorted by this function and just can't figure it out. So now I'm asking for help from y'all. :) I want to have the changelist table in the admin section for this model show the output of this sort_qs function below. I know how to get the admin table to be filtered, but not the sorted part. Is this even possible? If not, is there some hacky workaround? This is not a production app and is just for my own use. For reference, here is my custom sort function: def sort_qs(self): def compare(item1, item2): null_due = date.today() + timedelta(days=14) item1_due = item1.due_date if item1.due_date else null_due item2_due = item2.due_date if item2.due_date else null_due if item1.due_date != item2.due_date: return (item2_due - item1_due).days if item1.priority() != … -
Best way to keep track of the sum of the field of multiple foreign keys [Django]
If you can think of a better way to phrase my question, by all means, please change it. Here's the situation I'm facing. I have 2 models: Agent, Deal. Here's the simplified version of what they look like: class Agent(models.Model): name = models.CharField(max_length=100) price_sum_of_all_deals = models.IntegerField() class Deal(models.Model): agent = models.ForeignKey(Agent, on_delete=models.CASCADE) address = models.CharField(max_length=100) price = models.IntegerField() I'm using celery beat to check an API to see if there are any new deals for each agent. With my current configuration, I am searching for a new deal from within a task method and if I find a deal, I add the price of that deal to the price_sum_of_all_deals field of the corresponding agent. The summary of the task looks likes this: from celery import shared_task from agents import models @shared_task def get_deals(): agents = models.Agent.objects.all() for agent in agents: price, address = get_new_deal_from_api(agent.name) new_deal = models.Deal(agent=agent, address=address, price=price) new_deal.save() agent.price_sum_of_all_deals += price agent.save() This, however, is not very intuitive and feels like an unnecessary abstraction. Is there a better way of calculating the price_sum_of_all_deals from within the model? What is the best practice here? I'm relatively new to Django so if there's something glaring that I overlooked, I apologize. -
Django error: didn't return an HttpResponse object. It returned None instead
I have the following form: class PrestataireProfilForm(forms.ModelForm): class Meta: model = Prestataire fields = ["user", "name", "address", "phone", "fax", "city"] def __init__(self, *args, **kwargs): super(PrestataireProfilForm, self).__init__(*args, **kwargs) self.fields['city'].widget.attrs.update({'class' : 'custom-select'}) self.fields['city'].label = "" And this is my view: @login_required def prestataire_profil(request): prestataire = Prestataire.objects.filter(user=request.user).first() is_prestataire = request.user.groups.filter(name='Prestataire').exists() form = PrestataireProfilForm(request.POST or None, instance=prestataire) if request.method == 'POST': context = { 'profil': prestataire, 'is_prestataire': is_prestataire, 'form': form } if form.is_valid(): prestataire = form.save(commit=False) prestataire.save() context = { 'profil': prestataire, 'is_prestataire': is_prestataire } # return render(request, 'dashboard/prestataires/profil.html', context) return redirect('prestataire_profil') else: context = { 'profil': prestataire, 'is_prestataire': is_prestataire, 'form': form } return render(request, 'dashboard/prestataires/profil.html', context) And this is my html form: <form method='POST'> {% csrf_token %} <div class="form-group row"> <label for="name" class="col-4 col-form-label">Nom d'utilisateur</label> <div class="col-8"> <input value="{{ profil.user.username }}" id="name" name="name" placeholder="Nom d'utilisateur" class="form-control here" required="required" type="text" disabled> </div> </div> <div class="form-group row"> <label for="name" class="col-4 col-form-label">Nom*</label> <div class="col-8"> <input value="{{ profil.user.last_name }}" id="name" name="name" placeholder="Nom" class="form-control here" required="required" type="text"> </div> </div> <div class="form-group row"> <label for="name" class="col-4 col-form-label">Prénom*</label> <div class="col-8"> <input value="{{ profil.user.first_name }}" id="name" name="name" placeholder="Prénom" class="form-control here" required="required" type="text"> </div> </div> <div class="form-group row"> <label for="name" class="col-4 col-form-label">Raison sociale*</label> <div class="col-8"> <input value="{{ profil.name }}" id="name" name="name" placeholder="Raison … -
What are the steps to apply Less in Django?
I plan to use less in django. I am after the minimal complete steps to achieve this. What I did is Installing less sudo npm install -g less Installing django-static-precompiler sudo pip3 install django-static-precompiler Adding static_precompiler to INSTALLED_APPS as follows INSTALLED_APPS = [ 'static_precompiler', .... and in my template.html: {% load less %} ... <link rel="stylesheet" href="{{ MEDIA_URL }}{% less "css/styles.less" %}" /> Then in my server application I received an error ImportError: No module named 'static_precompiler' I searched and people say you should migrate. So, I did sudo apt install python3-migrate which migrate /usr/bin/migrate Then when I migrate migrate static_precompiler I receive this error: Usage: migrate COMMAND ... Available commands: compare_model_to_db - compare MetaData against the current database state create - create an empty repository at the specified path create_model - dump the current database as a Python model to stdout db_version - show the current version of the repository under version control downgrade - downgrade a database to an earlier version drop_version_control - removes version control from a database help - displays help on a given command make_update_script_for_model - create a script changing the old MetaData to the new (current) MetaData manage - creates a Python script that … -
Django Djoser: Failed to parse when activating user
I've been trying to get the user activation url to work. Previously I would get a url not found error but I saw an answer here and implemented the activation view but in doing so I got failed to parse error. Any idea how to resolve this? Or other alternatives to handling the activation url? I also wanted to include some additional functionality upon activation such as configuring their profile. Settings: DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': 'api/v1/auth/users/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'api/v1/auth/users/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'api/v1/auth/users/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS': {}, 'LOGIN_FIELD': 'username', 'USER_CREATE_PASSWORD_RETYPE': True, 'SET_USERNAME_RETYPE': True, 'USERNAME_RESET_CONFIRM_RETYPE': True, 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': [], 'HIDE_USERS': True, 'EMAIL': { 'activation': 'api.email.ActivationEmail', 'confirmation': 'api.email.ConfirmationEmail', 'password_reset': 'api.email.PasswordResetEmail', 'password_changed_confirmation': 'api.email.PasswordChangedConfirmationEmail', 'username_changed_confirmation': 'api.email.UsernameChangedConfirmationEmail', 'username_reset': 'api.email.UsernameResetEmail', } } Url: urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), url(r'^auth/users/activate/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', UserActivationView.as_view()), path('auth/', include('djoser.urls.authtoken')) ] View: class UserActivationView(APIView): def get (self, request, uid, token): protocol = 'https://' if request.is_secure() else 'http://' web_url = protocol + request.get_host() post_url = web_url + "api/v1/auth/users/activate/" post_data = {'uid': uid, 'token': token} result = requests.post(post_url, data = post_data) content = result.text return Response(content) Error: InvalidURL at /api/v1/auth/users/activate/ODE/5cm-541c69a1b7e83d4f5c55/ Failed to parse: http://localhost:8000api/v1/auth/users/activate/ Request Method: GET Request URL: http://localhost:8000/api/v1/auth/users/activate/ODE/5cm-541c69a1b7e83d4f5c55/ Django Version: 2.2.6 Exception Type: InvalidURL Exception Value: Failed to parse: http://localhost:8000api/v1/auth/users/activate/ Exception Location: C:\Users\fendy\.virtualenvs\collegeapp\lib\site-packages\requests\models.py in … -
Django - Static files not working correctly
In my project, I have a signup page. In the signup page, I have a link to a css file within my static folder. However the css is not being applied to the document. Here is my code - settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static'), STATIC_URL = '/static/' urls.py: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Inside one of my app folders, I have a folder named 'static'. I then refer to the files within this static folder in my document: {% load static %} <link rel="stylesheet" href="{% static 'signup.css' %}"> <h1 class="myh1">YO!</h1> I have not run the collectstatic command as I am in development mode. Does anybody know why the css changes are not being applied to the html page? Thank you. -
Give boolean field a css class
Unlike Charfield() or others where we can implement first_name = forms.CharField(widget=forms.TextArea(attrs={'class'='something'})), how can we or is it possible to give a CSS class to a BooleanField. Tried looking into documentations and tutorials but couldn't find anything. -
Server Error (500) saving products on django
I fixed a problem from before with saving products on Django by setting DEBUG = False and adjusting the ALLOWED_HOST in settings. But now what happens is when i try to save it doesn't come up with any solutions and instead just says "Server Error (500) and i have retried many times, any ideas why? -
Connect django website/database with desktop application
So I am creating a sign up page in django that will also have a sqLite database which won't be accessible from the webpages to the users. As I want it to be only accessible with the desktop application. After reading up I came across an article that said that Tkinter and django don't mix together. What can I use instead of tkinter for the application? And what else am I missing in this picture? database? (check) desktop application (????) server side will only provide the info for the client side and 'reward users' client side will do the tasks and handshake with the server on completion for 'reward' -
Django 3 'NoReverseMatch at /post/1/
My blog has the capacity to make posts. I wanted to have a feature where i can update/edit the blog and when i try to implement the feature i run into the following error; NoReverseMatch at /post/1/ Reverse for 'post_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/edit/$'] I know what line is causing the problem: /post_detail.html <a href="{% url 'post_edit' post.pk %}"> +Edit Blog Post</a> without the line on top, i get no errors. I am just a begginer learning Django and i cannot make any sense of why this is not working. It is suggested in the tutorial i am following. /urls.py urlpatterns = [ path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), # new path('post/new/', BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), path('', BlogListView.as_view(), name='home'), ] /post_detail.html {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2> {{ my_posts.title }} </h2> <p> {{ my_posts.body }} </p> </div> <a href="{% url 'post_edit' post.pk %}"> +Edit Blog Post</a> {% endblock content %} views.py class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DeleteView): model = Post context_object_name = 'my_posts' template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = '__all__' class BlogUpdateView(UpdateView): model = Post template_name = 'post_edit.html' fields = ['title', … -
I dont have dist folder in my django-project
Hello I dont have dist folder in my django project, I removed the dist/ from .gitignore. Then ran git inint but still no dist folder -
Performance when using Pandas in Django
I am working on a web application that desperately needs to depend on pandas. I was not able to find details on how Django scales when it imports big libraries. So I would like to ask: Can I safely use full Pandas library in Django? Will it backfire in case of scaling? Is there any point in only importing what is really necessary, i.e.: from pandas import DataFrame vs import pandas as pd? Will Django load pandas in memory for each request that arrives at the server? -
Django: Somar todas as entradas e saídas financeiras do sistema
Eu tenho um sistema de gestão em django e gostaria de salvar em um lugar o relatório de todas as ganhos(Pago=True), inadimplências (pago=False) e despesas do mês ou período no próprio django admin, em um template ou em um documento PDF. class MovDiario(models.Model): cliente = models.ForeignKey('Cliente', on_delete=models.CASCADE) veiculo = models.ForeignKey('Veiculo', on_delete=models.CASCADE) placa = models.CharField(max_length=10) servico = models.ManyToManyField('Servico') valor = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) pagamento = models.ForeignKey('FormPagamento', on_delete=models.CASCADE, blank=True, null=True) pago = models.BooleanField(default=False) entregue = models.BooleanField(default=False) -
Django get_queryset filter objects on pk
So I have these models client and progress. I've mixed the Create and ListView but I only want to show progress data for the current client. I accomplished this with a hardcoded PK but when I try to make it dynamically I only get errors like Field 'id' expected a number but got <property object at 0x10ee5f890>. models.py class Client(models.Model): name = models.CharField(max_length=255) ... class Progress(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) ... views.py class ProgressClient(generic.CreateView): template_name = 'pages/clients/progress/index.html' model = Progress form_class = ProgressForm success_url = reverse_lazy('index') def get_context_data(self, **kwargs): kwargs['object_list'] = Progress.objects.filter(client__id=1) return super(ProgressClient, self).get_context_data(**kwargs) I've tried things like def get_context_data(self, **kwargs): kwargs['object_list'] = Progress.objects.filter(client__id=Client.pk) return super(ProgressClient, self).get_context_data(**kwargs) def get_context_data(self, **kwargs): client_pk = self.kwargs.get('client_id') kwargs['object_list'] = Progress.objects.filter(client__id=client_pk) return super(ProgressClient, self).get_context_data(**kwargs) -
Django Deprecation: Signals
Will signals be deprecated? I'm starting a new application and I initially planned to implement some signal based functions but a colleague told me that signals are about to be deprecated and that I should refrain from using them. Is that true? I haven't been able to find any sources that support his claim. -
Use currently uploaded file for rest of the GET/POST requests in Django
I have web page which first asks user(not required to logged in) to upload a file to Djnago server and then user can click on multiple tabs/links available on web page to get more information from DB file present in Django's media folder. All tabs/links of web page send REST GET/POST requests. Since REST are stateless. I need file name in every requests to serve them, keeping mind multiple users can upload different files. is there way to handle this scenario ? def upload(request): context = {} print('Entered in upload', request) if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) if name: print('settings.MEDIA_ROOT', settings.MEDIA_ROOT) db_file = os.path.join(settings.MEDIA_ROOT, name) context['db_file'] = db_file // redirecting to next page with some content response = main_output(request, file_path=db_file) context['op'] = response.get('op') context['table_name'] = response.get('table_name') context['headers'] = response.get('headers') return render(request, 'blog/main_output.html', context) So here user uploaded a file and i am re directing him to main_outout.html. up until this point i have db_file filename and so db content. but user has more options on UI. when he would like to get more data from same file and those options uses more GET/POST requests. for example: User wants to … -
Django: how to get username in template using django-tweaks
I have rendered a html form with widget_tweaks and i want the default value of the field to be the current username. #template {% if user.is_authenticated %} {% render_field form.title value="{{ request.user }}" readonly="True" %} </form> {% else %} <h1>Login First</h1> {% endif %} but this render the exact text "{{ request.user }}" rather than printing the username. If I use the tag and use the {{ request.user }}, prints the current username. This is how my views.py looks: #views.py class CreatePostView(CreateView): template_name = 'posts/new_post.html' redirect_field_name = 'posts/post_detail.html' form_class = PostForm model = Post def get_absolute_url(self): return reverse('posts:post_detail', args = [self.id]) -
why the templates still not changing when something change in data in django?
My Django project has the Credits System inside of it. I want the templates change if the user has not enough credits. models.py class CreditSystem(models.Model): forUser = models.ForeignKey(User, on_delte=models.CASCADE, null=True, blank=False) credits = mdoels.IntegerField(null=True, blank=False) views.py def userPanel(request): credits = CreditSystem.objects.get(forUser=request.user) return render(request, 'user/panel.html', {'credit': credit.credit} user/panel.html {% if credit < 5 %} <p>You have insufficient Credits</p> {% else %} <p> Welcome! </p> {% endif %} Now for example, I change the user credits at 10 (at the admin panel). Then it shows the "Welcome!" message at the html. Now if I change the current user credits at 5. How the templates change the message to "you have insufficient credit" message? Do I need a Asynchronous Django Project (django-channels)? -
Updating django model form values upon a change in a separate form value
I (first-time programmer) am attempting to create a site with django where one feature is that the admin can add locations and relevant information (like coordinates) to a feed. The goal of this is to allow the admin to enter in the latitude and longitude of a location into the admin site manually. However, if this isn't done, the program should attempt to generate these values via the use of a geocoder and the address field. This works fine, so far. But what I'm trying now is to automatically update those values whenever the address changes. The boolean refreshCoords should be set to true when the address model is changed. However, I get this error upon submitting the admin form: AttributeError at /admin/network/nonprofit/add/ type object 'Nonprofit' has no attribute 'changed_data I'm not sure what to do now. I'm using the changed_data method from the docs here: https://docs.djangoproject.com/en/3.0/ref/forms/api/#django.forms.Form.changed_data. How can I update the data like this? Is there another way, or am I using the wrong method? Below is the relevant code in python models.py: class Nonprofit(models.Model): network = models.ForeignKey(Network, on_delete=models.CASCADE) #Each nonprofit belongs to one network address = models.CharField(max_length=100, help_text="Enter the nonprofit address, if applicable", null=True, blank=True) lat = models.DecimalField(max_digits=9, …