Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add songs to my templates in views
if i post a song from my admin panel, i want the list of song to appear in the templates, i already created a models that allow me to post it, but i don't know how to create a views that allowed the song to appear in the templates, please how can i do this ? this is my empty views views.py from django.shortcuts import render from .models import Audio # Create your views here. def index(request): return render(request, 'index.html') this is my models.py i created models.py from django.db import models # Create your models here. class Audio(models.Model): book_title = models.CharField(max_length=100, null=False, blank=False) file = models.FileField(upload_to='file') author = models.CharField(max_length=100, null=False, blank=False) artist = models.CharField(max_length=100, null=False, blank=False) -
how to embed facebook video in django project
what is the easiest way to embed facebook live video or any facebook video in any django website ? I used https://github.com/jazzband/django-embed-video package but it's work only for youtube video . -
Django: Django_filters in a class-based views
I ask you if you know how put this filters : class CoursesFilters(django_filters.FilterSet): class Meta: model = Courses exclude = ('description') in this class view : class CoursesList(ListView): model = Courses template_name = 'courses_list.html' I used to build my applications using function-based views, and this is my first time use class-based views. Any idea? -
How to access HTTPS on development server
I have Django project, I tried to run develop SSL server by python manage.py runserver_plus --cert-file cert.crt, but anytime I get error Site doesn't reach, how i can fix it? I have mapped my hosts.ics file, tried also a sslserver, there is nothing working -
How to disable method in Django APIView?
My question is same title. How to disable method in Django APIView? for example, class A(APIView): permission_classes = [IsAuthenticated] def get(self, request): return JsonResponse({"message": "Hello, world!"}) I want to only get method allowed, How can I? -
Exception has occurred: AttributeError 'NoneType' object has no attribute 'split'. When debugging with Docker and VSCode
I'm setting up a debugger using docker-compose following this guide. I've modified the file manage.py to run debugpy when setting.DEBUG exists but when redding the settings file it throws an exception of 'NoneType' object has no attribute 'split'. Here are the files I'm using: .env.dev DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 0.0.0.0[::1] manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') # start new section from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import debugpy debugpy.listen(("0.0.0.0", 5678)) print('Attached!') # end new section try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Any ideas? -
Inheritance in Django: Make parent class fall back to child method
Tl;Dr: Circumvent that parents can not call child methods in python (I guess) Consider the following (simplified) django models were MaterialInstance and BookInstance both inherit Item. class Item(models.Model): """Represents an item that is physically in the library""" label = models.CharField(max_length=20, unique=True) @property def description(self) -> str: raise NotImplementedError class BookInstance(Item): """Represents a copy of a book that is physically in the library""" @property def description(self) -> str: return str(self.book) book = models.ForeignKey('Book', on_delete=models.RESTRICT) class MaterialInstance(Item): """Represents a instance of a material that is physically in the library""" @property def description(self) -> str: return str(self.material) material = models.ForeignKey('Material', on_delete=models.RESTRICT, null=True) I want to show all items (books AND material instances) in one table. One row should be a description (either the book title or the material name). It would be nice to use the following template (but this raises a NotImplementedError as the parent class does not try to call child methods. Any suggestions for a clever design that circumvents this problem? <table> <tr> <th>Label</th> <th>Description</th> </tr> {% for item in item_list %} <tr>{{ item.label }}</td> <td>{{ item.description }}</td> </tr> {% endfor %} </table> The final thing should look something like this |Label|Description| |---|---| |B1 | A Boring Book Title| |B2 … -
How can I filter on multiple NOT conditions in Django's ORM?
In Django 3.2, I have the following models: class Person(models.Model): name = models.CharField(max_length=100) class Employment(models.Model): owner = models.ForeignKey('Person', on_delete=models.CASCADE) title = models.CharField(max_length=100) full_time = models.BooleanField(default=True) class Car(models.Model): owner = models.ForeignKey('Person', on_delete=models.CASCADE) color = models.CharField(max_length=100) The Goal: Give me all people that drive a red car (unless they're a full-time firefighter) Here is what I thought would work: Person.objects.filter( ~Q(employment__title='firefighter', employment__full_time=True), car__color='red' ) However, this generates the following SQL: SELECT * FROM "person" INNER JOIN "car" ON ("person"."id" = "car"."owner_id") WHERE "car"."color" = red AND ( NOT ( EXISTS( SELECT (1) AS "a" FROM "employment" U1 WHERE U1."full_time" AND U1."owner_id" = "person"."id" ) AND EXISTS( SELECT (1) AS "a" FROM "employment" U1 WHERE U1."title" = firefighter AND U1."owner_id" = "person"."id" ) ) This in effect returns all people that drive a red car (unless they are a firefighter OR have full-time employment). Like all other filter keys, I would have expected the two conditions on the foreign relation to be ANDED. Why the unexpected behavior? What's the right way to write this so the sql looks like this:? SELECT * FROM "person" INNER JOIN "car" ON ("person"."id" = "car"."owner_id") WHERE "car"."color" = red AND ( NOT ( EXISTS( SELECT (1) AS … -
Django Annotation with boolean field ExpressionWrapper
I'm trying to create a high score statistic table/list for a quiz, where the table/list is supposed to be showing the percentage of (or total) correct guesses on a person which was to be guessed on. To elaborate further, these are the models which are used. The Quiz model: class Quiz(models.Model): participants = models.ManyToManyField( User, through="Participant", through_fields=("quiz", "correct_user"), blank=True, related_name="related_quiz", ) fake_users = models.ManyToManyField(User, related_name="quiz_fakes") user_quizzed = models.ForeignKey( User, related_name="user_taking_quiz", on_delete=models.CASCADE, null=True ) time_started = models.DateTimeField(default=timezone.now) time_end = models.DateTimeField(blank=True, null=True) final_score = models.IntegerField(blank=True, default=0) This models does also have some properties; I deem them to be unrelated to the problem at hand. The Participant model: class Participant(models.Model): # QuizAnswer FK -> QUIZ guessed_user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="clicked_in_quiz", null=True ) correct_user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="solution_in_quiz", null=True ) quiz = models.ForeignKey( Quiz, on_delete=models.CASCADE, related_name="participants_in_quiz" ) @property def correct(self): return self.guessed_user == self.correct_user To iterate through what I am trying to do, I'll try to explain how I'm thinking this should work: For a User in User.objects.all(), find all participant objects where the user.id equals correct_user(from participant model) For each participantobject, evaluate if correct_user==guessed_user Sum each participant object where the above comparison is True for the User, represented by a field … -
why doesn't django log the specified application?
I has some project with application named "work". The directory of the app also named work, and inside apps.py its also named "work", and in INSTALLED_APPS also, etc. And I try to log just the application into file. So. I have prescribed the following settings in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'file_logger': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, 'handlers': { 'file_logger': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': './logging.txt', }, }, 'loggers': { 'work.views': { 'handlers': ['file_logger'], 'level': 'DEBUG', 'propagate': True, }, }, } I initialized inside my views.py (views.py of work app) logger like this: logger = logging.Logger(__name__) where __name__ is "work.views" (I checked this one via debugger) and I have some view, which I want to log: def view_timesheet(request, t_id=None): logger.warning('wwwwwwwwwwwwwwwww') # some code return HttpResponse('ok') but when I execute the code of this view, nothing is written to the file. With what "wwwwwwwww" gets logged in the console This confuses me, because it seems to me that I have done everything according to the documentation and everything should work A few more details: If I write "django" instead of "work.views" all django logs will end up in a file. This leads … -
Why am I unable to set my GeoDjango database engine to 'django.contrib.gis.db.backends.postgis' on heroku?
I've had the same problem for several days now, and it seems like no matter what I do, I can't set my database engine to 'django.contrib.gis.db.backends.postgis' on heroku. The problem has me so stuck that it's driven me to finally make my first Stack Overflow post. I can see the engine is 'django.db.backends.postgresql_psycopg2' when I check the database settings in heroku: % heroku run bash ~ $ python manage.py shell >>> from django.conf import settings >>> settings.DATABASES {'default': {'NAME': [name], 'USER': [user], 'PASSWORD': [password], 'HOST': [host], 'PORT': 5432, 'CONN_MAX_AGE': 600, 'OPTIONS': {'sslmode': 'require'}, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'TIME_ZONE': None, 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}}} I've come to believe that the problem has to do with me not understanding how heroku uses the django settings.py file to set up the database. For example, I'm wondering if I'm doing things in the wrong order. Originally, I set up the heroku database with the below commands and then afterwards pushed my geodjango project to Heroku. % heroku addons:create heroku-postgresql:hobby-dev % heroku pg:psql app::DATABASE=> create extension postgis; I've also tried deleting the database entirely and then pushing my code to Heroku because I thought maybe heroku … -
Firebase for notification and aws for backend and database
I am trying to implement a notification system in Django. I find the firebase quite easy which is as follow: from fcm_django.models import FCMDevice device = FCMDevice.objects.all() Now in view: device.send_message(title="Title", body="Message", icon=..., data={"test": "test"}) In settings: FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "[string for AppConfig's verbose_name]", # true if you want to have only one active device per registered user at a time # default: False "ONE_DEVICE_PER_USER": True/False, # devices to which notifications cannot be sent, # are deleted upon receiving error response from FCM # default: False "DELETE_INACTIVE_DEVICES": True/False, # Transform create of an existing Device (based on registration id) into # an update. See the section # "Update of device with duplicate registration ID" for more details. "UPDATE_ON_DUPLICATE_REG_ID": True/False, } Now my question is, we are using AWS for the backend and also for the database. In this case can we use the firebase for notification? How do these two services aws and firebase work together? WIll there be any problem?? -
How do i replace or overwrite imagges stored in cloudinary using django
I want to setup user profile pic but do not want to keep adding new files each time they change the picture is there a way to overwrite or replace an image in the cloudinary database Here is Models : class CloudinaryField(BaseCloudinaryField): def upload_options(self, model_instance): return { 'public_id': UserProfile.user.username, 'filename': "Hey", 'unique_filename': False, 'overwrite': False, 'resource_type': 'image', 'tags': ['Profile'], 'invalidate': True, 'quality': 'auto:eco', } class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) Nick_Name = models.CharField(default="Hey", max_length=250) Profile_pic = CloudinaryField('Profile_Pic', default="") forms : class UserProfilePage(forms.ModelForm): class Meta: model = UserProfile fields = ['Nick_Name', 'Profile_pic'] help_texts = { 'Nick_Name': 'This will act as your display name', } Profile_pic = CloudinaryFileField( options={ 'folder': 'Profile/', }) And finally the views : def edit(request): func = data(request) form = UserEdit(initial={'email': request.user.email}) profile = UserProfilePage(initial={'Nick_Name': request.user.userprofile.Nick_Name, 'Profile_pic': request.user.userprofile.Profile_pic.url}) if request.method == "POST": form = UserEdit(data=request.POST or None, instance=request.user) profile = UserProfilePage(data=request.POST or None, instance=request.user.userprofile, files=request.FILES) if form.is_valid() and profile.is_valid(): user = form.save() profiles = profile.save() return redirect("Profile_Page") ctx = { 'form': form, 'profile': profile, 'url': func[0], 'name': func[1], 'date': func[2], } return render(request, "Edit_User.html", ctx) If any more code is required please comment it i will for sure edit it into the question Thanks a … -
Django Mixing Static and Media(Public/Private)
Whenever I run the following I get (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "C:\Users\arund\Desktop\Code\Django\portfolio-project\manage.py", line 22, in <module> main() File "C:\Users\arund\Desktop\Code\Django\portfolio-project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 187, in handle collected = self.collect() File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\storages\backends\s3boto3.py", line 469, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\botocore\client.py", line 391, in _api_call return self._make_api_call(operation_name, kwargs) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\botocore\client.py", line 691, in _make_api_call request_dict = self._convert_to_request_dict( File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\botocore\client.py", line 737, in _convert_to_request_dict api_params = self._emit_api_params( File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\botocore\client.py", line 766, in _emit_api_params self.meta.events.emit( File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\botocore\hooks.py", line 357, in emit return self._emitter.emit(aliased_event_name, **kwargs) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\botocore\hooks.py", line 228, in emit return self._emit(event_name, kwargs) File … -
Set ForeignKey in Django Error : matching query does not exist
I want to set ForeignKeys to my tables in views.py but I got this Error Words matching query does not exist. at this line of code : word_id = Words.objects.get(pk= wordID), I don't know what's wrong and Why I got this error? So how I should set the foreign keys? this is my model.py code class Words(models.Model): word = models.CharField(max_length=50) phonetic= models.CharField(max_length=50) audio= models.URLField(max_length = 200) class Meanings(models.Model): word_id = models.ForeignKey(Words, on_delete=models.CASCADE) partOfSpeech = models.CharField(max_length=30) class Definitions(models.Model): word_id = models.ForeignKey(Words, on_delete=models.CASCADE) Meaning_id = models.OneToOneField(Meanings, on_delete=models.CASCADE, primary_key=True) definition = models.TextField() def __str__(self): return self.definition and this is the views.py : def get_details(request): words = ['hello', 'table' , windows'] wordID = 0 MeaningID = 0 for word in words: wordID+=1 print(word) url = 'https://api.dictionaryapi.dev/api/v2/entries/en/' + word response = requests.get(url) if type(response.json()) == list: response = response.json()[0] # convert list to dictionary word = response.get('word',{}) phonetics = response.get('phonetics',{}) phonetic = phonetics[0] print(phonetic) word_data = Words( word = response.get('word',{}), phonetic = phonetic.get('text', {}), audio = phonetic.get('audio', {}) ) word_data.save() meanings = response.get('meanings',{}) for i in range(len(meanings)): MeaningID +=1 meaning_data =Meanings( word_id = Words.objects.get(pk= wordID), partOfSpeech = meanings[i].get('partOfSpeech',{}) ) meaning_data.save() definitions_data = Definitions( word_id = Words.objects.get(id= wordID), meaning_id = Meanings.objects.get(id= MeaningID), definition = meanings[i].get('definition',{}) ) … -
Wrong distance calculation between two Points in django
I have a model that uses PointField to store location: from django.contrib.gis.db import models from django.contrib.gis.geos import Point class Post(models.Model) location = models.PointField() and trying to do the following calculation: initial_location = Post.objects.first().location last_location = Post.objects.last().location total_distance = initial_location.distance(last_location) The values for this locations are: print(initial_location) >>> SRID=4326;POINT (-1.407385628884526 -24.29361291088179) print(last_location) >>> SRID=4326;POINT (65.55023895708794 43.8537639564256) print(total_distance) >>> 95.53736684717059 Ok, at first glance I thought it was working, but this value is totally wrong. Using this site to convert decimal coordinates to degrees coords and this site to calculate the distance based on this coords, I get a result almost 100 times higher than Django is printing. I'm not sure what is wrong since all of these methods and functions are built-in of the Point class. -
how to get the Userid in GET method in Django Rest framework
I'm trying to pass the requested "userid" to the Stored Procedure but I couldn't able to get the requested "userid" in GET method. SP is working fine when I entered user id directly views.py: @api_view(['GET', 'POST']) def ClaimReferenceView(request, userid): try: userID = Tblclaimreference.objects.filter(userid=userid) except Tblclaimreference.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': user = Tblclaimreference.objects.get(userid=self.request.user.id) print(user) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaims] @UserId= %s',(user,)) result_set = cursor.fetchall() print(type(result_set)) response_data = [] for row in result_set: response_data.append( { "Number": row[0], "Opened": row[1], "Contacttype": row[2], "Category1": row[3], "State": row[4], "Assignmentgroup": row[5], "Country_Location": row[6], "Openedfor": row[7], "Employeenumber": row[8], "Shortdescription": row[9], "AllocatedDate": row[10] } ) return Response(response_data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = ClaimReferenceSerializer(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) models.py: class Tblclaimreference(models.Model): taskid = models.IntegerField(db_column='TaskId', primary_key=True) userid = models.IntegerField(db_column='UserID') internaldescription = models.CharField(db_column='Internaldescription', max_length=500, blank=True, null=True) additionalcomments = models.CharField(db_column='Additionalcomments', max_length=500, blank=True, null=True) -
ModuleNotFoundError: No module named 'django.db.backends.postgresql'
Try to migrate local_proxy but i got this error as shown below; Using CMD: DJANGO_SETTINGS_MODULE=maroxie.settings.local_proxy python manage.py migrate ??? Fig:1 enter image description here Fig:2 enter image description here -
Python Django ModeulNotFoundError: No module named 'SomeFolder'
I have a django app. It is quite complicated, I can't post all the code here, so I have a big picture summary. The setup of the folders in the big picture related to what I'm doing is below. Note that "SomeFolder" is a placeholder name for the actual name. Some folder is a folder containing some python scripts with functions inside of them. It wasn't installed in the Django app. I dragged and dropped SomeFolder into the backend folder. This is necessary and had to be done. It's some python stuff unrelated to Django. Dashboard backend SomeFolder A.py B.py C.py views.py Dashboard frontend manage.py Inside of views.py at the top, I do import SomeFolder Then, inside of views.py, I have a function that calls some of the functions within the python scripts A.py, B.py, and C.py. This is why I need to import SomeFolder. For example: def someFunction(): SomeFolder.A_Function_1 SomeFolder.A_Function_2 SomeFolder.B_Function_2 etc. The issue is, when I run python manage.py runserver I get a ModuleNotFoundError: No module named 'SomeFolder' in views.py. The SomeFolder folder is in the same directory as views.py, so I'm not sure why it's not being recognized. I've seen other similar examples on stackoverflow, but didn't … -
uploaded files by users in website are not showing when debug is false
hey I've been working on my website for quite a while now and finally I was deploying it for production then I've faced with this problem that I can't server media when DEBUG = FALSE apparently Django doesn't serve media for you in production for some reasons, IDK how to fix this and in my templates I've used this method to show different pictures that user have uploaded on website's database <img src="{{site.logo.url}}" alt="logo" class="footer_logo"> now none of then show up in website here are my media and static roots in setting.py STATIC_URL = '/static/' STATIC_ROOT = '../mywebsite/assets/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Additional locations of static files STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), I don't have a same problem with static files and I've almost tried all of the ways that others have recommended for same situation in other questions. also I have no idea how to setup nginx but I have no problem with setting it up and learn about it if you guys can give me a guide an how to do it, there was some tutorial on how to deploy django on Nginx with uWSGI but: first idk what is uWSGI and since I'm using … -
drf> What can I do for using annotate from M2M model
I have 4 models like this. user model class User(model.Model): name=models.ChaField() diary model class Diary(): title=charfield author=Foreignkey("user.User") recommend_diary model class RecommendDiary(): section=Foreignkey("recommend.RecommendSection") diary=Foreignkey("diary.Diary") recommend_section model class RecommendSection(): section=charfield diaries=M2M("diary.Diary", through=RecommendSection) when I give to users recommend item, I want to make an annotation that excludes blocked users. The queryset given to me is this queryset=Recommend.objects.filter(start time-end time) So I can take an object of a given queryset and check numerous diaries associated with this object like this. obj=queryset.first() diary_queryset=obj.diaries.all() (I made custom manager for this) After checking that the request user is blocked from the user who wrote this diary, and I can exclude it from the queryset. diary_list=[diary for diary in diary_queryset if diary.id not in block_list] but I got a filtered list not Queryset. and it is not RecommendSection queryset even. can I get a excluded RecommendSection queryset from blocked user by using annotate or something else? I wanna exclude block user list from RecommendSection ex) queryset=RecommandSection.objects.exclude(diary_id__in=block_user) (it doesnt work btw) I wanna use .annotate if able thx for help. -
Django - Encrypt whole instance
I'm currently figuring out what would be the best way to encrypt an instance of a model in Django. Encrypting single fields seems easy, but I would like to encrypt a whole instance. Context I'm currently building a note-taking application which should have the ability to optionally encrypt a note using a given password. The model looks something like this: class Note(models.Model): title = CharField() content = TextField() created_at = DateTimeField() edited_at = DateTimeField() While I could simply only encrypt the title and content, I don't want that to avoid telling any information about a note when it is encrypted. So basically all fields (event created_at and edited_at) should be encrypted. Thoughts I thought about adding a second model EncryptedNote which only holds a field encrypted_data. This field contains the data in a JSON format in an encrypted form. When the application needs to load the instance, it will decrypt the content and create a Note instance based on the JSON data. However, it feels a little bit off to manually save JSON when using a SQL-like database. Question Is there already a good (and secure) way to encrypt an instance or is this idea of manually encrypting and decrypting … -
NextJS/Django 404 page issue & Unhandled runtime error
So I am creating a blog using django as a backend, nextjs as a fronted. I am having an issue with categories in navbar, as all of them are returning 404 error (just before 404, I get Unhandled runtime error for less than a second, I attached a screenshot) Anyway, here is my Navbar.js component, where I use categories import Link from 'next/link' const Navbar = () => { return ( <nav className='navbar navbar-expand-lg navbar-light bg-light'> <div className='p-2 text-muted'><Link className='navbar-brand' href={'/'}>5minRead</Link></div> <button className='navbar-toggler' type='button' data-toggle='collapse' data-target='#navbarNavAltMarkup' aria-controls='navbarNavAltMarkup' aria-expanded='false' aria-label='Toggle navigation'> <span className='navbar-toggler-icon'></span> </button> <div className='collapse navbar-collapse' id='navbarNavAltMarkup'> <div className='navbar-nav'> <div className='p-4 text-muted'><a href={'/category/world'}>WORLD</a></div> <div className='p-4 text-muted'><Link href={'/category/enviroment'}>ENVIROMENT</Link></div> <div className='p-4 text-muted'><Link href={'/category/technology'}>TECHNOLOGY</Link></div> <div className='p-4 text-muted'><Link href={'/category/culture'}>CULTURE</Link></div> <div className='p-4 text-muted'><Link href={'/category/business'}>BUSINESS</Link></div> <div className='p-4 text-muted'><Link href={'/category/health'}>HEALTH</Link></div> <div className='p-4 text-muted'><Link href={'/category/travel'}>TRAVEL</Link></div> <div className='p-4 text-muted'><Link href={'/category/fashion'}>FASHION</Link></div> <div className='p-4 text-muted'><Link href={'/category/opinion'}>OPINION</Link></div> <div className='p-4 text-muted'><Link href={'/subscribe'}>SUBSCRIBE</Link></div> </div> </div> </nav> ) } export default Navbar here is my Category.js component (any category click from Navbar should navigate here) const Category = () => { return ( <div> category </div> ) } export default Category here is my views.py that contain APIView class BlogPostCategoryView(APIView): serializer_class = BlogPostSerializer permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category … -
Django Rest Framework - How to make extra query before serializer.save
I'm new to Django Rest Framework and I'm trying to do this simple thing, but I'm not sure how to do it. So, this is my models.py class Category(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) email = models.EmailField(_('email address'), blank=True, null=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Report(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) description = models.TextField() address = models.CharField(max_length=500) reporter_first_name = models.CharField(max_length=250) reporter_last_name = models.CharField(max_length=250) reporter_email = models.CharField(max_length=250) reporter_phone = models.CharField(max_length=250) report_image_1 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) report_image_2 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) report_image_3 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) date = models.DateTimeField(default=timezone.now) class Meta: ordering = ('-date',) def __str__(self): return self.description I have a form in React that submits, among other values, the category ID. What I need to do, before saving the report to the DB, is send a mail to the email address of that category ID. This is my views.py class ManageCategories(viewsets.ModelViewSet): serializer_class = CategorySerializer def get_object(self, queryset=None, **kwargs): item = self.kwargs.get('pk') return get_object_or_404(Category, slug=item) def get_queryset(self): return Category.objects.all() class ManageReports(viewsets.ModelViewSet): serializer_class = ReportSerializer parser_classes = [MultiPartParser, FormParser] def get_permissions(self): if self.action == 'create': self.permission_classes = [permissions.AllowAny] else: self.permission_classes = [permissions.IsAuthenticated] return super(self.__class__, self).get_permissions() def create(self, request, *args, **kwargs): serializer = ReportSerializer(data=request.data) if … -
Supervisor when uploading a project to the server
I am trying to run my site (Django based) on a VPN server and I am having a problem. I am unable to set up a supervisor. When entering the command sudo supervisorctl reread The message appears: no config updates to processes It is quite possible that this is due to the fact that I changed the configuration file. But what to do now, I do not know. I changed the configuration file, but currently there are no errors.