Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter a field by its belonging to the model defined in the original model in Django?
For example I have such models: class Person(models.Model): ... class Group(models.Model): persons = models.ManyToManyField(Person, through='Membership') ... class Membership(models.Model): group = models.ForeignKey(Group) person = models.ForeignKey(Person) class Team(models.Model): group = models.ForeignKey(Group) ... class TeamPerson(models.Model): team = models.ForeignKey(Team) person = # Question about this # So Membership links the Person with the Group and we have Team that relates to a Group. The thing what I need to do is to use in TeamPerson the persons related through the Team -> Group -> Membership -> Person so Django knows that I can choice only the persons that are in the group choose for the team that was choose in the TeamPerson. Actually what I expected is automatic filtering the persons in the TeamPerson admin page when I choice the team. Is there a (right) way to do that? -
Is there any way to add html file dynamically from django admin?
I am very new to django. I want to include html file from django admin dashboard. Let me explain a little. Let, My model is like below class myModel(models.Model): fileName= models.CharField(max_length=100) my views.py file def calcView(request): template_name = 'index.html' filename = Adsense.objects.first() context = {} context['filename'] = filename return render(request, template_name, context) Now i enter filename in as 'anyfile.html'. It already available in template folder. Now in index.html file how can i it from dashboard. Pseudo code {% include "{{ filename.fileInclude}}" %} Is it possible ?? if yes, how can I do this ? Thanks in advance -
Refactoring part of template into own file breaks django
I have something weird: I got a base.html that acts as a skeleton with blocks for the website. It contains this part: <main class="main"> {% block main %} <div class="content"> {% block content %} content {% endblock %} </div> {% endblock %} </main> I also got a base_with_sidebar.html that looks like this: {% extends "core/base.html" %} {% block main %} {{ block.super }} <div class="sidebar"> {% block sidebar %} {% include "polls/recent_polls.html" %} {% endblock %} </div> {% endblock %} and index.html which fills the content: {% extends "app/base_with_sidebar.html" %} {% block content %} somecontent {% endblock %} This all works so far. The problem arises if I want to refactor base.html: from this: <main class="main"> {% block main %} <div class="content"> {% block content %} content {% endblock %} </div> {% endblock %} </main> to this: base.html <main class="main"> {% block main %} {% include './main.html' %} {% endblock %} </main> main.html <div class="content"> {% block content %} content {% endblock %} </div> This results in my index.html always displaying 'content' - instead of the block content specified in index.html -
Using prefetch_related() in Django in combination with raw_id_fields
I'm trying to eliminate queries by prefetch_related(). In the admin with TabularInline this works in all cases, except the ForeignKeyRawIdWidget created by raw_id_fields = ('article',). This is due to the Queryset.get() it does, and filter actions are not supposed to work when prefetching. So for every row in the inline I'll get a seperate query. This blogpost illustrates a workaround: https://blog.mounirmesselmeni.de/2017/02/06/accessing-prefetched-objects-inside-your-models-methods/ The workaround looks quite messy to me, and won't work in this case since the widget does the get. Is there some proper way to do prefetching here or is this a Django prefetching limitation? Not using raw_id_fields is not an option since the default widget does even more queries. Also, I don't understand why filter actions do not check the prefetching cache before actually querying the database. This small step could potentially save multitudes of queries, right? -
You're accessing the development server over HTTPS, but it only supports HTTP. in django
I am building a django app to bookmark images from other sites. But, when I go to any website and click on the "Bookmark" button, I get this error in my terminal: [19/Jan/2021 21:15:00] code 400, message Bad request version ('÷b%2Eí\x10Ð\x80ðB\x90\x00"\x8a\x8a\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [19/Jan/2021 21:15:00] You're accessing the development server over HTTPS, but it only supports HTTP. I don't get any error in my website though. Is this a problem in my code? -
Is there a way in django to update the same page with the response without totally rendering it?
Is there a way in django to update the same page with the response without totally rendering it. I am trying to create a code editor to test. But when I am returning the results my contents are removed. I understand it is because I am rendering the page . I need the contents to retain. How can I do it using redirect? I am including the render statement I used and a screenshot of how it looks here: Steps: Handle post request Program execution code Save the result in a variable called "message". Then I used return render(request, 'editor.html', {'message': message}) I want to redirect the message to the same page without rendering a new page. [Before submission][1] [After submission][2] [1]: https://i.stack.imgur.com/BxoLU.png [2]: https://i.stack.imgur.com/uiEOU.png Any help will be appreciated. Thank you. -
Can a contains search be made in ElasticSearch in the search query?
I created a django project to learn ElasticSearch and when I search for users in this project, when I enter the username of the user exactly, the result is returned. Can I set this to contains as in django ORM? i use "match" because i just know it. q = request.GET.get('q') users = UserDocument.search().query("match",username=q) -
Posted data doesnt appear on DRF serializer attrs
im having an issue here and cant find out whats happening. I have and DRF REST API which must receive a POST to create an AlertRule object and a couple of EmailAddress objects related to it. The problem is that when debugging the validator method, the email data should come on the attr param on the validator mathod, but its just not there when i send the data obver http post. Example of what im sending: {'alert_event_max_count': 2, 'alert_time_window': 2, 'company': 'Q29tcGFueToxNw==', 'company_id': 17, 'comparison_rule': 4, 'comparison_value': '0', 'daily_start_time': '07:00:00', 'daily_stop_time': '17:59:59', 'emails': [{'email':'bruno.carli@smartgreen.net'}], 'end_date': '2022-01-01', 'installation_ids': [], 'monitored_property_id': 30, 'name': 'kk', 'start_date': '2019-01-01', 'week_day_bitmask':17} The attr only shows: OrderedDict([('alert_time_window', 2), ('alert_event_max_count', 2), ('company', <Company: Company object (17)>), ('comparison_rule', 4), ('comparison_value', '0'), ('daily_start_time', datetime.time(7, 0)), ('daily_stop_time', datetime.time(17, 59, 59)), ('end_date', datetime.date(2022, 1, 1)), ('installations', []), ('monitored_property', <Property: None - None>), ('name', 'loli'), ('start_date', datetime.date(2019, 1, 1)), ('week_day_bitmask', 17)]) Where is the 'emails': [{'email':'bruno.carli@smartgreen.net'}], data i have sent? Here the code: serializers class EmailSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'email'] model = EmailAddress class AlertRuleSerializer(serializers.ModelSerializer): emails = EmailSerializer(many=True, required=False) ... # other fields class Meta: model = AlertRule fields = [ ... # other fields 'emails' ] depth = 2 def … -
TimeoutError Error while sending email using Django and SMTP protocol
I have a Django project and an app inside the project. Now I am trying to send email using SMTP. But when I am trying send email it's showing this error: TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond The configuration for sending email in settings.py is : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = "MyEmailId" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = "MyPass" The code for sending email in views.py is : from django.core.mail import send_mail send_mail( 'email_subject', 'email_body', 'MyEmailId', ['ReceiverEmailId'], fail_silently=False, ) Thanks a lot for help. -
Error while getting database values into form
I am trying to get values from database and import them in checklist inside a form. I am getting values with CustomStudent.objects.all().values_list('sname') but values are retrieved as list which gives error when submitting. This is my forms.py class WeeklyForm(forms.Form): sname = forms.ModelMultipleChoiceField(queryset=CustomStudent.objects.all().values_list('sname'), required = False, widget =forms.CheckboxSelectMultiple( attrs ={'class':' form-check-input' ' form-check-inline'})) class_name = forms.CharField(widget= forms.Select(choices= [('1', 'UKG'), ('2', 'Class 1'), ('3', 'LKG'), ('4', 'Montessori') ] ,attrs={'class': 'form-control', 'placeholder' : 'Select Class'})) fdate = forms.DateField(initial = datetime.date.today() , required=False, widget =forms.DateInput( attrs ={'class': 'form-control' , 'placeholder' : ' Date ', 'name' : 'date'})) tdate = forms.DateField(initial = datetime.date.today() , required=False, widget =forms.DateInput( attrs ={'class': 'form-control' , 'placeholder' : ' Date ', 'name' : 'date'})) objective = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'objective'})) target = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'target'})) how = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'how?'})) material = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'material required'})) support = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'Any Support Required?'})) This is my model class CustomStudent(models.Model): _id = models.AutoField sname = models.CharField(max_length = 50) slname = models.CharField(max_length = 50) password = models.CharField(max_length = 255, default = '') I have tried adding CustomStudent.objects.all().values_list('sname', flat=True) which returns proper name instead … -
Python PIP version
I`m writing a django project, every time When I installed django: pip install "Django==3.0.*" I was encountering a WARNING: WARNING: You are using pip version 19.2.3, however version 20.3.3 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. But the strange thing is when I go to the PIP installations directory on Windows and Check for the pip version, I always got the version upgraded: ...Programs\Python\Python38\Scripts> pip --version pip 20.3.3 from c:\users\... This is very annoying, cause each time I pip install Django I have to upgrade it while it has been already upgraded. Somebody tell me how is this happen? -
how to add a link in django admin app that redirects to a html file
i have an application django admin based, in a specific admin page i have a fieldsets as below: def report(self, obj): return mark_safe(json2html.convert(json=obj.report, table_attributes="class=\"results\" style=\"overflow-x:auto;\"")) fieldsets = ( (None, { 'fields': ('complete',), }), ('Transaction Details', { 'fields': ('chp_reference', 'income_period', 'property_market_rent', 'rent_effective_date', 'number_of_family_group',), }), ('Report', { 'classes': ('collapse',), 'fields': ('report',), }), and in the models.py class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, @property def report(self): family_groups = [] for f in self.familygroup_set.all(): family_members = [] for m in f.familymember_set.all(): family_members.append({ 'name': str(m), 'rent_percentage': m.effective_rent_percentage, 'weekly_income': "%.2f" % float(m.weekly_income or 0), 'rent_component': "%.2f" % float(m.income_component or 0) }) report = [ family_groups, 'Household Rent: ' + "%.2f" % float(self.household_rent or 0) ] import json return json.dumps(report, indent=4) what im trying to do is to add a clickable link to the report function, and this link redirect the user to a html file that i will create, instead of the function i made in the models.py. what is the best approach to accomplish this ? -
Django max_length where there should not be a max_length
I do not have a deep understanding of Django, anyway not deep enough to overcome a problem that turns up in my application. In models.py I have a.o. the following definitions: class Relatiedata(models.Model): ... getuigen = models.TextField(blank=True, null=True) ... class Meta: db_table = 'relatiedata' Relatiedata.objects = Relatiedata.objects.using('genealogie') So in the database genealogie, which is not the default database, I have a table relatiedata with a column getuigen that has to contain a text string without a limitation on the length. Further, I have a user form for mutating records of this table. As usual, the form is populated from a Relatiedata.object and the returned form results in another Relatiedata.object which is saved, thereby updating the database. This works (almost) perfect. The problem is that in my form it turns out to be impossible to enter a string of length above 600 in the textarea for getuigen. Longer strings are simply cut off. There seems to be sort of a form validation for the length of that field, despite the fact that there is no such limit in the models, nor in the database, nor in the migration files. This value of 600 comes from earlier, abandoned, implementations of the model, … -
django fieldsets IndentationError: unindent does not match any outer indentation level
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from authentication.forms import UserForm, CustomUserChangeForm # Register your models here. User = get_user_model() class CustomUserAdmin(UserAdmin): add_form = UserForm form = CustomUserChangeForm model = User add_fieldsets = ( ('Personal Details', {'fields': ('email', 'full_name', 'username', 'picture', 'password1', 'password2')}), ('Permissions', {'fields': ('is_staff', 'is_active')}) ) fieldsets = ( ('Personal Details', {'fields': ('email', 'full_name', 'username', 'picture')}), ('Permissions', {'fields': ('is_staff', 'is_active')}) ) admin.site.register(User, CustomUserAdmin) I am working on web application for this i want to do some customization on my admin panel but it giving Indentation error. I also try it in list but it still showing me same error. What I did wrong! Traceback (most recent call last): File "C:\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "G:\Python\publish\env\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "G:\Python\publish\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "G:\Python\publish\env\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "G:\Python\publish\env\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "G:\Python\publish\env\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "G:\Python\publish\env\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 786, in exec_module File "<frozen importlib._bootstrap_external>", line 923, in get_code File "<frozen importlib._bootstrap_external>", line 853, in … -
How to add a custom input field into some Model Create form in django Admin
The question is How to add some custom form fields into django model create form and handle their values before create new Model into DB. I'm using django for my site, and there is a simple model Specialist { name, diploma, email, phone } also there is a model Topics { title, description } Each specialist can be experienced in different set of topics. There is a many to many relation via an extra Model TopicsSpecialists { specId, topicId } Standard Django admin allows me to create specialists and topics. Aslo to make it convenient i've provided Inline class TopicsInline(admin.TabularInline): extra = 1 model = Topics and passed it as in admin registration class SpecialistAdmin(admin.ModelAdmin): inlines = [TopicsInline,] Now list of extra fields were added to my Specialist creation form. It works well, but to make it more sense I would like to have a chance to have a set of checkboxes for each user to select topics instead of drop downs (as i have now). But would not add a bunch of bool fields into DB, just convert checkboxes to set of references before save specialist into DB There should be the way to customize model creation form. If … -
ManagementForm data is missing or has been tampered with for nested forms
I have the following Forms defined in my forms.py class MachineryGroupForm(ModelForm): class Meta: model = MachineryGroup fields = '__all__' class MachineryPartForm(ModelForm): class Meta: model = MachineryPart fields= '__all__' The following is the corresponding UpdateView: class MachineryGroupUpdate(UpdateView): model = MachineryGroup template_name = 'procman/machinerygroup_form.html' form_class = MachineryGroupForm success_url = 'machinery_group_list' MachineryPartFormSet = inlineformset_factory(MachineryGroup, MachineryPart, fields='__all__') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['parts'] = self.MachineryPartFormSet(self.request.POST, instance = self.object) else: data['parts'] = self.MachineryPartFormSet(instance = self.object) return data And Below is the template used to render the form: <h1>Machine Group</h1> <form method="post"> {% with named_formsets.MachineryPartFormFormSet as formset %} {{ formset.management_form }} {% csrf_token %} <table> {{ form.as_table }} {% if parts %} <table style="border-collapse: collapse; width: 100%;" border="1"> <br><br> <tbody> <thead> <td style="width: 14.2857%;">Group Code</td> <td style="width: 14.2857%;">Group Name</td> <td style="width: 14.2857%;"></td> <td style="width: 14.2857%;"></td> </thead> {% for part in parts %} <tr> <td style="">{{part.part_name}}</td> <td style="">{{part.part_number}}</td> <td style="width: 14.2857%;"><a href="#"> Edit</a></td> <td style="width: 14.2857%;"><a href="#"> Delete </a></td> </tr> {% endfor %} </tbody> </table> {% endif %}<br><br> </table> <br><br><input type="submit" value="Save"> {% endwith %} </form> I have tried every permutaion using {{formset}}, {{MachineryPartFormSet}} and also the last one using the with tags, but I am still getting the error: ['ManagementForm data is missing … -
Want to share backup file in Django web container with Postgres database container: How to?
I have a Django app on Docker with web container where automatics backups are stored and another postgresql database container. I want to be able to restore postgresql database using \i 'path\to\backup.psql' in a psql shell but it failed because file is not found db_preprod=# \i '/usr/src/app/backup/backup_2021-01-19_1336.psql' /usr/src/app/backup/backup_2021-01-19_1336.psql: No such file or directory I also tryed to copy with docker cp but not works: docker cp web:/usr/src/ap/backup/backup_2021-01-19_1336.psql db:/. copying between containers is not supported docker-compose version: '3.7' services: web: restart: always container_name: web build: context: ./app dockerfile: Dockerfile.preprod restart: always command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app:/usr/src/app - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.preprod depends_on: - db - redis healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/"] interval: 30s timeout: 10s retries: 50 db: container_name: db image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.preprod.db nginx: container_name: nginx build: ./nginx restart: always volumes: - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media ports: - 1340:80 depends_on: web: condition: service_healthy volumes: postgres_data: static_volume: media_volume: -
Djano recursive SubQuery
I'm tring to implement a query including a recursive function. I have in one hierarchical structure, i.e. every organisation has a head organisation which has also a head organisation and now I want to get the (head) organisation with level 3 of a given (sub) organisation. The corresponding model looks like this: class OrganisationHierarchy(TimeStampMixin): id = models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID') level = models.ForeignKey(OrgaLevel, on_delete=models.PROTECT, null=True, blank=True) name = models.CharField(max_length=60, blank=True) zip_code = models.ForeignKey(ZipCode, on_delete=models.PROTECT, null=True, blank=True) parent = models.ForeignKey('self', null=True, on_delete=models.PROTECT, related_name='organisationhierarchy', blank=True) The query below works except getting the head organisation. I have written a separate method for this, but I don't know how to get the current organisation into this value, i.e when doing head_organisation=get_head_organisation_name(F('organisation')) then the method receives F('organisation') and not the value of organisation class EventGeneralSerializer(serializers.ModelSerializer): locations = serializers.SerializerMethodField('get_locations') class Meta: model = Event fields = ( 'locations', ) def get_head_organisation_name(self, organisation): if organisation.level_id > 3: return self.get_head_organisation_name(organisation.parent) elif organisation.level_id < 3: raise Exception("To low value") else: return organisation.name def get_locations(self, obj): result = obj.registration_set.values('organisation__name').annotate( participants=Coalesce(Sum('participantgroup__number_of_persons'), 0) + Coalesce(Count('participantpersonal'), 0), head_organisation=F('organisation__parent__parent__name')) \ <-- Insert recursive method here .values('organisation__name', 'participants', 'head_organisation', lon=F('organisation__zip_code__lon'), lat=F('organisation__zip_code__lat'), ) return result So thanks for your help in advance! -
Django REST API followers system
I'm trying to make a rest API for a blog app using Django-rest-framework. I'm a beginner and it's hard for me to understand how to implement that system. I made an intermediary model for making connections between followers and followings and serializers for users. But my API showing absolutely wrong following and followers for each user and endpoints for following and unfollowing not working also. Models.py: class UserFollowing(models.Model): class Meta: constraints= [ models.UniqueConstraint(fields=['user_id', 'following_user_id'], name='unique_following') ] ordering = ['-created'] user_id = models.ForeignKey('auth.User', related_name='following', on_delete=models.SET_NULL, null=True,blank=True) following_user_id = models.ForeignKey('auth.User', related_name='followers', on_delete=models.SET_NULL, null=True,blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user_id} is following {self.following_user_id}' serializers.py: class UserSerializer(serializers.HyperlinkedModelSerializer): following = serializers.HyperlinkedRelatedField(many=True, view_name='user-detail', read_only=True) followers = serializers.HyperlinkedRelatedField(many=True, view_name='user-detail', read_only=True) posts = serializers.HyperlinkedRelatedField(many=True, view_name='post-detail', read_only=True) class Meta: model = User fields = ['url', 'id', 'username', 'posts', 'following', 'followers'] def get_following(self, obj): return FollowingSerializer(obj.following.all(), many=True).data def get_followers(self, obj): return FollowersSerializer(obj.followers.all(), many=True).data class UserFollowingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserFollowing fields = '__all__' class FollowingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserFollowing fields = ['id', 'following_user_id', 'created'] class FollowersSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserFollowing fields = ['id', 'user_id', 'created'] views.py: class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class UserFollowingViewSet(viewsets.ModelViewSet): queryset = UserFollowing.objects.all() serializer_class = UserFollowingSerializer class UserFollow(APIView): """ Retrieve, update … -
Django nested regroup
I use Django 2.2.12 I have three models: RiskRating is pointing to RiskType which is pointing to RiskCategory with ForeignKeys. class RiskCategory(models.Model): name = models.CharField(max_length=400, blank=True) class RiskType(models.Model): riskcategory = models.ForeignKey(RiskCategory, on_delete=models.CASCADE, related_name="risksforcategory") class RiskRating(models.Model): risktype = models.ForeignKey(RiskType, on_delete=models.CASCADE, related_name="ratingsforrisk") In my view: riskratings = Riskrating.objects.all() I would like to display RiskRating grouped by RiskCategories, i.e. I would like to do a nested regroup as following: {% regroup riskratings by risktype.riskcategory as ratingsbycategory %} How can I do that ? Thanks a lot -
django encrypt files before storage
So I want to encrypt files before storage in django and decrypt them upon retireval. I am using a custom storage class for the same and the cryptography module. import hashlib import os import uuid import django.core.files.storage as storage from cryptography.fernet import Fernet from django.conf import settings from django.core.files import File class DefaultStorage(storage.FileSystemStorage): def __init__(self): super(DefaultStorage, self).__init__() self.encryptor = Fernet(settings.ENCRYPTION_KEY) def _save(self, name, content): encrypted = self.encryptor.encrypt(content.file.read()) content.file.write(encrypted) print(content.file.read() == encrypted) return super(DefaultStorage, self)._save(name, content) def _open(self, name, mode='rb'): encrypted = open(self.path(name), mode).read() return File(self.encryptor.decrypt(encrypted)) def get_available_name(self, name, max_length=None): # we return a hash of the file given, # in case we miss out on uniqueness, django calls # the get_alternative_name method dir_name, file_name = os.path.split(name) file_root, file_ext = os.path.splitext(file_name) file_root = hashlib.md5(file_root.encode()).hexdigest() name = os.path.join(dir_name, file_root + file_ext) return super(DefaultStorage, self).get_available_name(name, max_length) def get_alternative_name(self, file_root, file_ext): # we insert a random uuid hex string into the given # file name before returning the same back return '%s%s%s' % (file_root, uuid.uuid4().hex, file_ext) I am overwritting the _save and _open methods here, but the class doesn't work as expected. Under the save method, I want to encrypt the contents of the file, but when I print this print(content.file.read() == encrypted) It … -
Attribute Error in Django,when using IMDbpy
I am trying to use the IMDbpy library in my django projects,but it raises an Attribute Error. I tried all the solutions available on the internet,but none seem to work,could you please help me with this? The Error: moviesDB = imdb.IMDb() AttributeError: module 'imdb' has no attribute 'IMDb' The code: import imdb moviesDB = imdb.IMDb() movies= moviesDB.search_movie('whatever_movie') id = movies[0].getID() movie = moviesDB.get_movie(id) print(movie) title=movie['title'] rating = movie['rating'] cover=movie['cover url'] print(title,rating,cover) I have been scratching my head the entire day,due to this error,I'm kinda new to this,so please help! I tried reinstalling the imdbpy library,pip3 installed it,renamed it but nothing seems to be working. The code is working in external files,but in the views.py in django,it just doesnt seem to work please help! -
Parts of CSS styles are not loaded when routing between React Components until refreshing the page?
I build a Django project, and using Webpack to create the React bundle rendered in Django template body. I tried to load CSS files either in Django template or in App.js but same results. When I switch between React pages parts of the CSS is not loaded, but when I refresh the page all the CSS and JS files are loaded. {% load i18n %} {% load static %} {% load render_bundle from webpack_loader %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="OneUIUX HTML website template by Maxartkiller. Bootstrap UI UX, Bootstrap theme, Bootstrap HTML, Bootstrap template, Bootstrap website, multipurpose website template. get bootstrap template, website"> <meta name="author" content="Maxartkiller"> <link rel="stylesheet" href="{% static 'css/swiper.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/newstyle.css' %}"> <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery.cookie.js' %}"></script> <script src="{% static 'js/masonry.pkgd.min.js' %}"}></script> <script src="{% static 'js/swiper.min.js' %}"></script> <script src="{% static 'js/main.js' %}"></script> </head> <body> <div id='reactify-django-ui'> {% render_bundle 'main' %} </div> </body> </html> And my Webpack config file const path = require("path"); const host = process.env.HOST || 'localhost'; const devPort = 3000 var webpack = require('webpack'); … -
How to securely store OAuth2 access and refresh tokens in Django
I'm trying to implement the Azure AD OAuth authentication for our Django app and I would be doing that with Azure AD as an OAuth provider. So now I wanted to know how securely we can store the OAuth access/refresh tokens in the DB that we receive from Azure AD or any OAuth provider. I want to store the user's access token in DB because we have a feature in our web app where users can send an email with their email ID and we have a periodic job that runs every half an hour and it's gonna fetch user's mails based on a specific subject line. This we're gonna do with the help of Microsoft's Graph API and in order to call Microsoft Graph API, the web app should store the user's access token may be in the DB. But my concern is once we receive the access and refresh token, it shouldn't be accessed by anyone once we store it in the DB. So how securely or in an encrypted way we can store the OAuth2 access tokens in Django. I have gone through a few articles, QnA, and forums on this concern but wanted to hear from … -
Django field that can be either IntegerField or DecimalField
In one of my Django model, I have a field that can be either an IntegerField or a DecimalField based on the user. When the value of the record is an integer, the form should only display/edit it without trailing digits. When the value of the record has decimals, all decimals should be displayed/edit on the form. I have tried defining this field as a DecimalField and play with the form, but the challenge is that I use django-crispy-forms to render my forms so I cannot use the floatformat filter in my template. As a result, 5 as an integer, for instance, is displayed as 5.00000000 in my form. Is there a way around this?