Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I set range in forloop in Django template tags?
So I want to create a for loop that has certain range. Let me show you the code. views.py def mainPage(request): ... myList = [ ### has some elements ### ] listLength = len(myList) context = {'listLength' : listLength} return render(request, 'main.html', context) main.html {% for i in listLength %} <div class="book-{{i}}">Book number {{i}}</div> {% endfor %} So I know that the {% for i in listLength %} part is wrong. I want to pass each number from 1 to listLength, but can't figure out how. Please help. Thanks. :) -
Django I need upload file button only remove choose file and don't need refresh page when upload
I want to upload only button and don't need refresh when upload how to fix this model_form_upload.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" >Upload</button> </form> forms.py class DocumentForm(forms.ModelForm): class Meta: model = DocumentFile fields = ['document'] views.py def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() print(form) return render(request, 'model_form_upload.html', {'form': form}) -
Django-python code for password.is_valid()
I want to create an input field for password such that it verifies if the password is valid when the user is typing. So I have created a class PasswordValidation in views.py: from django.views.generic import View import json from django.http import JsonResponse from django.contrib.auth.models import User class PasswordValidation(View): def post(self, request): data = json.loads(request.body) password = data['password'] if not condition_to_check_if_password_is_valid: return JsonResponse({'password_error': 'The error message'}, status=409) return JsonResponse({'password_error': True}) In urls.py, I have added this class based view as /password_valid/ HTML and JavaScript to send and fetch the data from the server: <div class="field"> <div class="label">Password*</div> <input type="password" name="password" id="password1" class="form-control"> <div class="invalid_feedback" style="display: none"></div> </div> <script type="text/javascript"> const password = document.querySelector('#password1'); const feedback = document.querySelector('.invalid_feedback'); password.addEventListener("keyup", (e) => { const passwordVal = e.target.value; password.classList.remove("is-invalid"); feedback.style.display="none"; if(passwordVal.length>0){ fetch("/password_valid/", { body: JSON.stringify({'password' : passwordVal}) , method:"POST", }) .then((res) => res.json()) .then((data) => { console.log("data", data); if(data.password_error != true){ password.classList.add("is-invalid"); feedback.style.display="block"; feedback.innerHTML = `<small class="text-danger font-weight- bold">${data.password_error}</small>` } }); } }); </script> -
Django Formsets For Each Foreign Key Relation
I'm trying to create a single page with each potential foreign key relationship creating a separate form on the page. So, given my three related models: models.py class Product(models.Model): product_id = models.AutoField(primary_key=True) upc_code = models.CharField(max_length=200) product_name = models.CharField(max_length=200) sap_number = models.IntegerField() category = models.CharField(max_length=200) product_status = models.CharField(max_length=200) product_order = models.IntegerField() eff_date = models.DateTimeField('effective date') expn_date = models.DateTimeField('expiration date') def __str__(self): return self.product_name class Meta: db_table = 'product' class Ticket(models.Model): invoice_number = models.AutoField(primary_key=True) company_store_id = models.ForeignKey(CompanyStore, on_delete=models.PROTECT) po_number = models.IntegerField() tran_type = models.CharField(max_length=2, choices=TRAN_TYPES) ticket_date = models.DateTimeField('ticket date') user_id = models.ForeignKey(User, on_delete=models.PROTECT) signature_date = models.DateTimeField('signature date', null=True, blank=True) creation_date = models.DateTimeField(auto_now_add=True) def was_created_recently(self): return self.creation_date >= timezone.now() - datetime.timedelta(days=60) class Meta: db_table = 'ticket' class TicketProduct(models.Model): invoice_number = models.ForeignKey('Ticket', on_delete=models.PROTECT) product_id = models.ForeignKey('Product', on_delete=models.PROTECT) count = models.IntegerField(default=0) class Meta: db_table = 'ticket_product' For each product that currently exists, I would like to have the invoice_number, product_id, and an input box for the count. I have tried creating a formset: forms.py class TicketProductForm(forms.ModelForm): class Meta: model = TicketProduct exclude = [] TicketProductFormSet = modelformset_factory(TicketProduct, form=TicketProductForm) This is my current view: views.py def newTicketProduct(request, invoice_number): ticket = get_object_or_404(Ticket, pk=invoice_number) if request.method == 'POST': formset = TicketProductFormSet() if formset.is_valid(): formset.save() return HttpResponseRedirect(str(ticket.pk) + '/edit') … -
How do I render user uploaded html file as a page? Django
This is the views.py def datacategory(request): book = models.notebook.objects.filter(category='Students') return render(request,'datasets/students.html',{'notebooks':book}) class DataDetailView(generic.DetailView): model = models.notebook template_name = "datasets/data_detail.html" data_detail.html {% block body %} <div style="padding: 2rem;"> {{ notebook.noteb }} </div> {% endblock %} models.py: class notebook(models.Model): noteb=models.FileField(upload_to="notebooks/") category=models.TextField(default="") objects = models.Manager()class The detail views are working but its just outputting the file name of the uploaded html file. How do I render the contents as a webpage? thanks -
Stopping Django Development Server using Fabric
Using Fabric 2.5.0 i was able to start a Django Development Server on a remote machine: c = Connection(host, config=config) with c.cd('Django-directory'): c.run('python manage.py runserver') Now let's say i want to stop the server after a minute or two: time.sleep(60) c.run('pkill -f runserver') This doesn't seem to work as i am inside the shell. So, at this moment how can i stop running the Http server. -
Django: Why do I need these in my setttings.py and urls.py
I am watching an online tutorial on making a video subscription website, and somehow these codes should appear in my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_root'), ] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root') In my urls.py, these codes appear as well... if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am quite a beginner in django and python, can anyone please explain to me why do I need these codes? -
How to trigger a Javascript's function on an user's view when another user clicks on a link in Django?
I'm making a multiplayer board game using Django. I want to create a JS function in my template that will run for the users currently on that view whenever another user clicks on a link (also on that view). I was wondering what general direction I should go for to implement this feature? Thank you! -
Django Model, Forms Fields
I am struggling with django forms. I have been created model.form that its IntegerField but django takes them as string. here is my models.py from django.db import models class CircuitComponents(models.Model): e1 = models.IntegerField() r1 = models.IntegerField() c1 = models.IntegerField() forms.py from django import forms from .models import CircuitComponents class CircuitComponentForm(forms.ModelForm): class Meta: model = CircuitComponents fields = '__all__' and my models.py from django.shortcuts import render from .forms import CircuitComponentForm def circuit_components_view(request): if request.method == 'POST': form = CircuitComponentForm(request.POST) if form.is_valid(): form.save() else: form = CircuitComponentForm() e1 = request.POST.get('e1') c1 = request.POST.get('c1') r1 = request.POST.get('r1') context = { 'form': form, 'basic_circuit_result': e1 + c1 + r1 } return render(request, 'basic_circuit.html', context) There is also ss from the application. I was trying to make summing up them but result is as you can see on ss.. Can anyone help me with the thing that i am not seeing :D ? thanks in advance.. enter image description here -
How would my function made in python call it using a button 
<form action=" " method="get"> <img src="https://placehold.it/500x500" id="preview" class="img-thumbnail"> <input id="submit" type="button" onclick="myfuncion()" method="get" value="Click" /> <!-- Llamar ala funcion para se abra la camara --> <input type="text" value="8" name="letra" size="1"/><!-- Presionar una letra se toma la foto --> <a href="{% url 'catalogs:imagen_list' %} " class="btn btn-primary btn-** **block ">Cancelar</a> </form>** I have a function to take a photo through my laptop's camera, it works on the console. How would you implement it using buttons in a web environment? -
Websocket between python server and javascript client
I am very new to web development, so any tips regarding the following matter will be useful! So, the client written in javascript is supposed to communicate with the server written in python. They work perfectly fine when I run them on a same PC, using localhost. However, I keep running into 'Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT. I tried turning off the firewall settings, but it didn't work. Any input will be very appreciated! PS. The javascript client is written inside the html file of Django framework. Python Server import asyncio import websockets async def hello(websocket, path): name = await websocket.recv() print(f"< {name}") greeting = f"Hello {name}!" await websocket.send(greeting) print(f"> {greeting}") start_server = websockets.serve(hello, "localhost", 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() Javascript Client var ws = new WebSocket("ws://localhost:1337/"); ws.onopen = function(){ console.log("Connection is Established"); ws.send("Message to Send"); }; ws.onmessage = function(evt) { var received_msg = evt.data; console.log(received_msg); }; -
Can only upload images to AWS S3 from Django 3.1 app from admin , not from from my CustomUser app
From localhost,I can upload an image for a user from Django admin but I can't from the User app. I have created a Custom User so that I can use email as the username (not sure if this is relevant). I have also tried setting AWS_S3_SIGNATURE_VERSION = 's3v4' but this does not work either. The image associated with the CustomUser is added using the Profile model which has a one-to-one association with the CustomUser model. I am puzzled as to why it works from Django admin but not from the actual app itself. Any assistance would be greatly appreciated. I am a newbie to Django as well. The following are snippets from the relevant files: settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'ap-southeast-2' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' forms.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django import forms from .models import CustomUser, Profile class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('email',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('email', 'first_name', 'last_name',) class ProfileChangeForm(forms.ModelForm): class Meta: model = Profile fields = ['image',] models.py: class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
Django rest framework return docx file in response
I have a function which should generate the docx file using request.data before saving them to the DB SaveDataAndReturnDocx Views.py SaveDataAndReturnDocx class SaveDataAndReturnDocx(generics.ListCreateAPIView): queryset = ClientData.objects.all() serializer_class = ClientDataSerializer def create(self, request, *args, **kwargs): docxContractGenerate(request.data) serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list)) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Service.py here I got function (used docxtpl library) which changes and renders the docx template def docxContractGenerate(data): #print('-------------DOCS-------------') doc = DocxTemplate("docs/template.docx") #print(doc) context = data doc.render(context) doc.save("docs/"+context['director']+".docx") I tried sending the url of document, but I don't want to store data in storage. It will be better to send the file by response, but don't save it in storage. -
, I am getting operational error no such table while developing website. I already tried to delete db sqlite3 and re add it
This is error I am getting while adding product to the products section of my website]1 0001_initial.py # Generated by Django 2.1 on 2020-08-10 15:06 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('price', models.FloatField()), ('stock', models.IntegerField()), ('image_url', models.CharField(max_length=2083)), ], ), ] -
Get values for first or last object for a model in django-admin
Model.objects.all().values() returns a list of object values. Model.objects.all().first() - This just appears to print an object reference with id field attribute. Is there a way to do something like: Model.objects.all().first().values()? The following does the trick, but is there something for this purpose? Model.objects.filter(id=Model.objects.all().last().id).values() -
Making Javascript Datatable column header align correctly from the start
I have a DataTable in JavaScript that is completely functional. However, when I check my website, the column headers are all scrunched up against the left side. If I select one of the datatable columns (to sort the data based on that particular column), then it aligns properly and starts to work. Any advice on how to get it aligned on page loading instead of after sorting by one of the columns? Code: dataTable("#some_table", 1, "desc", 10) // a bunch of code function dataTable(tableId, sortNum, sortWay, pageLength) { $(document).ready(function () { $(tableId).DataTable({ "scrollY": "200px", "scrollCollapse": true, "order":[[sortNum, sortWay]], "pageLength": pageLength, "columnDefs": [{ "targets": 0, "render": function ( data, type, row ) { return type === 'display' && data.length > 50 ? data.substr( 0, 50 ) +'…' : data; } }] }); $('.dataTables_length').addClass('bs-select'); }); }; Pictures of the before and after: https://ibb.co/92c1PxQ https://ibb.co/xJ95ScG Would appreciate any help on this, thanks! -
How to set Django ForeignKey value as a typed integer in admin forms
I have a model with a ForeignKey in Django. Right now the admin defaults to using a dropdown to select the value of that ForeignKey. What I want is to be able to type in the id of the referenced object there instead of using the dropdown. I tried using django.forms.IntegerField instead of ChoiceField but it did not work. -
Django model accepting a generic key pair entry
I am designing a web api using Django Rest Framework. The API requirement is that end user can send an arbitrary key pair value (can be more than 1 pair at the same time) and I need to store them in the database. That list of key pair currently has around 200 items and it may grow in the future. Is there a way I can represent a "generic" model in Django so that I can store those key pair value? Currently I have such models: class MyConfig(models.Model): pass class ConfigItem(models.Model): key = models.CharField(max_length=255) value = models.CharField(max_length=255) config = models.ForeignKey(MyConfig, on_delete=models.CASCADE) Whereas MyConfig will be the API endpoint (using django rest framework) but I am not sure how to pass a list of key/pair value to the same endpoint and then create the ConfigItem one by one. -
I can't create a Django app using startapp commnand
Python manage.py startapp does not work go -
Uploading locally created file in django views
Can anyone tell me how can I upload the file that I created in views.py? So, I created a JSON file on the server-side but now I want to save that file to the database. How can I do it? I created a python dictionary and created a JSON file out of it but want to save that file based on the user to the database(models). -
Getting issue in django admin panel
Hey there i have made a web app. In that i have login option where a user can signup and then he can sign in to that specific account. Whenever i logged in from an account and try to access the admin panel to check the users, the account from my app automatically logged out. is there any solution for this issue? how can i resolve this? i want the application to remain in same state when i logged in to the admin panel. when i am signed in to the app:Pic is Attached The Error that i want to resolve:Pic is Attached -
Django initialize inline nested formset using dictionary
I have following declaration of inline Formset: ModelAFormSet = generic_inlineformset_factory( ModelA, form=AddModelAForm, formset=BaseModelAFormset, min_num=1, extra=0) ModelA looks as follows: class ModelA(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() model_object = GenericForeignKey('content_type', 'object_id') and BaseModelAFormset is defined following way: class BaseModelAFormset(BaseGenericInlineFormSet): def add_fields(self, form, index): super(BaseModelAFormset, self).add_fields(form, index) form.nested = ModelBFormset( instance=form.instance, data=form.data if form.is_bound else None, files=form.files if form.is_bound else None, prefix='%s-%s' % ( form.prefix, ModelBFormset.get_default_prefix()), ) The I have ModelBFormset defined as follows: ModelBFormset = inlineformset_factory(ModelA, ModelB, form=AddModelBForm, extra=1) with ModelB looking like this: class ModelB(models.Model): quantity = models.IntegerField() value = models.DecimalField(max_digits=7, decimal_places=2) model_a = models.ForeignKey( ModelA, on_delete=models.CASCADE, related_name='model_as' ) I know I can initialize ModelAFormSet following way: init_list = [] for my_model in self.edit_parent.my_models.all(): dictionary = { 'name': my_model.name, 'description': my_model.description, 'id': my_model.id} init_list.append(dictionary) formset = ModelAFormSet(initial=init_list) But I have no clue how I could also initialize here ModelBFormset. Is there any special field name I should pas as a key to initial dictionary? -
After install djanog and try to runserver manage.py I get ImportError
I'm new and trying to follow this tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc from 05:00:00 I follow him just like he doing, then at 05:05:04 when he run the server it's work fine for him, but for me is not. This is exactly my steps.... After Install django like this: pip install django I write this: django-admin startproject pyshop . so far all good, no error, then I try to run the server like this: python manage.py runserver But then I get a big error: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x000001D36DA79AF0> Traceback (most recent call last): File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "D:\User\OneDrive\Programing Code\Python\PyShop\venv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
Bootstrap DateTime Picker Renders Blank Field Instead of Fetching From DB
I have a form with 2 date fields for which I'm using a bootstrap datetime picker as the widget. When I select a date on the form, the input gets saved to database and everything is fine. However, when I load the form in an edit-view the saved date is not automatically filled when all the other fields are. I do not get any errors the widget just doesn't fetch from the DB. The widget I'm using is here. Any help would be great, thanks! -
File Upload Slideshow
I am attempting to create a slideshow after I upload multiple images. I am using python django. Basically, I just would like for images to upload and automatically be inserted as a slideshow. Thank you!