Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Configure VSCODE to step into Django Model
How to configure vscode to be able to step into Django Model? I use pipenv, django & vscod. The python path is setup correctly but it just cannot understand the methods within the django model. Here is a picture as a reference. Thank you! Note pm comes from People.objects.get... -
ERROR while ingegrating MongoDB with Django on windows
I am trying to integrate MongoDB and Django. but when i run the code python manage.py runmigrations app_name i am getting the error: File "C:\Users\Gourav\Envs\test\lib\site-packages\django\db\utils.py", line 126, in load_backend raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' and utils.py line 119 to 136 code looks like; builtin_backends = [ name for _, name, ispkg in pkgutil.iter_modules(django.db.backends.__path__) if ispkg and name not in {"base", "dummy"} ] if backend_name not in ["django.db.backends.%s" % b for b in builtin_backends]: backend_reprs = map(repr, sorted(builtin_backends)) raise ImproperlyConfigured( "%r isn't an available database backend or couldn't be " "imported. Check the above exception. To use one of the " "built-in backends, use 'django.db.backends.XXX', where XXX " "is one of:\n" " %s" % (backend_name, ", ".join(backend_reprs)) ) from e_user else: # If there's some other error, this must be an error in Django raise every required directories is already installed in my virtual environment. pip list gives following result; asgiref 3.5.2 Django 4.0.5 django-mongoengine 0.5.4 djongo 1.3.6 dnspython 2.2.1 mongoengine 0.24.1 Pillow 9.1.1 pip 22.1.2 psycopg2 2.9.3 pymongo 4.1.1 python-snappy … -
Django Class Based View - How to access POST data outside of post() method
I have a CBV based on a TemplateView It has a post(self) method to access user input. Also, it has a template_name property which should be populated with data from post(). No Django models or forms are used here. Attempt to extract data within post method: # views.py class ReturnCustomTemplateView(TemplateView): def post(self, *args, **kwargs): chosen_tmplt_nm = self.request.POST.get('tmplt_name') print(chosen_tmplt_nm) # correct value. # how do I use it outside this method? (like bellow) template_name = chosen_tmplt_nm ... or is there any other way I can get the data from request.POST without def post()? Thanks in advance! -
Can django AutoField be used for custom increment logic in addition to the separate automatic ID AutoField?
I have the following model: class Lot(models.Model): parent_lot_number = models.IntegerField(default=0) child_lot_number = models.IntegerField(null=True, blank=True) I want the following behavior: parent lot number should increment only when the user enters data in a specific form that is creating a new parent child lot number should increment all the time, within each parent For example, the following should be valid data for Lot records: parent_lot_number: 1, child_lot_number: null parent_lot_number: 1, child_lot_number: 1 parent_lot_number: 1, child_lot_number: 2 parent_lot_number: 2, child_lot_number: null parent_lot_number: 2, child_lot_number: 1 parent_lot_number: 1, child_lot_number: 3 parent_lot_number: 3, child_lot_number: null Right now, I have working business logic to do this in my views/forms by getting the max of child_lot_number and parent_lot_number, then assigning the value after the record is created. Instead, can I accomplish this by removing the default=0 on parent_lot_number and using AutoField? When I set parent_lot_number = models.AutoField() I receive errors that "NOT NULL constraint failed: main_lot.parent_lot_number" or "ValueError: Model main.Lot can't have more than one auto-generated field." because of django's hidden ID column. This is a column I cannot drop. -
Can I access same django website on another computer connected with LAN with my computer?
Hey I am trying to access my django webapp on an external machine within my local network. but I am having issues. Below you are the things I have done. But no success. DEBUG = True ALLOWED_HOSTS = ['*'] at this point i've already added port 9595 as an inbound rule within windows firewall. Inbound rules were added on the machine running : python manage.py runserver 0.0.0.0:9595 second machine on network: second-machines-ip-address:9595 first-machines-ip-address:9595 result: empty page/no success. would you have any ideas as to why this is happening? -
How to create a query that shows cases for all status?
I have a problem in my Django project. I have some cases like; Case Type Status Sub Case Stage Volleyball 2020 finished win Basketball 2022 pending none Basketball 2021 finished loss Volleyball 2020 finished win I want to create a query for example are there how many cases is volleyball - 2020 - finished - win or are there how many cases is basketball - 2021 - finished - loss There are a lot of cases with different attributes, I have to count them with a dynamical query. Maybe pandas can help me with that but I don't know. Any idea can help me.