Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: iterate over 2 sets using for in template
I want to iterate over 2 sets of data and display values in my template. I have something like that: {% for email,phone in user.email_set.all, user.phone_set.all %} {{email}} {{phone}} {% endfor %} Unfortunately I get TemplateSyntaxError: 'for' statements should use the format 'for x in y' Is there a way I can do it? -
Tinymce not rendering in form
Attempting to use tinyMCE to allow rich input in blog content. I am constrained in that I am inside of Messanine using django 1.11.20. There seems to be many versions of tinyMCE so it is hard to google the right solution. I used the documentation from Fosstack to install django-tinymce4-lite. Then integrated it into an existing update blog form. The form did not show the change, it still is rendering as a standard CharField. (TextField not supported in this version of django) class TinyMCEWidget(TinyMCE): ` def use_required_attribute(self, *args): return False class UpdateForm(forms.ModelForm): content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ) class Meta: model = BlogPost fields = ['content'] def UpdateContent(request, slug): blog_post = BlogPost.objects.get(id=slug) if request.method == 'POST': form = UpdateForm(request.POST) if form.is_valid(): blog_post.content = form.cleaned_data['content'] blog_post.save() return HttpResponseRedirect('/write/') else: form = UpdateForm(instance=blog_post) return render(request, 'blog_my_update.html', {'form' : form}) in blog_my_update.html <h1>Update Story</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} ` Update the Story I expected to see the tinyMCE render the form. But got a normal text box. Anyone know how to fix this? Thanks in advance. -
Delete button in a template is inactive
I have a group_edit.html which permit to update info of a group and delete it. Upade(save) works great but button for delete is doing nothing. Thanks for help: My group_edit.html: {% block page %} <form method="POST"> {% csrf_token %} <div class="col-lg-4 col-md-4 col-sm-4 content"> {% bootstrap_form form %} <button type="submit" class="btn btn-pink pull-right">Save</button> <button type="reset" class="btn btn-warning pull-left"><a href="{% url 'confirm-delete' group_id %}"></a>Delete</button> </div> <a href="{% url 'group-list' %}">Back to list</a> </form> {% endblock %} My confirm_delete.html template: {% block title %}Delete{% endblock %} {% block heading %}<h3 class="page-header-center">Object Delete</h3> {% endblock %} {% block page %} <form method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ obj }}"?</p> <input type="submit" value="Confirm" class="btn btn-warning"> <a href="group_list.html" class="btn btn-default">Cancel</a> </form> {% endblock %} my views.py: def group_edit(request, group_id): form = GroupForm(instance=Group.objects.get(group_id=group_id)) if request.method == "POST": form = GroupForm(request.POST, instance=Group.objects.get(group_id=group_id)) if form.is_valid(): form.save() messages.success(request, 'Group saved') # message for inform user of success - See messages in html file return redirect(group_list) return render(request, 'imports/group_edit.html', { "group_id": group_id, "form": form, }) def confirm_delete(request, group_id): obj = GroupForm(instance=Group.objects.get(group_id=group_id)) if request.method == "POST": obj.delete() messages.success(request, 'Deleted') # message for inform user of success - See messages in html file return render(request, 'imports/group_list.html') context … -
URL Getting changing to http://127.0.0.1:xxxx/?next=/page2 it has to be http://127.0.0.1:xxxx/page2 to get the views in page2
I have an application that runs with Django and React when ever my login was successful I need to redirect to the next page ,but for some reason the url is redirecting to http://127.0.0.1:xxxx/?next=/mfa, where it has to be actually http://127.0.0.1:xxxx/mfa.Not sure how the url is getting configured and /?next= is getting added if request.method == 'POST': form = AuthenticationForm(request.POST) with transaction.atomic(): if form.is_valid(): user = form.get_user() auth.login(request, user) logging.user_login(user, log_description.SUCCESS) if not user_is_reviewer(user): form.add_error(None, 'Unauthenticated User') logging.user_login(form.get_user(), log_description.FAILURE) return render(request, 'pages/login.html', { 'form': form }) MFAToken.objects.filter(user_id=user.id, killed__isnull=True).update(killer=request.user, killed=datetime.utcnow()) return redirect('/mfa') logging.user_login(form.get_user(), log_description.FAILURE) else: form = AuthenticationForm() mfa/urls.py urlpatterns = [ url(r'api/mfa', token, name='token'), url(r'^mfa$', mfa, name='mfa') ] settings.py LOGIN_URL = '/' PROJECT_DIR = os.path.dirname(__file__) MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(PROJECT_DIR, 'staticfiles'),) UPLOADED_FILE_FOLDER = '' Not sure why I am getting "?next=/" getting added to url when we redirect to mfa page . thanks in advance. -
django.db.migrations.exceptions.InconsistentMigrationHistory on fresh database
Folder structure: -project/ -project/ -manage.py -settings.py -urls.py -wsgi.py -apps/ -user/ -migrations/ -migration files here -models.py User model: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils import timezone class User(AbstractUser): timestamp = models.DateTimeField(default=timezone.now, db_index=True) class Meta: swappable = 'AUTH_USER_MODEL' settings.py: INSTALLED_APPS = [ # user 'apps.user.apps.UserConfig', # built-in 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # third party 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account', 'rest_auth.registration', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] AUTH_USER_MODEL = 'user.User' What I've tried (every new code block is run on a fresh database and without any migration files for the app user): python manage.py makemigrations user python manage.py migrate python manage.py makemigrations user python manage.py migrate user python manage.py migrate python manage.py makemigrations user python manage.py migrate user And all of them results in the following exception: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration authtoken.0001_initial is applied before its dependency user.0001_initial on da tabase 'default'. -
Emails fail to deliver from docker container
Basically I have a celery periodic task meant to send emails via the SendGrid WebAPI every minute for testing purposes. I am using this package, django-sendgrid-v5 (https://github.com/sklarsa/django-sendgrid-v5), and all is successful outside of docker. With the following docker-compose.yml set up however the emails fail to send (although the celery tasks are themselves successful). Because I am new to Docker I thought I'd create an additional periodic task which make a HTTP request just to be sure I am able to do so in a docker container and sure enough the google homepage is getting fetched and I see the printed body in my terminal. From what I understand the said django package utilises the SendGrid web API so it is itself a HTTP request instructing the server's at SendGrid to send the email. So I'm at a loss as to why this isn't working. docker-compose.yml version: '3.7' services: # postgresql db for django app and celery backend db: image: postgres:10.1-alpine volumes: - docker-django-celery-rabbitmq-example:/var/lib/postgresql/data/ networks: - celery-rabbitmq # django web app - celery master web: build: . command: sh ./run_web.sh volumes: - .:/app ports: - 8000:8000 depends_on: - db networks: - celery-rabbitmq # Celery beat - periodically creates tasks celery-beat: build: … -
Django annotation has side effect on another annotation
I'm running into an issue where adding an annotation to a QuerySet changes the results of previous annotations. Here is the (simplified) setup: class Player(models.Model): name = models.CharField() class Unit(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='unit_set') rarity = models.IntegerField() class Gear(models.Model): pass class UnitGear(models.Model): unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name='ug_set') gear = models.ForeignKey(Gear, on_delete=models.PROTECT) Annotating players with the count of rarity 7 units works well: Player.objects.annotate( rarity7_count=Count(unit_set__rarity=7) ).values_list('name', 'rarity7_count') [('Player1', 170), ('Player2', 172), ('Player3', 164), ..., )] The values returned for rarity7_count above are correct. If I add the following additional annotation, this is no longer the case: Player.objects.annotate( rarity7_count=Count(unit_set__rarity=7), gear_count=Count(unit_set__ug_set) ).values_list('name', 'rarity7_count', 'gear_count') [('Player1', 476, 456), ('Player2', 490, 466), ('Player3', 422, 433), ..., )] Notice how rarity7_count values have changed -- these values are no longer correct! Values for gear_count are, however, correct. Why is that? How can get both annotation to work without interfering with each other? I have tried all sorts of things and am currently at loss on how to do this. -
How to link a row from django_table page to detailed page of that row?
I am new to Django and this might seem too basic, but still, I have you downvote too much I am trying to link a django_table to a detailed page which displays that row with some extra data. I have tried all the tutorial I could find to link the table columns with id there aren't many details in the documentation how to do it as well Here in CustomerListView, everything is working fine I can display my filter blocks and the table, but I can't figure out how to link the results to details views.py from django.views.generic import ListView from django.core.exceptions import ObjectDoesNotExist from django.db.models.query_utils import Q from django_tables2 import RequestConfig from braces.views import LoginRequiredMixin, GroupRequiredMixin from .tables import CustomerTable from .utils import PagedFilteredTableView from cameras.models import Camera, ErrorLog from .forms import CustomerListFormHelper from .filters import CustomerListFilter class CustomerListView(LoginRequiredMixin, GroupRequiredMixin, PagedFilteredTableView): model = Camera template_name = 'customers.html' context_object_name = 'camera' ordering = ['-id'] group_required = u'company-user' table_class = CustomerTable filter_class = CustomerListFilter formhelper_class = CustomerListFormHelper def get_queryset(self): qs = super(CustomerListView, self).get_queryset() return qs def post(self, request, *args, **kwargs): return PagedFilteredTableView.as_view()(request) def get_context_data(self, **kwargs): context = super(CustomerListView, self).get_context_data(**kwargs) context['nav_customer'] = True search_query = self.get_queryset() table = CustomerTable(search_query) RequestConfig(self.request, paginate={'per_page': 20}).configure(table) … -
Django ORM - queryset order by filtered foreign key relationship
I am attempting to use the Django ORM to order a queryset based on the result of what I would normally define as a subquery in postgres. My database schema is such that there is a table of items, and a user can "favorite" an item. This list of user-specific data is stored in a second database table with foreign keys to the user and the item: database design I want to return the user a list of all items, but order by whether they have "favorited" the item or not. In a postgres query this would look as follows using a where statement in the subquery: ideal postgres query Is this possible to accomplish with the Django ORM without dropping into SQL? I have attempted to look at various answers here and elsewhere as well are the ORM documentation. I assume this is possible with some combination of the below: Annotations F expressions Subquery (with OuterRef) select_related Example model code: class User(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=256) class DashboardItem(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=256) class DashboardItemUserData(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User) dashboard_item = models.ForeignKey(DashboardItem) is_favorite = BooleanField() Query I would think would work (or similar): current_user … -
Custom User Model with Multiple User Types vs Django Groups to Handle Logic and Permissions?
Abstract Question: If you had multiple users categories with different business logic and permissions, would you use a custom / extended user model with different user types or would you stick with a basic user model and handle differences by means of Django’s groups and group permissions? What are pro’s and con’s? When would you use what way? A practical example: Assuming there is a web application with three different user categories, e.g: Applicants Recruiters Investors with users in each category also separated into different subgroups with respective permissions - let’s say: membership requested regular member and prime member How would you go about managing those (overall 9) different user groups and what way would you prefer? Implementing multiple user types in a custom user model (AbstractUser) Sticking with a simple / standard user model and handling different permissions merely by using Django’s build in groups with respective group permissions. A combination of both 1 and 2. (split how?) External package handling permissions (which one?) -
How do I output from views.py to html template
This is the code class Predict(views.APIView): def post(self, request): employeeId = 44 return render(request, 'InventoryShop/home.html', {'employeeId': employeeId}) What I want to achieve is to output this employeeId on the home.html, from this scope. When I put this employeeId outside the scope, I am able to output it without problem though: def home(request): context = { 'employeeId' : employeeId } return render(request, 'InventoryShop/home.html', context) The first block of code gives an error when trying to run "context must be a dict rather than set." -
CreateView return "Experience.id_auth_user" must be a "AuthUser" instance
I'm creating a CRUD on Django, i have the table of users and the table of experiences, each user can have multiple experiences, so i want to assign the user-id to the new experience. When i try to do that i get an error "Experience.id_auth_user" must be a "AuthUser" instance." Models.py class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(unique=True, max_length=254) is_staff = models.BooleanField() is_active = models.BooleanField() date_joined = models.DateTimeField() perfil_photo = models.CharField(max_length=150, blank=True, null=True) cel_number = models.CharField(max_length=150, blank=True, null=True) date_of_birth = models.DateTimeField(blank=True, null=True) location = models.CharField(max_length=150, blank=True, null=True) gender = models.CharField(max_length=150, blank=True, null=True) class Meta: managed = False db_table = 'auth_user' class Experience(models.Model): experience_name = models.CharField(max_length=255, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) minimum_age = models.IntegerField(blank=True, null=True) duration = models.IntegerField(blank=True, null=True) price = models.FloatField(blank=True, null=True) id_auth_user = models.ForeignKey(AuthUser, models.DO_NOTHING, db_column='id_auth_user', blank=True, null=True) class Meta: managed = False db_table = 'experience' views.py class ExperienceCreate(CreateView): model = Experience fields = ['experience_name','description','duration','price'] def form_valid(self, form): # form.instance.id_auth_user = Experience.objects(id_auth_user=self.request.user.id) #instance_experience = Experience.object.id(id_auth_user=self.request.user.id) #form.instance.id_auth_user = self.request.user self.object = form.save(commit=False) self.object.id_auth_user = self.request.user.id self.object.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('experience') any suggest? -
Check blank before create
For some reason, the POST method is allowing me to create Telefono_paciente even if I do not have all the required fields. # Create a new telefono_paciente def post(self, request): serializer = Telefono_pacienteSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Telefono_paciente(models.Model): tipo = models.CharField(max_length=3,null=True, blank=False, choices=PHONE_CHOICES) Paciente = models.ForeignKey(Paciente, null=True, blank=False, on_delete=models.CASCADE) def __str__(self): return '%s %s %s' % (self.tipo, self.lada, self.telefono) class Meta: verbose_name_plural = "Pacientes - Telefonos" -
Math in Django Templates
I have rows of cards (three per row) dynamically generated. The number is arbitrary, so per row there will be somethings only one or two cards. I want to fill up the last row with cards depending on what is already automatically produced. Is this really the simplest way to achieve? {% load mathfilters %} {% with dataset|length|add:1|mod:3 as occupied %} {% with 3|sub:occupied as free %} {% with ''|center:free as range %} {% for i in range %} <div class="my-card"> <div class="card text-center"> <div class="card-body"> <button type="button" class="btn btn-primary"><i class="fas fa-plus-circle fa-10x"></i</button> </div> </div> </div> {% endfor %} {% endwith %} {% endwith %} {% endwith %} It works, but it is quite a long way to go for such a simple task. Any better ideas? -
end point to accept multiple values, including query strings
I have a view which should accept an end point with a query parameter, as well as without a parameter. http://localhost:8001/v1/subjects?owner_ids=62,144 and http://localhost:8001/v1/subjects Here's my view file... class SubjectPagination(JsonApiPageNumberPagination): """ Required for frontend to retrieve full list. """ max_page_size = 5000 class SubjectViewSet(Subject.get_viewset()): pagination_class = SubjectPagination def get_queryset(self): import pdb; pdb.set_trace() queryset = Subject.objects.all() if self.request.GET['owner_ids']: owner_id_list = self.request.GET['owner_ids'].split(',') owner_id_list_integer = [] for i in owner_id_list: owner_id_list_integer.append(int(i)) return queryset.filter(organization__in=owner_id_list_integer) else: return queryset SubjectUserRoleViewSet = Subject.get_by_user_role_viewset( SubjectViewSet, GroupRoleMap, Role) I am trying to figure out how to handle both the end points? Please advice what needs to be done at the view to handle a URI with or without query strings? Here's the urls.py router.register(r'subjects', views.SubjectViewSet) -
Getting django.core.exceptions.ImproperlyConfigured: 'django.db.backends.mysql' isn't an available database backend' on making migrations
I want to chnge my existing project from sqlite to mysql in django but it does not allow. I have already installed mysqlclient and mysql-connector-python. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'TestPro', 'USER' : 'urvi', 'PASSWORD' : 'test', 'HOST' : '', 'PORT' : '', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4', } } } -
How to use ember-apollo-client?
I am trying to use graphql through apollo-client. On frontend there is Ember, on backend we have django and graphql server, implemented on this tutorial (https://www.howtographql.com/graphql-python/0-introduction/). The Ember application is on 4200 port, the graphql server is proxied on 8000/graphql (ember s --proxy http://localhost:8000) I tried to follow this guide (https://www.howtographql.com/ember-apollo/1-getting-started/), but without graphcool, because we have backend. In a controller signup.js I have import Controller from '@ember/controller'; import { inject as service } from '@ember/service'; import Mutation from '../gql/mutation'; I have injected apollo this way export default Controller.extend({ apollo: Ember.inject.service(), And the mutation is this actions: { signUp() { let username = this.get('username'); let password = this.get('password'); let email = this.get('email'); const credentials = { username, password, email }; let mutation = Mutation.CREATE_USER; return this.get('apollo').mutate({mutation, credentials}, 'createUser').then(() => { this.set('username', ''); this.set('email', ''); this.set('password', ''); console.log('user created successfully!'); }).catch(error => console.log('ERROR!!!!111:', error)); After clicking submit button in a form, I got this message POST http://localhost:4200/graphql 500 (Internal Server Error) ServerParseError: Unexpected token < in JSON at position 0 What can I do? -
Javascript generated Materialize cards display problem
I have some rendered card to be displayed on a website. All displayed properly, except the first one. The image for the first card will roll as you scroll the page, and it only takes half of the image space. The rest cards have no problem at all. <div class="parallax"> {% if object_list.count == 0 %} Nothing found {% else %} <!-- Icon Section --> <div class="row"> {% for member in object_list %} <div class="col s12 m6 l3"> {% if member.get_image_url %} <div class="card medium"> <div class="card-image"> <img src="{{ member.get_image_url }}"/> </div> <div class="card-content"> <span class="card-title activator"> {{ member.title }} <i class="material-icons right">more_vert</i> </span> </div> <div class="card-reveal"> <span class="card-title grey-text text-darken-4"> {{member.title}} <i class="material-icons right">close</i></span> <p>{{ member.summary}} </p> </div> <span class="btn btn-flat"> <a href="{{ member.slug }}/"> find out more </a></span> </div> <!-- #endcard --> {% endif %} </div> <!-- #end col --> {% endfor %} </div> <!-- #end row --> {% endif %} </div> I have changed back to the original CSS for Materialize card, still having the same issue. Not sure what to change that affects the first card only, given that all the cards are sharing the same block of HTML code. And, I'm using Django framework if … -
Django Session Scope issue between different apps within a project
I am following a tutorial about Creating Shopping Cart this here link. I wanted to make some tweaks on my own, I tried to add a cart icon in the navbar capable of displaying no. of items and total of the items in the cart. But this icon shows values correctly only when I am on cart's template page, on rest of the pages it is blank. (To me it seems to be problem with the scope of sessions). Project Structure image - (https://academy.muva.tech/blog/wp-content/uploads/2018/05/cart.png) image of cart icon on cart detail page-(https://imgur.com/xyyqCNp) image of cart icon on other page-(https://imgur.com/jNGoiUK) base.html <div class="shopping-item"> <a href="{% url 'cart:cart_detail'%}">Cart - <span class="cart-amunt">{% with totail_items=cart|length %}Rs {{ cart.get_total_price }}</span> <i class="fa fa-shopping-cart"></i> <span class="product-count">{% if cart|length > 0 %}{{ cart.cart_item_count }}{% else %}0{% endif %}{% endwith %}</span></a> </div> detail.html( cart page ) {% extends 'shop/base.html' %} {% load static %} {% block title %} Your Shopping Cart {% endblock %} {% block body_block %} <div class="container"> <div class="row" style="margin-top: 6%"> <h2>Your Shopping Cart<br><br> <span class="badge pull-right"> {% with totail_items=cart|length %} {% if cart|length > 0 %} My Shopping Order: <a href="{% url "cart:cart_detail" %}" style="color: #ffffff"> {{ cart.cart_item_count }} item {{ totail_items|pluralize }}, Rs. … -
Customize Django rest framework authentication response {"detail": "Authentication credentials were not provided."}
I am using django 2.1 and python 3.6 and django rest framework 3.8.2 ... I am trying to find a way to customize the json response when authentication failed. I am using a third party package Django OAuth Toolkit The only way I could think of is writing a custom authentication class { "detail": "Authentication credentials were not provided." } { "Failure": "Authentication credentials were not provided. xyz etc" } -
TemplateDoesNotExist at certain location
My code was working perfectly fine till yesterday. I had deployed the app on heroku and it went well. I wanted to work on the security of the app, so today I deployed some code changes directly on heroku. When it didn't ran perfectly, I reverted the changes and by mistake I copied the settings.py from my production server to development server. Now the deployed code is running perfectly, though my development server is unable to find the templates! When I realised that I'm using the production settings.py, I made the necessary changes. Debug = True, removed security headers and made sure the middlewares were the default ones. Initially I kept getting the below error while accessing https://localhost:8000 You're accessing the development server over HTTPS, but it only supports HTTP. I then changed my url to simply 127.0.0.1:8000, and then I started getting the below error raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: my_form/index.html [11/Jun/2019 23:25:49] "GET / HTTP/1.1" 500 88781 I've even tried to start the project from scratch, and even cleared my cache from browser. Project Structure: ├───my_server │ ├───my_form │ │ ├───migrations │ │ │ └───__pycache__ │ │ ├───static │ │ │ └───raffle_form │ │ │ ├───images │ │ │ … -
pytest and Django transactional database
I use production database for tests (actually it's test database in docker). The question is: how to make tests run in transactions against this database. I need the same behavior like @pytest.mark.django_db(transaction=True) but with production database. Current setup: conftest.py @pytest.fixture(scope='session') def django_db_setup(): """Avoid creating/setting up the test database""" pass @pytest.fixture def db(request, django_db_setup, django_db_blocker): django_db_blocker.unblock() @pytest.fixture def myfixture(db): ... return SomeObject test_example.py def test_something(db, myfixture): assert ... -
Django saving, deleting and viewing user uploaded media with same name
I have a profile app, where users can upload a profile picture. I save the picture with the user's username eg. ifakih.jpg. If that file already exists, and they want to change their profile picture, I delete the old one and replace it with the new one. I can see the change in my directory. The old ifakih.jpg is replaced with the new one. However, my website still uses the old image. If I go to the admin and check the imagefield for that user, it points to the correct directory and image, but the content is wrong. Models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=64,blank=True) profilePic = models.ImageField(blank=True, null=True, upload_to= path_and_rename) phoneNumber = models.CharField(max_length=12,blank=True) streetAddress = models.CharField(max_length=64,blank=True) @receiver(pre_delete, sender=Profile) def post_delete(sender, instance, **kwargs): """ Deleting the specific image of a Post after delete it """ if instance.profilePic: if os.path.isfile(instance.profilePic.path): os.remove(instance.profilePic.path) @receiver(pre_save, sender=Profile) def post_update(sender, instance, **kwargs): """ Replacing the specific image of a Post after update """ if not instance.pk: return False if sender.objects.get(pk=instance.pk).profilePic: old_image = sender.objects.get(pk=instance.pk).profilePic new_image = instance.profilePic if not old_image == new_image: if os.path.isfile(old_image.path): os.remove(old_image.path) else: return False -
I want to lock an item
It's a boolean field with 2 choices only, but I need to add a key so that one of them is default and if you need to change to second choice then you gotta unlock it. '''UNITS = ( ('kg/cm', 'kilo/centimeter'), ('lb/in', 'pound/inches'), ) unit = forms.ChoiceField(choices=UNITS, required=False) ''' I've tried to add a lock in the same page and import from somewhere else, none of these seems to work. -
Read multiple files from folder and display on webpage in Django
I have a separate Java program that adds text files to a folder almost every minute. The text files look something like this 11-Jun-19_12:01:56.txt 12 35 21 56 77 89 11-Jun-19_12:02:48.txt 23 21 45 72 96 14 What is the best way to read all the text files in this folder automatically (not using drag&drop or input buttons) and display indiviudal line charts on a Webpage with name of text file on top of it (refreshing the page every 10 seconds to make sure charts from new files are seen). Since i am using Django framework, is it advisable to use Python script or Javascript/Jquery to acheive the required outcome?