Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get TypeError: the JSON object must be str, bytes or bytearray, not dict
I'm saving a dict into a JSONfield field in my model. This is going ok, but when I want to retrieve data by id, the next error message appears: ***TypeError: the JSON object must be str, bytes or bytearray, not dict This is an example of what I'm doing: data = {"123": {"dummy": false, "dummy2": 123}}} data is saved succesfully with object.save() into the model. I can see that in the database. When I try to retrieve a registry by id with: try: my_record = models.MyModel.objects.get(business_id=my_id) except models.MyModel.DoesNotExist: logger.debug(f"Record does not exists {my_id}") continue This is the full Traceback: my_record = models.MyModel.objects.get(business_id=my_id) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/query.py", line 425, in get num = len(clone) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/query.py", line 269, in __len__ self._fetch_all() File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/query.py", line 70, in __iter__ for row in compiler.results_iter(results): File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1100, in apply_converters value = converter(value, expression, connection) File "/home/esufan/repos/verdata-service/venv/lib/python3.8/site-packages/django/db/models/fields/json.py", line 74, in from_db_value return json.loads(value, cls=self.decoder) File "/usr/lib/python3.8/json/__init__.py", line 341, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not dict I know the issue … -
How do I print " this character in python [duplicate]
Pardon me if this is not a big deal. I came across a program which needed to print " this character and whenever I use this character it closes the string. How can I print this " -
Database design required for a requirement of tree structure [closed]
Database design required for a requirement of tree structure: Tree structure with node Green ones in the image are kind of folder structure and blue ones are links -
Django form not showing when request.method is changed from GET to POST
I am creating a form but when I change request.method == 'GET' to request.method == 'POST', my form does not open when I enter its link. Also when I use 'GET', the form data does not get saved. Please help me solve this problem. Here are the relevant files: models.py from django.db import models # Create your models here. class GrpDetails(models.Model): year = models.IntegerField(default='') branch = models.CharField(max_length=30) group = models.IntegerField(default='') session = models.DateTimeField() sem = models.IntegerField(default='') subject = models.CharField(max_length=50) stu_list = models.FileField(upload_to='documents/') views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import User, auth from django.contrib import messages import csv from django.contrib.auth.decorators import login_required from .forms import GrpDetailsForm from .models import GrpDetails # Create your views here. def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('dashboard') else: messages.info(request, 'Username or password are invalid!') return redirect('login') else: return render(request, 'login.html') def logout(request): auth.logout(request) return redirect('login') @login_required(login_url='login') def dashboard(request): return render(request, 'dashboard.html') @login_required(login_url='login') def add_class(request, id=0): if request.method == 'GET': if id == 0: form = GrpDetailsForm() else: info = GrpDetails.objects.get(pk=id) form = GrpDetailsForm(instance=info) return render(request, 'newform.html', {'form': form}) else: if id == 0: form = … -
Django Dependent/Chained Dropdown List for more than 2 field
I have implemented a Dependent / Chained Dropdown List (as can be seen in the following code). Now, however, I would need to add a field; so far I have: the provinces, cities (which appear based on the selected province) and offices (which appear based on the selected city). Do you have any advice on how to do it? <script> $( document ).ready(function() { var $a = $("#provddl"); $b= $("#comddl"); $options = $b.find('option'); $a.on('change',function() { $b.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); }); </script> <div> <labe>Provincia: </label> <select id="provddl"> <option> --- selezionare province--- </option> {% for a in A %} <option value="{{ a.province_id }}"> {{ a.province_name }} </option> {% endfor %} </select> </div> <div> <label>Comune: </label> <select id="comddl"> <option> --- select city--- </option> {% for b in B %} <option value="{{ b.province_id }}"> {{ b.city_name }} </option> {% endfor %} </select> </div> -
The Function is being called before the button click. What should i do? [closed]
html code: <div class="container"> <h1>Add An Employee</h1> <hr> <form action="/add_emp" method="post"> {% csrf_token %} <label for="first_name">First Name</label><br> <input type="text"id="first_name" name="first_name" value="{{ first_name }}"><br> <label for="last_name">Last Name</label><br> <input type="text"id="last_name" name="last_name" value="{{ last_name }}"><br> <label for="department">Department</label><br> <input type="text"id="department" name="department" value="{{ department }}"><br> <label for="Salary">Salary</label><br> <input type="text"id="Salary" name="Salary" value="{{ salary }}"><br> <label for="role">Role</label><br> <input type="text"id="role" name="role"value="{{ bonus }}"><br> <label for="bonus">Bonus</label><br> <input type="text"id="bonus" name="bonus" value="{{ role }}"><br> <label for="phone">Phone Number</label><br> <input type="text"id="phone" name="phone" value="{{ phone }}"><br> <hr> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> --> It is calling a views.py function before i click the submit button. If you need the python code as well tell me i will add it. I need help resolving this. All help appreciated. -
Can you horizontally access other fields via "related_name" in Django?
I have a theoric question that I have to solve in order to provide a solution. I am reading a piece of code, but something doesn't make sense to me in how it is accessing the fields through a reverse lookup with "related_name". I share with you the important parts of the code to explain myself. I was looking for more information related to this, and strengthened my knowledge about "related_name" but didn't find something that helped me. class Account(models.Model): country = models.ForeignKey( 'Country', on_delete=models.PROTECT, null=True, blank=True ) class Stage(models.Model): step_name = models.CharField(max_length=100) n_step = models.PositiveIntegerField(null=True, blank=True) class Status(models.Model): TIPOS_STATUS = { ('open', 'open'), ('open_staged', 'open_staged'), ('closed_won', 'closed_won'), ('closed_lost', 'closed_lost') } name = models.CharField(choices=TIPOS_STATUS, max_length=50) class AssignedAccount(models.Model): account = models.ForeignKey( Account, on_delete=models.CASCADE, null=True, blank=True, related_name='assignation', ) status = models.ForeignKey(Status, on_delete=models.PROTECT) stage = models.ForeignKey( Stage, null=True, blank=True, on_delete=models.PROTECT, ) The thing is that I know that I can do something like the following with related_name and do a reverse lookup to see all the assigned accounts toward an account: account = Account.objects.get(pk=1) assigned_accounts = account.assignation.all() But now see what they do with the FK between these two in this DF: accounts = Account.objects.all() accounts_dataframe = pd.DataFrame( list( accounts.values( 'pk', 'country__two_letter_code', 'assignation__stage__n_step', … -
Replacing values for multiple different elements each time I poll the server - htmx
I'm trying to poll the server once every 5 seconds and update 3 different values on the page, all in different locations. I've watched a few tutorials on htmx and oob swaps and I think I'm close to the solution but I just can't get it. The results are coming through fine from the backend, they're just all going into the div with the id="udp", where I trigger the server poll from. I think this is what's causing me the problem but I'm not sure whether I need to move the hx-trigger to ensure id="ujp" and id="uep" both get updated or if I've missed something else? result.html: <div> <div class="card-body" style="margin: 0 auto"> <div id="udp" hx-get="{% url 'result' %}" hx-trigger="every 5s" hx-swap-oob="true" style="text-align: center;"> {% include 'partials/updated_results.html' %} </div> </div> </div> <div class="card"> <div class="card-body" style="margin: 0 auto"> <div id="uep" hx-swap-oob="true" style="text-align: center;"> {% include 'partials/updated_results.html' %} </div> </div> </div> <div class="card"> <div class="card-body" style="margin: 0 auto"> <div id="ujp" hx-swap-oob="true" style="text-align: center;"> {% include 'partials/updated_results.html' %} </div> </div> </div> updated_prices.html: <div id="udp" hx-target="#udp" hx-swap="outerHTML"> {% if add_result1 %} <p>{{ add_result1.result }}</p> {% else %} <p>Retrieving results...</p> {% endif %} </div> <div id="uep" hx-target="#uep" hx-swap="outerHTML"> {% if add_result2 %} <p>{{ add_result2.result … -
Pros/Cons of hosting website on apache vm
I recently have begun hosting my own website on an Apache Linux VM, through the Google Cloud compute engine. This project primarily used Django for backend & API call handling, while using React as the primary frontend engine. Initially hosting the site was difficult for, but once it was running, it was fast, easy to tie to a domain, and performed all functionality as required. My main question was, in this sort of web-application scenario, what would be some alternatives for hosting a site like this? Is this a computationally efficient way of hosting a site? Is it an expensive method when compared to alternatives? How well would this scale with the number of users? -
Django Form Search Bar with multiple chocie
I have a ManyToMany relationship and i want the following : 1) to make for the ManyToMany field, from the form, a search bar. 2) to display all the searched items as check boxes 3) then check ( if wanted) and submit them How should i approach this ? Thanks ! -
is it unconventional to prefix a django app with _
prefixing Django apps with _ does seem to work but is it unconventional? Will it give problems? exemple: _login _dashboard _proxy core locale static templates -
User object has no attribute
I am creating an app in which it manages ranking and ELO functions for a local hobby game store. I am using django to write the application. I am having troubles trying to figure out how to access a user's model from their name. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mtg_currentELO = models.IntegerField(default=1000) mtg_highestELO = models.IntegerField(default=1000) mtg_lowestELO = models.IntegerField(default=1000) def __str__(self): return self.user.username views.py def home(request): users = User.objects.all() if request.method == 'GET': user1 = User.objects.get(username=request.POST['player1']) user2 = User.objects.get(username=request.POST['player2']) print(user1, user2) # DEBUG LINE -- it does find print(user1.mtg_currentELO) # DEBUG LINE -- it does NOT FIND So what I'm trying to accomplish is the find mtg_currentELO from the user1. However, I can't access it via user1.mtg_currentELO. How can I access the property mtg_currentELO of a Profile, via the user's name? -
how to reveal info of selected element?
Is there any way to show info of the object under tag? I somehow need to reveal under this tag adress of selected object: class VideoLibrary(models.Model): shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') HTML code: {% if shop_name %} <select name="shops" id="shop_select" class='box'> <option value="" disabled selected id='blank_option' onchange='revealMore()' name='select_option'></option> {% for library in shop_name %} <option id='library_element'>{{library.shop_name}}</option> {% endfor %} </select> {% else %} <p>ERROR</p> {% endif %} <script src={% static 'js/show_more.js' %}></script> JS: function revealMore() { var blank_text = document.getElementById('blank_option'); if (this.value !== blank_text) { var library = this.value; alert(library); } } document.getElementById('shop_select').addEventListener('change', revealMore); -
What should i implement on my model regarding data security?
I only have this to define the limit of data on my model. class Direcao_ST(models.Model): direcao= models.CharField("Direção", max_length=7) slugD = models.SlugField(null=False, default="") def clean(self): if (Direcao_ST.objects.count() >= 20 and self.pk is None): raise ValidationError("Can only create 20 Direcao instances. Try editing/removing one of the existing instances.") I would like to know which are the most essential things that I should implement on my Model regarding security. And is there any "defaults" measures of security that every Developer should implement in their Models? -
Django forms.Form reflecting property field constraints
I'm implementing a Django Form witch should contain the field 'fieldA' from modelA: class ModelA(models.Model): fieldA = models.CharField(max_length=8) ... My question is: Is there a way to have Django form, which will automatically handle validation of fieldA (check the max_length)? I know I Could use form.ModelFormclass referring to ModelA, but then the form would reflect all the fields of the ModelA. I would like to use simple forms.Form. I'm looking for a solution like: class formX(forms.Form): fieldA = forms.CharField(**modelA.fieldA.constraints) fieldB = ... some other fields not related to ModelA ... .... even more fields -
Django Rest Framework for Calculations
I'm starting to develop in django/django rest framework and I needed to make a kind of calculator, send a and b, python would take these values, process, for example, do the sum and return in a json, but I only find examples with database data, would it be possible to do this? -
Django Middleware Login check
I want to restrict all pages for unauthenticated users. I wrote the following middleware: from django.shortcuts import redirect def require_login(get_response): def middleware(request): if request.user.is_authenticated: response = get_response(request) return response return redirect('/login/') return middleware The issue is that it also redirects to my Login page when it redirects to Login page (hope you got it). So it continuously redirects to my login page. What do I need to do about it? Is it okay to check if the requested page is Login page then don't check the if statement above. Thanks! -
django-tailwind problem on python manage.py tailwind start
I have an issue with tailwind that did not happen before and I can't really think of any change I would have done. Anyone encountered that? Can't really find a fix to it. Thanks for your help Traceback (most recent call last): File "manage.py", line 9, in execute_from_command_line(sys.argv) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\user\Desktop\Projets\afufmedia1\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\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\management\commands\tailwind.py", line 55, in handle return self.handle_labels(*labels, **options) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\management\commands\tailwind.py", line 63, in handle_labels getattr(self, "handle_" + labels[0].replace("-", "_") + "_command")( File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\management\commands\tailwind.py", line 103, in handle_start_command self.npm_command("run", "start") File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\management\commands\tailwind.py", line 113, in npm_command self.npm.command(*args) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\npm.py", line 23, in command subprocess.run([self.npm_bin_path] + list(args), cwd=self.cwd) File "c:\program files\miniconda\lib\subprocess.py", line 489, in run with Popen(*popenargs, **kwargs) as process: File "c:\program files\miniconda\lib\subprocess.py", line 854, in init self._execute_child(args, executable, preexec_fn, close_fds, File "c:\program files\miniconda\lib\subprocess.py", line 1247, in _execute_child args = list2cmdline(args) File "c:\program files\miniconda\lib\subprocess.py", line 549, in list2cmdline for arg in map(os.fsdecode, seq): File "c:\program files\miniconda\lib\os.py", line 818, in fsdecode filename = fspath(filename) # Does type-checking of filename. TypeError: expected str, bytes or os.PathLike object, not NoneType -
How to Reassign value to variable in Django template through filters
I have an xml object that I am looping to print in template. It is detailing of items with their tax rate. so after printing all items I need sum of those tax rate values. I am trying to sum up that value in template. I have created filter named updatevariable, it is working and doing sum up but issue is due to loose of old sum it just returns latest value rather than whole sum up. SO I need a way to reassign TotalTax with sum up value from filter. this is example of output needed: Tax-1 16 Tax-2 18 Tax-3 2 TotalTax = 36 {% with TotalTax=0 %} {% if taxRateDetailing %} {% for item in taxRateDetailing%} <tr> <td> {{item.1.text}} </td> <td> {{item.4.text}} {{TotalTax|updatevariable:item.4.text}} </td> </tr> {% endfor %} <tr> <td> Total Tax </td> <td> {{TotalTax}} </td> </tr> {% else %} <tr> <td> Tax </td> <td> {{defaultSalesTaxRate}} </td> </tr> {% endif %} {% endwith %} Filter function def updatevariable(value, arg): TotalTax = value + float(arg) return TotalTax -
why my URL's path work when I delete name?
hi guys my second app path works when I delete 'notes' in the path why? urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('notes/', include('notes.urls')) ] urlpatterns= [ path('',views.list, name="notes"), ] def list(request): all_notes = Note.objects.all() return render(request, "notes/notes.html" , {'notes' : all_notes} ) -
How do I display a Django form correctly using ListView
I am writing a simple app to track sales leads based on the Django tutorial "Writing your first Django app" (https://docs.djangoproject.com/en/4.0/intro/tutorial01/). Everything works well except for displaying a ListView of the existing leads. Here are the relevant python snippets: # leads/models.py class Leads(models.Model): id = models.IntegerField(primary_key=True) last = models.CharField(max_length=32) first = models.CharField(max_length=32) # config/urls.py urlpatterns = [ # Django admin path('admin/', admin.site.urls), # User management path('accounts/', include('allauth.urls')), # Local apps path('leads/', include('leads.urls')) # leads/urls.py app_name = 'leads' urlpatterns = [ path('', LeadsListView.as_view(), name='list'), path('<int:pk>/', LeadsDetailView.as_view(), name='detail'), ] # leads/views.py class LeadsListView(ListView): model = Leads template_name = 'leads/list.html' context_object_name = 'leads_list' def get_queryset(self): return Leads.objects.order_by('id') class LeadsDetailView(DetailView): model = Leads template_name = 'leads/detail.html' The link in the 'home.html' template, which displays a menu option correctly: <a href="{% url 'leads:list' %}">Leads</a> And finally, the 'list.html' template that does not display at all. Instead of showing the list of leads, it remains on the home page. {% block content %} {% for lead in lead_list %} <div class="lead-entry"> <h2><a href="{% url 'leads:detail' lead.pk %}">{{ lead.fname }} {{ lead.lname }}</a></h2> </div> {% endfor %} {% endblock content %} I'm missing something fundamental here.... -
Convert the Image to base64 and upload the base64 file in S3 and get the same file using django
I need to get a image from django imagefield and convert it to base64 file and upload that converted file in private s3 bucket. And while I getting the image from the s3 bucket I need to get that base64 file and send it to the forntend(reactjs). Basically I need to convert the image to base64 file, I checked on the internet and Iam not sure where to use that code correctly. Can anyone please suggest me to do that or is any clear documentation available to use as step by step. Here is my model, views and seriailizers class Organisation(models.Model): """ Organisation model """ org_id = models.AutoField(unique=True, primary_key=True) org_name = models.CharField(max_length=100) org_code = models.CharField(max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def remove_on_image_update(self): try: # is the object in the database yet? obj = Organisation.objects.get(org_id=self.org_id) except Organisation.DoesNotExist: # object is not in db, nothing to worry about return # is the save due to an update of the actual image file? if obj.org_logo and self.org_logo and obj.org_logo != self.org_logo: # delete the old image file from the storage in favor of … -
Django, runserver exits with -1073741819 (0xC0000005) code
I have downloaded Django project in my Windows PC, that has a large amounts of libs and modules. When I try to run runserver command, it returns to me this: Process finished with exit code -1073741819 (0xC0000005) Every other manage.py commands just crashes silently without any warnings and messages. I know that this code means buffer overload. How it is possible to increase buffer or fix this? -
What should I return at post function in DetailView Class
I have Message model and Post model. I can successfully save message on data base, however I got an error at PostDetailView,views.py 'super' object has no attribute 'post' How can I fix this? All my code views.py class PostDetailView(DetailView): model = Post def post(self, request, *args, **kwargs): message = Message.objects.create( user=request.user, post_id=self.kwargs.get('pk'), body=request.POST.get('body') ) message.save() return super(PostDetailView,self).post(request, *args, **kwargs) -
Is there any way to run python manage.py runworkers & python manage.py runserver simultaneously in apache server?
While deploying django project in Apache server facing an error : I need to run python manage.py runworkers and python manage.py runserver simultaneously. It is working fine while running local/django server. But have complications in production time.