Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I use the ManyToManyField attribute in a class in MinValueValidator?
I have two models. One has a price attribute and I would like to use it to set a minimum value in lastbid. I don't really understand how to do this. class Auctionmodel(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) title = models.CharField(max_length=300) content = models.TextField() price = models.IntegerField() pic = models.CharField(max_length=300, blank=True) category = models.ManyToManyField(Category, related_name='auctioncategory') class Bids(models.Model): whosebid = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) bidauction = models.ManyToManyField(Auctionmodel, blank=True, related_name="bbidauction") currentprice = bidauction.price lastbid = models.IntegerField(validators=[MinValueValidator(currentprice)]) -
how to write a Django rest framework custom authentication
I need a third party package for Django rest framework authentication that in the first login, give API-KEY from user and generate access token and refresh token for he. it is like the Json Web Token but the difference is I want to give API-KEY not user password. please help me thanks a lot -
How to have urls in an svg in django
I want to have an svg image that is in memory to have urls embedded in it, that when the user clicks they go to another page. I am able to create the image: import matplotlib.pyplot as plt from io import BytesIO sns_plot = plt.scatter([1, 2, 3], [4, 5, 6]) sns_plot.set_urls(['https://www.bbc.co.uk/news', 'https://www.google.com/', None]) fig = sns_plot.get_figure() img_in_memory = BytesIO() fig.savefig(img_in_memory, format="svg") image = base64.b64encode(img_in_memory.getvalue()) image = image.decode(settings.DEFAULT_CHARSET) sns_plot.get_figure().clf() and display it in the template: <img src="data:image/svg+xml;base64,{{image}}" class="img-fluid mx-auto d-block"/> If I right click and save the image the links are clickable but when the image is displayed in the browser they are not? -
Django django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
So I'm trying to integrate a model with mongoDB usng djongo driver, and when I tried to insert a record from within models.py it is giving me this error. AppRegistryNotReady("Models aren't loaded yet.") here are my code files. models.py from djongo import models class Iname(models.Model): item_name = models.TextField() class Meta: abstract = True class Iquantity(models.Model): item_quantity = models.TextField() class Meta: abstract = True class Iprice(models.Model): item_price = models.TextField() class Meta: abstract = True class Order(models.Model): email = models.EmailField(primary_key = True, name = "email") name = models.CharField(max_length=30, help_text="Enter Customer Name", name = "name") address = models.TextField(help_text="Enter customer's Address", name = "address") item_names = models.ArrayField(model_container = Iname) item_quantities = models.ArrayField(model_container = Iquantity) item_prices = models.ArrayField(model_container = Iprice) objects = models.DjongoManager() o = Order() o.email = "jayesh@gmail.com" o.name = "dhsdb" o.address = "agdkhdvf" o.item_names = ['chocolate', 'pencil'] o.item_quantities = [5, 10] o.item_prices = [10, 3] o.save() serializers.py from .models import Order, Iname, Iprice, Iquantity from rest_framework import serializers class ItemSerializer(serializers.ModelSerializer): class Meta: model = Iname class QuantitySerializer(serializers.ModelSerializer): class Meta: model = Iquantity class PriceSerializer(serializers.ModelSerializer): class Meta: model = Iprice class OrderSerializer(serializers.ModelSerializer): item_names = ItemSerializer() item_quantities = QuantitySerializer() item_prices = PriceSerializer() class Meta: model = Order fields = "__all__" views.py from rest_framework.decorators import api_view … -
Django SlugRelatedField with multiple keys which are unique
I have a model like the followings. class Tree(AuditedModel): id = models.AutoField(primary_key=True) genre = models.ForeignKey('Genre', on_delete=models.CASCADE) specie = models.ForeignKey('Specie', on_delete=models.CASCADE) name = models.CharField(max_length=63) class Meta: get_latest_by = 'created' unique_together = (('genre', 'specie'),) ordering = ['-created'] I do have a separate serializer for the above model and, Then I do have another model ,serializer (for another model), which serializes it as follows. class TreeSubplant(AuditedModel): id = models.AutoField(primary_key=True) tree = models.ForeignKey('Tree', on_delete=models.CASCADE) name = models.CharField(max_length=63) class TreeSubplantSerializer(serializers.ModelSerializer): tree = models.SlugRelatedField('id', queryset=Tree.objects.all()) name = models.CharField(max_length=63) class Meta: model = TreeSubplant But my question is, as tree's genre and specie would be the directly used parameters with the client, is there a way that we can make use to use interact with the backend in this scenario. -
OSError: [Errno 99] Cannot assign requested address when testing the sendtestemail of kiwi tcms
I am encountering this error below when running the command "docker exec -it kiwi_web /Kiwi/manage.py sendtestemail user1@example1.tld": OSError: [Errno 99] Cannot assign requested address I can't find other logs pertaining to this error. The full error log: File "/Kiwi/manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/venv/lib64/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/venv/lib64/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/venv/lib64/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/venv/lib64/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/venv/lib64/python3.8/site-packages/django/core/management/commands/sendtestemail.py", line 35, in handle send_mail( File "/venv/lib64/python3.8/site-packages/django/core/mail/__init__.py", line 87, in send_mail return mail.send() File "/venv/lib64/python3.8/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/venv/lib64/python3.8/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/venv/lib64/python3.8/site-packages/django/core/mail/backends/smtp.py", line 80, in open self.connection = self.connection_class( File "/usr/lib64/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib64/python3.8/smtplib.py", line 337, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib64/python3.8/smtplib.py", line 308, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib64/python3.8/socket.py", line 808, in create_connection raise err File "/usr/lib64/python3.8/socket.py", line 796, in create_connection sock.connect(sa) OSError: [Errno 99] Cannot assign requested address -
Slice queryset after order_by() in Django
I have order_by() model django and got queryset following result: queryset = <QuerySet [<MyModel: MyModel object (4)>, <MyModel: MyModel object (2)>, <MyModel: MyModel object (1)>, <MyModel: MyModel object (3)>, <MyModel: MyModel object (5)>]> The result is not sorted by id. And I want slice queryset that have order MyModel with id greater than 1 to get the following results: new_queryset = <QuerySet [<MyModel: MyModel object (4)>, <MyModel: MyModel object (2)>]> Is there any way to slice without loop like this to reduce the query ? for index in range(len(queryset)): if queryset[index].id == 1: new_queryset = queryset[:index] break Thank You in Advance. -
I am getting the error Error code: Unhandled Exception on python anywhere
I am trying to deploy my blog app using python anywhere. After I did all the steps and I clicked only my link I got the error Error code: Unhandled Exception. I do not know what is causing my issue any help would be appreciated. # +++++++++++ DJANGO +++++++++++ # To use your own django app use code like this: import os import sys # ## assuming your django settings file is at '/home/codewizblog/mysite/mysite/settings.py' ## and your manage.py is is at '/home/codewizblog/mysite/manage.py' path = '/home/codewizblog/codewizblog/code-wiz-blog' if path not in sys.path: sys.path.append(path) os.chdir(path) os.environ.setdefualt("DJANGO_SETTINGS_MODULE", "blog.settings") import django django.setup() #os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Determining Whether the User Entered In A City Or A Country In Folium
I am trying to design a program where the user will enter in the name of a country, city, or small town and then have the marker on a world map accurately show the location as well as the name of that country, city, or small town. Any ideas on the approach I can take to accomplish this? The following is the current Python source code I have at the moment: def DisplayMap(request): if request.method == 'POST': mapForm = MapDataForm(request.POST) if mapForm.is_valid(): mapForm.save() # return redirect('/') will redirect the user back to # 127.0.0.1:8000/ which is the homepage of the application. # Instead the user must be redirected back to the page that # is loaded with the 'display-map' url path name. return redirect('display-map') else: mapForm = MapDataForm() # For the following line to work, we must have at least one 'MapDatabase' object. address = MapDatabase.objects.all().last() location = geocoder.osm(address) latitude = location.lat longitude = location.lng country = location.country city = location.city if latitude == None or longitude == None: address.delete() return HttpResponse('Your search input was invalid.') # Here the map object is being created. # The following line of code will center the map and zoom in at # an … -
Django form not rendering? (No Model)
So my Django form is not rendering in the html. all I'm able to see is the Get Rank text. I'm not sure if it's because I don't have a model or maybe it's something wrong with my html? If you need to see anything else let me know not sure what's wrong, I also tried just doing it all inside of the home function but then it doesn't render the html at all. Side question - Also I only plan on grabbing the users name, and the tag outside their name ("JohnDoeNA#1") so I probably use a get method correct? views.py: from urllib import response from django.shortcuts import render from django.http import HttpResponse import requests from .forms import SearchUser import json # Create your views here. def index(response): return render(response, "main/base.html", {}) def home(response): form = SearchUser() data = requests.get( 'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-APIKEY') userid = data.json()['puuid'] return render(response, "main/home.html", { 'userid': userid, # 'mmr': apidata['rank'] }) def search(response): form = SearchUser() return render(response, "main/home.html", {"form": form},) forms.py: from django import forms class SearchUser(forms.Form): name = forms.CharField(label="Name", max_length=200) home.html: {% extends 'main/base.html'%} {% block content %} <h2>Valorant Ranked Checker</h2> <form method="post" action="/home/"> {{form}} <buttom type="submit", name="search"> Get rank </buttom> </form> <p><strong>{{userid}} - … -
Extending multiple templates in django
I know a similar question might have been asked here a couple of times before, but I am still not able to find a solution to my problem with the answers provided. So I lets say I have four templates. Base1.html, template2.html, and template3.html and template4.html. template2. template3 and template4 all extend base1. Lets assume they are different sections of the homepage. How do I merge all the contents of each of these different templates into one template? I have tried extending template2 using base1 as the base template, and then extending template3 using template 2 as the new base template but the problem is I lose all the data associated to the new base template whenever I get to the second template extension. Is there an easy way to do this? -
Axios seemingly randomly adding an appending slash to the URL of some requests
I have a react app frontend, django backend (now making urls without an append slash). It seems that axios is adding an appending slash to the url of requests and I'm not sure why. my custom axios function: const authAxios = axios.create({ baseURL: process.env.REACT_APP_API_URL, // "http://localhost" headers: { 'Authorization': token, }, }); example request that works: const url = '/books' try { const res = await authAxios.get(url); } catch (err) { console.log({err}); } // Backend url hit: "http://localhost/leads" example request that doesn't work: const url = '/books' const query = `?page=1&page_size=2` try { const res = await authAxios.get(url + query); } catch (err) { console.log({err}); } // Backend url hit: "http://localhost/books/?page=1&page_size=2" <-- fails 404 because of / after books This doesn't only happen when query params are added. I have other urls that are failing like: "/authors" ---> hitting the backend as "/authors/" "/verticals" ---> hitting the backend as "/verticals/" I am guessing the url modification is happening in axios because there is no redirect 301 message on the backend server it just shows a request made to '/verticals/' then 404s, though maybe I'm wrong. All that shows on the backend regarding the request: The axios response error looks like … -
How to develope An ofline. mobile application using django
I am learning mobile app developement with flutter. And I want to use an offline backend technology to write my logics. But all the stuff that goes well with flutter as a backend like 'firebase' or anything else, they do not support offline. So I was thinking that as I know django if there is any way to use it as an offline backend then I can use it in my applications. So is there any way to use django or any other python framework for offline backend? -
Where does the fcgi.py file go in the 'Django on Bluehost' WSGI solution?
In the post [1]How to deploy Django app on Bluehost using WSGI? it mentions the .htaccess, django.fcgi, and fcgi.py files. Where is the fcgi.py file to be located? Does it go in the django project or app folder, or in the public_html folder? The latter would seem like a security issue, but as I'm having trouble getting any solution to work for Django on Bluehost (and am running out of patience) I thought I'd dig a little deeper. -
ModuleNotFoundError: No module named 'openpyxl' when i deploy my django app on heroku
In my django application I use the openpyxl module to work with excel files. It works perfectly locally but when I deploy on heroku it doesn't work. I have this error: import openpyxl ModuleNotFoundError: No module named 'openpyxl' My python version 3.8 What can I do to solve this problem? Thanks in advance. -
Download multiple pdfs in Django View using xhtml2pdf
I can successfully download a single pdf using xhtml2pdf in a Django View. I am trying to leverage the same tools to download multiple pdfs. The problem is that the last line of the function - return response - kills the for loop and will not iterate back through the code. Any thoughts? Here is my View: def report_cover_page_collated_pdf(request, *args, **kwargs): students = ['65002582', '65005968'] student_list = Student.objects.filter(id__in=students).order_by('student_name') for item, student in enumerate(student_list): context = {'student': student, 'item': item} pdf = render_to_pdf('learning_logs/pdfs/report_cover_page_collated_pdf.html', context) response = HttpResponse(pdf, content_type='application/pdf') filename = "_Binder.pdf" filename = students[item] + filename content = "attachment; filename=%s" % filename response['Content-Disposition'] = content return response Binder for first student is downloaded and the for loop stops. -
loop.subprocess_shell => how write and read from diferent method asyncio django channels
I'm trying to implement a ssh client with django & django-channels. When a websocket request is comming the connect method creates a subprocess and a new "terminal" is started. Then when the next message arrives from client, the receive method handle the request and here is my problem... I don't know how to send the message to the shell subprocess created on "connect" method Help would be appreciated. PS: I made the same solution with pty.fork & select.select and it works but my guess is that is not really scalable since we need many terminals running concurrently. class ShellConsumerAsync(AsyncWebsocketConsumer): async def connect(self): ... self.accept() ... sub_process = await create_subprocess_shell(command, stdin=async_subprocess.PIPE, stdout=async_subprocess.PIPE, stderr=async_subprocess.PIPE) ... async def receive(self, message): ... # Write to sub_process created here => (self.connect) # check read availability on sub_process # something like select.select or asyncio.add_reader # message = await asyncio.wait_for(sub_process.stdout.read), timeout=15) ... # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'channel_gr_message', 'message': message } ) -
Django Command: Load Data Mysql
Writing a django command that imports from a directory of txt files into a database. The database is created, however when run I get the lovely, indescript error django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '...path' at line 1"). I have no clue to what to investigate. When I try a singular file into the mysql portal, it seems to work. How can I make the jump to a Django command? Below is the command code: def handle(self, *args, **options): self.stdout.write("\nStarting...") with connections['wk'].cursor() as cursor: db_name = settings.DATABASES['wk']['NAME'] for path in glob.glob(f'{options["p"]}/*[!.sql]'): table_name = f'{db_name}.{path.rsplit("/")[-1].lower()}' cursor.execute("LOAD DATA INFILE '%s' INTO TABLE %s", [path, table_name]) -
This site can't be reached - Django
After I created a virtual enviroment and the necessary files, I ran, python manage.py runserver and there was an error. This is what the terminal gave me: C:\Users\****\AppData\Local\Microsoft\WindowsApps\python.exe: can't open file: 'C:\\Users\\****\\Desktop\\pydjango\\django-project\\manage.py': [Errno 2] No such file or directory -
Django: Import from project root
I was searching for an answer but could not get the solution for this exact case: So, my project structure is like this project/ myproject/ ... app/ ... views.py ... logic/ do_stuff.py db.sqlite3 manage.py And this do_stuff.py contains a function call_me() How can I call call_me() function from views.py (For example, upon a successful file upload)? Many thanks! -
modal form is not saving data with jquery
so my issue is I have this modal that contains this form, I am able to call the form with jquery and also pass the required data for the specific item in my table that I am trying to edit but when I click save/submit nothing happens and the updated information isn't saved and modal just stays there. so any help is appreciated Jquery $('#office-expense tbody').on('click', '.edit-btn', function (e) { e.preventDefault(); var $this = $(this); let item = $this.parents(".record").find('td').eq(1).text(); let amount = $this.data('amount'); let date = $this.data('date'); let method = $this.parents(".record").find('td').eq(4).text(); let trustee = $this.parents(".record").find('td').eq(5).text(); $("#editForm input[name='item']").val(item); $("#editForm input[name='amount']").val(amount); $("#editForm input[name='date']").val(date); $("#editForm input[name='method']").val(method); $("#editForm input[name='trustee']").val(trustee); $('#editModal').modal('show'); }); $('#editForm').on('submit', function(e){ e.preventDefault(); e.stopPropagation(); var $this = $(this); var valid = true; $('#editForm input').each(function(){ let forms = $(this); if(forms.val()){ valid = false; $this.parents('.validate').find('.mySpan').text('The' +$this.attr("name").replace(/[\_]+/g), '')+ 'field is required' } }); if(valid){ let data = $this.serialize(); $.ajax({ url: "{% url 'edit_office' %}", type: 'POST', data: data, dataType: 'json', success: function(resp){ if(resp.message == 'success'){ alert('Updated Successfully'); $('$editModal').modal('hide'); } else{ alert(resp.message) } }, error:function(resp){ console.log('error updating form') }, }); } return false; }); modal with form <div class="modal fade" id="editModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="editModalLabel">Edit Expense</h5> <button … -
How to put data from html form into django form?
Html form: <form method="post" action="{% url 'blog:add_comment' article.id %}"> {% csrf_token %} <textarea type="text" id="text" class="form-control" rows="3"></textarea> <button type="submit" class="btn btn-primary mt-2">Submit</button> </form> Django form: class NewComment(forms.Form): text = forms.TextInput() add_comment view: def add_comment(request, article_id): if request.method == "POST": form = NewComment(request.POST) if form.is_valid(): text = form.cleaned_data['text'] return redirect('blog:detail', article_id) I'm trying to validate comment with django form, but it's cleary dosen't work. -
How to make other values of same dataset available in Django model field
I have a created a custom Django model field that should encrypt data before saving it to the database (get_prep_value()) and decrypt data after reading it from the database (from_db_value()). The key I use to encrypt and decrypt the data is stored in the same model/dataset as the encrypted field itself. Somehow I am not able to get the value of another field/column of the same model/dataset (here the key i want to use to encrypt and decrypt my field value) in the from_db_value() and get_prep_value() method of my custom model field. Any tip or hint how to do it is very much appreciated... Thank you. -
Django update_or_create with potentially null idenitfier
I have a function in Django that accepts a post request. If that post request includes an id, I want to update that object. If the post request sends a blank/null id, I'd like to create a new object and have Django set the ID (primary key) of the model. Here is what I have: def save_user_roster_to_db(): name = request.data['name'] id = request.data['id'] # this could be null/blank or be an ID try: user_roster = SavedUserRoster.objects.update_or_create( id=id, defaults={ "name": name, } ) return user_roster.pk except: raise Exception However, this seems to try to assign the blank/null value as the ID when creating a new object. How can I tell Django to set its own ID (which is the primary key) if it's creating a new object? -
Django forms Exception Value: __init__() got multiple values for argument 'data'
I recently upgraded from django 1.9 to django 3.2 and I get the below error. I understand that the keyword argument is overwriting positional argument as shown in the other posts with similar errors. Appreciate help in showing how I should pass the data argument to forms super constructor. Traceback (most recent call last): File "/home/dreamer/Envs/his/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/dreamer/Envs/his/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dreamer/Envs/his/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/dreamer/Envs/his/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/dreamer/Envs/his/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/dreamer/Envs/his/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/dreamer/Envs/his/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/dreamer/Projects/his/apps/internationals/views.py", line 46, in dispatch return super(InternationalList, self).dispatch(request, *args, **kwargs) File "/home/dreamer/Envs/his/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/dreamer/Envs/his/lib/python3.8/site-packages/django/views/generic/list.py", line 142, in get self.object_list = self.get_queryset() File "/home/dreamer/Projects/his/apps/internationals/views.py", line 59, in get_queryset self.filter_form = InternationalFilterForm(self.request, data=self.request.GET) File "/home/dreamer/Projects/his/apps/internationals/forms.py", line 141, in __init__ super(InternationalFilterForm, self).__init__(*args, **kwargs) Exception Type: TypeError at /internationals/list/ Exception Value: __init__() got multiple values for argument 'data' class InternationalList(views.OrderableListMixin, ListFilterMixin, generic.ListView): ... def get_queryset(self): if not self.request.GET.items(): self.filter_form = InternationalFilterForm(self.request) else: self.filter_form …