Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django model dynamically query ManyToManyField for values
The following code works fine for an object that has a ManyToManyField called references like this: res = [] for ref in MyBook.objects.get(id=some_id).references.values("f_name", "l_name"): res.append(ref) My question is, how can I dynamically get a pointer to references, given just the string "references"? Once I have an instance of the MyBook class like this: my_book_model = MyBook.objects.get(id=some_id) I don't know how to get the pointer to my_book_model.references. Once I have that pointer, then I can just pass the values array to the pointer.values(values_array) -
Filter and group by user age - Django
I'm making a chart table which i would like to group and count by integer range (ages) of the users in that object. Table for example: Name Age John 21 Steve 24 Dan 29 Mike 31 and my expected result is: [20-25] [26-31] 2 2 I was playing around with the annotate function of Django but couldn't figure it out so far. Any suggestions aboout this? My views.py: qs = Post.objects.filter(spot=spot).annotate( age_group = Case( When(attendant__profile__age__range=[21, 27], then=Value('21-27')).count(), When(attendant__profile__age__range=[29, 33], then=Value('29-33')).count(), default=Value('No group'), output_field=CharField(), ) ).values('age', 'age_group') models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField(null=True, blank=False) def age(self): return int((datetime.date.today() - self.birthday).days / 365.25) -
HyperlinkedRelatedFIeld and OneToOne relationship - object has no attribute
For my app I have offices and HR users (users with an OneToOneField to HRProfile), and I want to be able to assign HRs to offices. The issue I'm facing is that I just can't access the User's 'email' field when trying to look it up through a HyperlinkedRelatedField on an OfficeSerializer. Relevant models: class User(AbstractBaseUser, PermissionsMixin): ... email = models.EmailField(unique=True) ... from polymorphic.models import PolymorphicModel class Profile(PolymorphicModel): ... related_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="profile", ) ... class HRProfile(Profile): some_hr_specific_field = models.CharField() def __str__(self) -> str: return self.related_user.email class Office(models.Model): ... assigned_hrs = models.ManyToManyField( "users.HRProfile", related_name="offices", blank=True ) ... View: class UserViewSet( GenericViewSet, ): serializer_class = UserSerializer queryset = User.objects.all() lookup_field = "email" lookup_url_kwarg = "email" lookup_value_regex = "[\\w@.]+" ... # the OfficeViewSet just has the two required fields (queryset and serializer) And the OfficeSerializer I'm having trouble with: class OfficeSerializer(serializers.HyperlinkedModelSerializer): ... assigned_hrs = serializers.HyperlinkedRelatedField( queryset=HRProfile.objects.all(), view_name="api:user-detail", lookup_field="related_user.email", many=True, ) ... The above raises 'HRProfile' object has no attribute 'related_user.email' which I don't know what to make of, since the HRProfile.__str__ has no issues resolving the self.related_user.email path correctly for a given user. I tried it with source='assigned_hrs.related_user', lookup_field='email' but to no avail. Also, I tried replacing the HyperlinkedRelatedField with an … -
Django Forms Validation Check is not working
I am giving this validation rule in my django forms, so when the field is none then it will rasie validation error but validationcoming ervey time , i meant when is none or not none i am getting the validationerror every time, How i solve this issue. models.py class Check(models.Model): use_for_car = models.BooleanField(default=False) Forms.py class CheckForm(forms.ModelForm): translated_names = TranslationField() def clean(self): cleaned_data = super(CheckForm, self).clean() use_for_car = self.cleaned_data.get("use_for_car") if use_for_car is None: raise ValidationError("Use For Car NEED TO BE FILLED ") return use_for_registrations class Meta: fields = "__all__" model = models.Check -
How can I shutdown the server when I exit the browser tab?
How can I shutdown the server when I exit the browser tab django open server django in django after server and open website in tab How can I make the server shutdown if all tabs on the site are closed? Also, can I control the server to be open in the background and not in the terminal? I have tried handling the beforeunload event window.addEventListener('beforeunload', function(e) { e.returnValue = 'if you exit?'; //required for Chrome }); But this event only works when the page is refreshed and does not work when the tab is closed -
Use model instance in custom templatetag
How can i get current instance model in templatetag, like: from django import template from users.models import Product register = template.Library() @register.simple_tag(name='description_tag') def description_tag(): custom_description = Product.product_description return custom_description with this a get the object : <django.db.models.query_utils.DeferredAttribute I have no ideia to get a current instance model, any tip? -
Has anyone had this error in manage django
could you help me? Thank you for this one already. I'm having a problem exiting the finish when I run manage, and the localhost "http://127.0.0.1:8000" is not active apparently, I'm using Opera GX, and in it the page appears as On the Local Server Page: Unable to access website Connection to 127.0.0.1 was refused. Try: check connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED" The error that appeared in the terminal is as follows: Note (I'm using Python 3.10 and localhost Django) (venv) PS C:\Users\gabri\OneDrive\Desktop\ProjectDjango> & "c:/Users/gabri/OneDrive/Desktop/ProjectDjango/venv/Scripts/python.exe" "c:/Users/ gabri/OneDrive/Desktop/ProjectDjango/manage.py" Type 'manage.py help ' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser [contenttypes] remove_stale_contenttypes [django] check compilemessages createcachetable dbshell difsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver [sessions] clearsessions [staticfiles] collectstatic findstatic runserver -
why am I getting 304 status code trying to get gif pic from cache
I made a blog on Django and added images to form. While I add .jpg or .png pics I have now problem, evrth works, but once I try to add a .gif pic - it doesn't add to post. Another interesting fact, that when I try to edit this post and add that very .gif pic or any other .gif - it works. when I press post button I see next logs: [21/Jun/2022 19:03:04] "POST /create/ HTTP/1.1" 302 0 [21/Jun/2022 19:03:05] "GET /profile/Natuska/ HTTP/1.1" 200 6925 [21/Jun/2022 19:03:05] "GET /media/cache/27/b6/27b6ff73a4d6cea2aa42a8ff16d888b6.jpg HTTP/1.1" 304 0 [21/Jun/2022 19:03:05] "GET /media/cache/3a/11/3a11ddc3f6d23b024579611a813df2f4.jpg HTTP/1.1" 304 0 [21/Jun/2022 19:03:10] "GET /profile/Natuska/ HTTP/1.1" 200 6925 [21/Jun/2022 19:17:09] "GET /posts/42/ HTTP/1.1" 200 2847 As I understand, I have some problems with cache. Obj not modified. But how it can be if it was just created here is my views.py file: @login_required def post_create(request): template = 'posts/create_post.html' is_edit = False form = PostForm(request.POST or None) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('posts:profile', username=request.user) context = { 'form': form, 'is_edit': is_edit } return render(request, template, context) @login_required def post_edit(request, post_id): template = 'posts/create_post.html' post = get_object_or_404(Post, pk=post_id) form = PostForm( request.POST or None, instance=post, files=request.FILES or None, … -
When an option selected I wanna change the other select tags options
In my Django template I have two select tag. I want to change the second tag to be linked to the first. For example when in first tag animals option select I want to show the animals on the second select tag. When plants select in first tag I want to show plants in the second select tag. How can I do this? (animals or plants) <select id="creatures"> {% for x in list %} <option value="{{x.creature}}">{{x.creature}}</option> {% endfor %} </select> <select id="instances"> {% for y in instances %} <option value="{{y.instance}}">{{x.instance}}</option> {% endfor %} </select>