Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django vs Flask - Which framework is more powerful considering I want to design an end to end IOT solution
Planning to build an end to end IOT application. I know that we can do it using Django and Flask. Which one is a better choice and how it is better? -
django dependent dropdown is not working though implemented according to a blog
I have a dependent dropdown list in my template. forms.py class Bill_CreateForm(forms.ModelForm): def __init__(self, context, *args, **kwargs): super(Bill_CreateForm, self).__init__(*args, **kwargs) self.fields['added_by'] = forms.ChoiceField(choices=tuple([(name, name.members) for name in context['users']])) self.fields['added_to'] = forms.ChoiceField(choices=tuple([(name.id, name.group_name) for name in context['groups']])) self.fields['share_with'].queryset = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([])) if 'group' in self.data: try: group_id = int(self.data.get('group')) u_l = GroupMembers.objects.filter(group_name=group_id).order_by('members') self.fields['share_with'].queryset = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([(name, name.members) for name in u_l])) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['share_with'].queryset = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple(self.instance.group.groupmembers_set.order_by('name'))) class Meta: model = Transactions fields = ( 'bill_type', 'amount', 'added_by', 'added_to', 'share_with', ) template {% extends 'base.html' %} {% load crispy_forms_tags %} {% block body %} <div class='container'> <div class='row justify-content-center'> <div class='card' style='width: 28rem;;margin: 0 auto;float: none; margin-bottom: 10px; /* Added */'> <div class="card-body"> <form method='post' id='billform' user-data-url="{% url 'ajax_load_users' %}" novalidate> {% csrf_token %} {{ form|crispy }} <button class='btn btn-primary'> Add bill </button> </form> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $("#id_added_to").change(function () { var url = $("#billform").attr("user-data-url"); // get the url of the `load_cities` view var group_id = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) … -
PyCharm Cannot resolve file "url" in Django project
I am using PyCharm Professional 2019.3 and Django 3.0. PyCharm highlights <a href="/login/">Log In</a> with the following inspection Cannot resolve file: login (Inspection info: This inspection checks unresolved file references in HTML.) How do I configure PyCharm to pick up urls and inspect correctly? -
'Image' object has no attribute '_committed' while generating Qr code from model
from django.db import models import qrcode model # Create your models here. class Customer(models.Model): name=models.CharField(max_length=255) address=models.CharField(max_length=255) gender=models.CharField(max_length=255) registerd_date=models.DateTimeField(auto_now_add=True, blank=True) Image = models.ImageField(upload_to="media/static/images/",blank=True,null=True) def __str__(self): return self.name function take data and convert to qr code and save to model field data def save(self, *args, **kwargs): self.Image=qrcode.make(self.name) super(Customer,self).save(*args, **kwargs) -
How to make Django models refer to each other bidirectionally?
I am trying to create a relationship where a blog post can be assigned any number of tags, and a tag can be associated with any number of blog posts. But I'm having difficulty setting up this bidirectional relationship. Right now, to create a blog post and assign any number of tags, here is my model for the posts: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=100, unique=True, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) tags = models.ManyToManyField("Tags", blank=True) content = RichTextUploadingField() created_on = models.DateTimeField(auto_now_add=True) And the model defining the tags: class Tag(models.Model): name = models.CharField(max_length=20, unique=True) This works. I can log into the admin interface and create a bunch of tag objects, then create a post object and assign it any number of those tags. But let's say I also want to do the opposite. I want to be able to log into the admin interface, select a tag object, and then associate it with any number of post objects. I tried to do this by defining a ManyToManyField in the Tag model like so: class Tag(models.Model): name = models.CharField(max_length=20, unique=True) posts = models.ManyToManyField("Post", blank=True, related_name="posts") This does show a list of posts on the change … -
Django Admin custom record view
I want to create a custom view which, unlike the changelist_view, shows you the record instead of showing you a form. It will have the URL /app/model/<int:pk/test/view. Is this the best way to do it: @admin.register(Property) class ModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() custom_urls = [ path('<int:pk>/view/', self.admin_site.admin_view(self.test_view)) ] return custom_urls + urls def test_view(self, request): record = Model.objects.get(pk=pk) # ... return django.http.HttpResponse('test') # P.S: I will rendering a template -
django I get a TemplateDoesNotExist when loading a page
My directories are structured in this picture I don't know why i'm getting the error. Please assist. Let me know if you need more info. Screenshot of the ERROR -
String mismatch on test in django model test
Been banging my head against a wall for two days trying to figure out why my test is not passing. I've wrapped them in str(). Multiline string. Just can't get this to pass. What am I missing here. Please help. This is my first post. So if I left anything out in my post that I could do better please let me know. Here is my model class MemberAddress(models.Model): address_type = models.CharField(max_length=100, default='Home') address_line_one = models.CharField(max_length=100) address_line_two = models.CharField(max_length=100, default=None) city = models.CharField(max_length=50) state = models.CharField(max_length=50) zipcode = models.CharField(max_length=50) UserProfile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) REQUIRED_FIELDS = ['address_type', 'address_line_one', 'city', 'state', 'zipcode' ] def __str__(self): address = self.address_line_one + '\n' if (self.address_line_two is not None): address += self.address_line_two + '\n' address += self.city + ' ' + self.state + ' ' + self.zipcode return address Here is my test: def test_member_address_is_created(self): faker = Faker('en_US') test_address = MemberAddress( address_type='Home', address_line_one=faker.street_address(), address_line_two=faker.secondary_address(), city=faker.city(), state=faker.state(), zipcode=faker.zipcode(), UserProfile=self.user ) test_address.save() queried_address = MemberAddress.objects.get(id=1) object_string_test = '{}{}{}{}{} {} {}'.format( test_address.address_line_one, '\n', test_address.address_line_two, '\n', test_address.city, test_address.state, test_address.zipcode) self.assertEqual(test_address.address_type, queried_address.address_type) self.assertEqual(test_address.address_line_one, queried_address.address_line_one) self.assertEqual(test_address.address_line_two, queried_address.address_line_two) self.assertEqual(test_address.city, queried_address.city) self.assertEqual(test_address.state, queried_address.state) self.assertEqual(test_address.state, queried_address.state) self.assertEqual(test_address.zipcode, queried_address.zipcode) self.assertEqual(test_address.UserProfile, queried_address.UserProfile) self.assertEqual(object_string_test, test_address) # <---- Failing Test ----<<< Here is my error: python manage.py test Creating … -
NOT NULL constraint failed: registratie_inkomen.pg_id
This are my models: class PersoonGegevens(models.Model): # Voornaam en achternaam voornaam = models.CharField(max_length=265,) achternaam = models.CharField(max_length=265) #username user = models.OneToOneField(User, on_delete=models.CASCADE) class inkomen(models.Model): pg = models.ForeignKey(PersoonGegevens, on_delete=models.CASCADE) inkomenfield = models.CharField(max_length=100) This is the form: class inkomenForm(forms.ModelForm): class Meta(): model = inkomen fields = ('inkomenfield',) This is my view: def tijdelijk(request): #User id user = request.user.id if request.method == 'POST': incoming = inkomenForm(data=request.POST) if incoming.is_valid(): incoming.save() return HttpResponse("saved") else: x = incoming.errors print (x) return HttpResponseRedirect('/tijdelijk') else: incoming = inkomenForm() return render(request, 'index/tijdelijkeindex.html', {'inkomen':incoming}) I have tried: incoming.save(commit=False) incoming.pg = user incoming.save also readed the documentation about Inline formsets of django. But i dont really get So i get the following error:(NOT NULL constraint failed) and i know it comes because i need to assign the pg.id and i know i can do that by adding the field in the form.py and let the user choose the id. But what i actually want is that pg = the logged in user. -
Django adding and removing form ManyToMany field: AttributeError: 'QuerySet' object has no attribute 'add'
I am trying to add users to a many to many fields in my course model buy I am getting an error: Course.course_dislikes.through.objects.filter(course__course_code=code,course__course_university=university).add(request.user) AttributeError: 'QuerySet' object has no attribute 'add' My intention is to filter my Course model based on course code and add a user to like a field or remove it when the user dislikes. Now I know I cannot use get since there may be two objects with the same course code. Currently, I am trying to do this by: Course.course_likes.through.objects.filter(course__course_code=code).remove(request.user) I have tried with get but it gaves me an error that two objects with the same name exist which is understandable since get has to return one unique object. How can I achieve this withot for-loop as I cannot think of anny other method. -
Stack Inline Multiple Django Models in Admin with indirect relationship
I have the following three models class Participant(models.Model): participant_id = models.AutoField(primary_key=True) pin = models.CharField(unique=True, max_length=4, validators=[RegexValidator(r'^\d{1,10}$')]) class Teacher(models.Model): teacher_id = models.AutoField(primary_key=True) participant_id = models.OneToOneField(Participant, on_delete=models.CASCADE) email = models.EmailField() compensation_id = models.OneToOneField(Compensation, on_delete=models.CASCADE) class Compensation(models.Model): compensation_id = models.AutoField(primary_key=True) wage = models.DecimalField(max_digits=6, decimal_places=2) To summarize, Participant has different types one of them is Teacher (OneToOne relation). The teacher is one type of employee that is compensated with and it's related (OneToOne relation) with Compensation Model I want to create an admin form by stacking Participant Teacher Compensation The problem: I am using Participant as a primary model and stacking teacher to it. However, when I try to stack compensation to it, it apparently doesn't work due to missing foreign key relation between Participant and Compensation models. An easy way out would be to have the fields of the Compensation model in the Teacher Model. However, it would create redundancy when I want to associate other types of Participants to it. What could potentially be a solution to this? I am open to altering the model if it makes thing any easier or less complicated. P.S. There are also other types of participants (Child, Parent) that I have not mentioned. -
Django 3.0 Forms: Form Errors are not showing onto template
###I have model named Publisher in models.py file.### ###And based on this model, a modelForm has made, called "RegistrationForm".### ###Which renders form on registration.html template.### <br /> <br />**This is code of registration.html** <pre><code> ``` <body> <div class="container"> {% load my_filters %} <div class="row"> <div class="col-md-6 offset-md-3"> {% if registered %} <h1>Thank you for registering!</h1> {% else %} <h1>Register Here</h1> <h3>Just fill out the form.</h3> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ reg_form.non_field_errors }} <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.name.errors }} <label for="{{ reg_form.name.id_for_label }}" >Name:</label> {{ reg_form.name|addclass:'form-control' }} </div> </div> <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.email.errors }} <label for="{{ reg_form.email.id_for_label }}">Email:</label> {{ reg_form.email|addclass:'form-control' }} </div> </div> <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.contact.errors }} <label for="{{ reg_form.contact.id_for_label }}">Contact:</label> {{ reg_form.contact|addclass:'form-control' }} </div> </div> <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.password.errors }} <label for="{{ reg_form.password.id_for_label }}">Password: </label> {{ reg_form.password|addclass:'form-control' }} </div> </div> <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.confirm_password.errors }} <label for="{{ reg_form.confirm_password.id_for_label }}">Confirm Password:</label> {{ reg_form.confirm_password|addclass:'form-control' }} </div> </div> <input type="submit" name="" value="Register"> </form> {% endif %} </div> </div> </div> </body> ``` </code></pre> ### I am NOT using crispy forms just manually rendering Django forms and using manual template tag to add classes to fields. **This is the template tag in used … -
How to add to the database outside of the admin site in django
I'm new to coding (6 months, self taught) and am currently working on an order and inventory management system using django. I have an order class setup in the database and am able to add orders using the django admin. My question is, how can I now create a separate html page with forums that will add orders to my database in the same way? I realize this is probably really general and basic, but I've yet to find the answer. Thanks tigerking -
django create confirm email for subscribe
I want to confirm e-mail for my subscribers. But I can not create confirm email. In views.py , I am sending e-mail but there is no confirm link. How can I create confirm link in this example ? models.py class Subscribe(models.Model): name = models.CharField(max_length=200,verbose_name="İsim") email = models.EmailField(max_length=200,verbose_name="E-Mail") confirmed = models.BooleanField(default=False) def __str__(self): return self.name + " - " + self.email views.py def yeniabone(request): if request.method == 'GET': form = SubscribeForm() else: form = SubscribeForm(request.POST) if form.is_valid(): request.session['form-submitted'] = True name = form.cleaned_data['name'] email = form.cleaned_data['email'] abone = Subscribe.objects.create(name=name,email=email) mymessage = "Merhaba "+name+",\nYazılarıma abone olduğun için teşekkürler. Aşağıdaki linkten aboneliğini onaylayıp yazılarımdan en hızlı şekilde haberdar olabilirsin.( I WANT TO SHOW CONFİRMATİON LİNK HERE )\n\nCemre ACAR - cemreacar.com" try: send_mail("Abone | cemreacar.com",mymessage,'Abonelik | Cemre ACAR <mail@cemreacar.com>',[email],'fail_silently=False') except BadHeaderError: return HttpResponse('Bir şeyler ters gitti!') return redirect('blog:yeniabone_onay') return render(request, "yeniabone.html", {'form': form}) -
{ % block content % } { % endblock % } is not working
This is main.html file: <!DOCTYPE html> <html> <head> <title>CRM</title> </head> <body> <h1>Navbar</h1> <hr> { % block content % } { % endblock % } <hr> <h1>Footer</h1> </body> </html> This is the contact.html { % extends 'accounts/main.html' % } { % block content %} <h2>contact!</h2> { % endblock % } this is my directory: accounts accounts accounts templates accounts contact.html main.html This is what I am getting: It displays the block tags too. -
How to build variable of integers + strings in python for loop?
Manually built variable STAFFLIST works in django database as a list of choices listed as PositiveSmallIntegers. STAFF1 = 1 STAFF2 = 2 STAFF3 = 3 STAFFLIST = ( (STAFF1, _('John Doe')), (STAFF2, _('Lisa Beauty')), (STAFF3, _('Harry Potter')), ) Print for this variable works as follows: >>>print(STAFFLIST[1]) (2, 'Lisa Beauty') >>> How to built this variable automatically in for loop based on the actual list of staffs? I was trying something like below, but unsuccsessful: from django.contrib.auth.models import User from django.utils.translation import gettext as _ staff = User.objects.filter(is_staff=True) idx=0 for stf in staff: STAFFLIST[idx] = (stf.id, _(stf.first_name + ' ' + stf.last_name)) idx=idx+1 I am getting error like: TypeError: 'str' object does not support item assignment I believe, my problem is low knowledge level of python datatypes. And currently, I am trying to work with tuple datatype and to store string inside. -
What is the best way to select single id from a loop using jquery in Django
I have a django template that loops through and displays all objects of a particular model. Each object displayed has a submit button. However, whenever I submit a form, the request always returns the id of the first object. html {% for food in food_list %} {{food}} <form action="{% url 'like'%}" id="form_id" method="post"> {%csrf_token%} <input name="food_id" type="hidden" value="{{ food.id }}"> <div class="like-button"></div> </form> {%endfor%} javascript <script> $('.like-button').on('click', function () { $(this).toggleClass('animate').promise().done(function () { document.getElementById("form_id").submit($(this)); }); }); </script> Please help, I am fairly new to jquery. -
Why is clang failing when building wheel for psycopg2?
I know this question or various forms of it has been asked. I am just trying to follow the Django tutorial on Heroku - which involves installing django-heroku, which has psycopg2 as a dependency. I am running MacOS Catalina, 10.15.3. I know one work around is to download the binary with pip install psycopg2-binary, but then I don't know how to get pip to recognize psycopg2-binary and stop trying to install psycopg2 from source when I run pip install django-heroku. So I suppose if someone could help me figure out that workaround, that would also suffice - although at this point I think I'm just gonna use Node. In any case, I feel like it's most likely just another instance of Catalina breaking things, but it would be nice to know how to fix this in case I ever have to use django-heroku/psycopg2. I have upgraded homebrew, reinstalled pyenv/python3.7.4, updated pip. I have openssl 1.1.1g installed (homebrew). I recently reinstalled XCode - but just to be sure it wasn't my compiler's fault, I installed homebrew clang using brew install llvm. Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status … -
django + chart.js : Cannot get two bar charts on the same graph with appropriate data
I am fairly new to javascript and I cannot get a bar chart to workout. Here is what is going on: DATA: {'supplier : "ARAGON", average_service_level_implied:-9.24, average_service_level_optimal: 0.495} view.py @method_decorator(login_required, name='dispatch') class SupplierPage(LoginRequiredMixin,APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_ress', None) context = {} if query and request.method == 'GET': Supplier = supplier.objects.filter(supplier = query) context.update({'Supplier': Supplier}) return render(request, 'Supplier.html',context) and chart.js graph <script> $(document).ready(function() { var endpoint = 'items.html' var forecastdata = [] var reference = [] ; $.ajax({ method: "GET", url: endpoint, success: function (data) { reference = data.reference forecastdata = data.forecastdata setChart() }, error: function (error_data) { console.log(error_data) } } ) function setChart() { var ctx = document.getElementById('myChart3').getContext('2d'); var myChart3 = new Chart(ctx3, { type: 'bar', data: { labels: ["actual service level", "optimal service level"], datasets: [{ label: 'Service level analytics', data: [ {% for dr in reference %}{{ dr.niveau_service_implicite}}, {% endfor %}, {% for dr in reference %}{{ dr.niveau_service_optimal}}, {% endfor %} ], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, … -
Django website uploads faster than video on the background
I am new to Django and I am trying to build a website for a friend. I manage to create a view page on my localhost with a video on the background. However, the video takes approx 2 seconds longer to show on the website. The video is hosted locally on my machine. Can you please advise? Here is the code I use to have a video on the background: <div class="fullscreen-video-wrap"> <video src="{% static "/Sequence01.mp4" %}" autoplay = True loop=True></video> </div> Thank you, -
How use Django to create a search bar on the home page, then redirect to search results?
I have a search bar on my jobs_board.html page which works well. But I want to add this search bar to my home page so it performs the same search and redirects to the jobs_board.html page to display the results. Any suggestions on how I can add this the home.html and it's view.py Thanks in advance. jobs/views.py def get_jobs_queryset(query=None): queryset = [] queries = query.split(" ") for q in queries: posts = JobsPost.objects.filter( Q(title__contains=q)| Q(body__icontains=q) ).distinct() for post in posts: queryset.append(post) def board_jobs_view(request): context = {} query = "" if request.GET: query = request.GET['q'] context['query'] = str(query) jobs_posts = sorted(get_jobs_queryset(query), key=attrgetter('date_updated'), reverse=True) context['jobs_posts'] = jobs_posts return render(request, "jobs/jobs_board.html", context) jobs_board.html <div class="container"> <div class="center"> <h1 class="display-4"> <form method="get"> <input class="form-control form-control-lg" type="text" name="q" id="id_q" placeholder="Search Jobs"> </h1> </div> </div> <script type="text/javascript"> document.getElementById("id_q").value = "{{query}}" </script> -
Good practices in creating a json with conditionals
I would like to improve the creation of this json, it has a conditional part but I don't think it is the best practice. I would appreciate examples with JS and Python example(list_contacts) { this.list_person= []; list_contacts.forEach(item => { let natural_person = item.natural_person; let _natural_person = { birth_day: natural_person.birth_day, dni: natural_person.dni, full_name: natural_person.full_name, dniPartner: '', full_name_partner: '', birth_day_partner: '', phone: natural_person.contact_details[0].concept, email: natural_person.contact_details[1].concept }; let partner = natural_person.partner; if (natural_person.partner != undefined) { _natural_person.dniPartner = partner.dni; _natural_person.full_name_partner = partner.full_name; _natural_person.birth_day_partner = partner.birth_day; } this.list_person.push(_natural_person); }); } -
django 3.0 inline admin form foreignkey -> foreignkey
I have any models and one Manager app/models.py class castratedListStudent(models.Manager): use_in_migrations = False def get_query_set(self): return super().get_query_set().filter(isOn=1) class student(models.Model): id = models.AutoField(primary_key=True) firstName = models.CharField(max_length=20) lastName = models.CharField(max_length=20) isOn = models.BooleanField() default_manager = castratedListStudent() objects = castratedListStudent() class discipline(models.Model): id = models.AutoField(primary_key=True) nameDiscipline = models.CharField(max_length=100, null=False) itemIdToDiscip = models.ForeignKey(item, on_delete=models.CASCADE, default=1) class listOfStudForDiscipline(models.Model): id = models.AutoField(primary_key=True) discipListId = models.ForeignKey(discipline, on_delete=models.CASCADE) studId = models.ForeignKey(student, on_delete=models.CASCADE) I am using django inline accounts/admin.py class discipStudentInline(admin.TabularInline): model = listOfStudForDiscipline admin.TabularInline.verbose_name = 'Student' extra = 0 def has_change_permission(self, request, obj=None): return False def get_queryset(self, request): return self.model.objects.filter(studId__isOn=1) class disciplineAdmin(admin.ModelAdmin): model = discipline inlines = [discipStudentInline] The Inline form is displayed on the HTML page and filter (studId__isOn=1) works. But the problem is that on the HTML page below there is a field that allows you to add another student and the list of students is not filtered by the filter rule(studId__isOn=1) When I check in the DEBUG_SQL console, I can see how the query goes without the WHERE expression "FROM journal_student". (0.000) SELECT `journal_listofstudfordiscipline`.`id`, `journal_listofstudfordiscipline`.`discipListId_id`, `journal_listofstudfordiscipline`.`studId_id` FROM `journal_listofstudfordiscipline` INNER JOIN `journal_student` ON (`journal_listofstudfordiscipline`.`studId_id` = `journal_student`.`id`) WHERE (`journal_student`.`isOn` = 1 AND journal_listofstudfordiscipline`.`discipListId_id` = 1) ORDER BY `journal_student`.`lastName` DESC; args=(True, 1) (0.000) SELECT `journal_student`.`id`,..., `journal_student`.`descriptionStudent` FROM journal_student` … -
Creating search functionality for profiles in my blog app based in Django
I want to extend my django blog app by creating a search form for User model based profiles. Currently any profile page is only accessed by the current logged in User with simple base url corresponding to the following urlpattern. urlpatterns = [ path('profile/', views_register.profile, name='profile'), ] I am fetching user search query from the following html template. <form method="GET" action="" id="searchform"> <input class="searchfield" id="searchbox" name="q" type="text" value="{{ request.GET.q }}" placeholder="Search..."/> </form> In my views.py, I have a function to receive this query but I don't know how to redirect the searching user to the corresponding user profile as the profile page for each user doesn't have any specific username based custom url. class ProfileSearch(LoginRequiredMixin): template_name = 'home.html' def get_queryset(self, request): query = request.GET.get('q') if query: return User.objects.filter(username__icontains=query) else: return User.objects.all() How do I redirect the query initiator to this new profile page? I know this function does nothing as it doesn't do any dynamic redirects but I am clueless. Following is the profile model and is auto created through signals when a new user registers. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default= 'default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = … -
How does Django decrypt EncryptedCharField fields?
So I've got a field in my Postgres database that is a bytea type. I know the decrypted value and also the key, but can't figure out how to get from that raw database value to the decrypted string. I believe I'm looking for the algorithm that Django uses to decrypt these values and how I can use that to encrypt another string. Django supposedly uses the package Keyczar, which mentions using Crypter package to encrypt/decrypt things. I'm unable to install that package so I'm not sure how to go about this in another way. I ultimately want to update a value in the EncryptedCharField field in my database since it is not valid anymore - is there a way to get this encrypted value online or within Python?