Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cant seem to push code to heroku on vsc
I'm reading Django for Beginners and in the book you need to push your code to heroku but when I try to push it to heroku im getting an error that looks something like this Enumerating objects: 26, done. Counting objects: 100% (26/26), done. Delta compression using up to 4 threads Compressing objects: 100% (25/25), done. Writing objects: 100% (26/26), 3.85 KiB | 171.00 KiB/s, done. Total 26 (delta 2), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 49cd9b70adce6b44ee89a1fddec675d04bc4300d remote: ! remote: ! We have detected that you have triggered a build from source code with version 49cd9b70adce6b44ee89a1fddec675d04bc4300d remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! remote: ! … -
How to get multiple select values from my own Django form
I would like to know how to get values from a jquery plugin from select multiple. This is my form. <form action="{% url 'agregar_solicitud' %}" method="post"> {% csrf_token %} <select name="producto[]" class="form-control" multiple="multiple" > {% for row in rows %} <option value="{{row.nombre}}">{{row.nombre}}</option> {% endfor %} </select> {% load static %} <script src="{% static 'js/BsMultiSelect.min.js' %}"></script> <script> $("select").bsMultiSelect({cssPatch : { choices: {columnCount:'3' }, }}); </script> <input type="submit" name="agregar" value="Agregar Productos" class="btn btn-success"> </form> [That is the image of the form] 1 And this is my view. def agregar(request): pr= request.POST["producto[]"] data = request.POST.get('producto[]') print(pr,data) return redirect('inicio_solicitud') But by none of the methods I can obtain the value of the product field by its position, such as: request.POST["producto1"]. In Laravel I had no problem doing the following: $request->producto1. Beforehand thank you very much. -
How to implement extended auth-User model in SignUp form in Django?
I want to add more fields in auth-User model. So, according to this docs(https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#extending-the-existing-user-model) I created a 'UserProfile' model in one-to-one relation with auth-user. But it's not working in forms.py. Actually, I couldn't implement it in forms.py Here is my code: models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE) profile_picture = models.ImageField() forms.py class CustomSignupForm(SignupForm): profile_picture = forms.ImageField() def signup(self, request, user): up = user.userprofile user.userprofile.profile_picture = self.cleaned_data['profile_picture'] up.profile_picture = self.cleaned_data['profile_picture'] user.save() up.save() return user Even after SignUp I don't get any object in 'UserProfile'. -
Apply two humanisers to number
How do you apply to humanisers to a number. For example, intcomma and ordinal. This would convert 1000 to 1,000nd. -
Authenticate Django from url without login
I am trying to log my user with a link generated from me, basically this is the workflow, a user wants to fill a form from my site, but they comunicate through whatsapp, so i will generate a link for them, but the catch is they have to log in once they go into the page, since they will fill some sensitive data , plus, id like them to get logged into the system and use other functionalities if they want. Security wise, i will always know if the user is who they say when they message me bc i can recognize the phone number, so i dont need them to log in again once they click the link and go into the browser. Dont get me wrong i want the user to be able to log in if they want from their computer, but it makes it a lo easier if they dont have to do that form mobile. Based on the phone number i will know the user, so what i need is generate a link where they will click and it will be self authenticating, meaning they will be logged with this link and forwarded to where … -
'User' object has no attribute 'encode' while signing up
I am building a BlogApp and Today i tried to signup and then this error is keep showing 'User' object has no attribute 'encode' AND Then i tried to register in all my previous versions then this error is showing them all. BUT it was working before few days. Then i restarted my pc but still same error. views.py def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=200) password1 = forms.CharField(widget=forms.PasswordInput()) username = forms.CharField(help_text=False) class Meta: model = User fields = ( 'email', 'username', ) models.py @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() When i click on register then this error is raising . When i check in admin then user is created BUT profile is not created, BUT it should show me User has no object Profile BUT it is showing something different. Any help would be much Appreciated. Thank You in Advance. -
Is there a way to modify model data on a button press?
I was wondering if there is a way to change the values of an object on a button press. I am making a to-do list application, and next to each item I would like there to be a button that sets the 'completed' value of the ToDo object to True. I think that you'd call a function in views.py that changes the data, but I don't really know how to do that. index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>To Do List</title> </head> <body> <h1>To Do List</h1> <form method="POST"> {% csrf_token %} {{ form }} <button type="submit">Add</button> </form> {% for todo in todolist %} {{ todo.content }} {{ todo.completed }} <br> <!-- The button/link would go here, but I don't know what to do --> {% endfor %} </body> </html> views.py: from django.shortcuts import render, redirect from .models import ToDo from .forms import ToDoForm def index(request): if request.method == 'POST': form = ToDoForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = ToDoForm() context = {'todolist': ToDo.objects.all(), 'form': form} return render(request, 'main/index.html', context) models.py: from django.db import models class ToDo(models.Model): content = models.CharField(max_length=100) completed = models.BooleanField(default=False) Thanks! -
How to run test fixtures in across multiple classes in Django?
I have three python packages with multiple classes all containing multiple tests and i am running all the testcases at once using 'python manage.py test' command. Each class has the annotation of TestFixture. Fixtures is loading only once for the first class and for all the other classes fixtures are not loading. I need fixtures to be loaded when each test class ran. (e.g. TextFixture1 loaded when class 1 runs, then TestFixture2 loaded when class 2 runs, and finally TestFixture3 loaded when class 3 runs.). example: class Class1(APITestcase): fixtures= ['abc.json', 'cba.json'] #fixture1 class Class2(APITestcase): fixtures= ['123.json', '456.json'] #fixture2 class Class2(APITestcase): fixtures= ['xyz.json', 'zyx.json'] #fixture3 In the above example one fixtures 1 is loading and the other two fixtures are not loading when i use the command 'python manage.py test'. How can i solve this? -
Is caching helpful in the web app by django?
I've made my first project app with Django Framework. Now I'm trying to use local memory based caching since I'm just testing its functionality and latency. As most part of my site contains dynamic web pages with different contents for different users, I'm trying to bring in efficiency using template fragment caching. I'm enclosing all the static part of templates of my pages in {% cache %} and leaving dynamically generated part outside using many cache blocks. I don't seem to understand if it's really going to help my pages to be rendered fast because the part going to be cached is already static. When template engine compiles and executes a template to give response, its running time is directly proportional to number of jinja statements. Right? So if I'm avoiding static part being gone through by template engine, by caching, I'm still leaving most of statements for engine, is it going to help with speed or waste efforts? P.S. Excuse me for poor framing of question. Really bad at it -
How to combine querysets based on fields that have the same value
I have two querysets. queryset[{'name': B, 'size': 8}] queryset['name': A, 'name': B, 'name': C, 'name': D}] the result I want is this. queryset[{'name': A, 'size': 0}, {'name': B, 'size': 8}, {'name': C, 'size': 0}, {'name': D , 'size': 0}] I've tried combining both querysets, but I don't get the results I want. ('|', union) How to combine if values of one field in two querysets are the same? I've been thinking about it for a few days. urgent please help -
Merging Json response Django python
I am writing a django server api,where I have two request to fetch data from two other apis. list1 = requests.get(f"www.test.com/list/") list2 = requests.get(f"www.test.com/list2/") this two lists have json as response.I want to merge this two and put it in a json object like below {"list1":list1,"list2":list2} and return the result -
add an `a` tag with `href` linking to the next part in a django form HTML
I have a django form and I am trying to create a step up form where when you finish one section you click next to the go the next section in the same HTML template: I have created everything fine but I am stuck with the button for the next button. I have set an id and linked it to an href but is not opening the next form as required. Here is what I have tried to make it easier for explaining: <ul class="nav nav-pills mb-3" id="ex-3" role="tablist"> <!-- General Information --> <li class="nav-item" role="presentation"> <a class="nav-link active" id="ex-3-tab-1" data-mdb-toggle="pill" href="#generalInformation" role="tab" aria-controls="pills-1" aria-selected="true" >General Information</a> </li> <!-- Contact Information --> <li class="nav-item" role="presentation"> <a class="nav-link" id="tab_contactInformation" data-mdb-toggle="pill" href="#contactInformation" role="tab" aria-controls="pills-2" aria-selected="false" >Contact Information</a > </li> </ul> In the General info part I have added an a tag to link to href="#contactInformation" same as the nav-pill showing in the top but it is not leading to it. It is just saying in the same location. <a href="#contactInformation" >Contact Information</a > My question How to add an a tag with href linking to the next part? What am I doing wrong and how can I fix it? Thanks for the … -
Registration of a user and subsequent activation by the admin with django-rest-framework and djoser
I would like to create a user that is activated by the system admin with djoser and django-rest-framework. The sequence of operations that I would like to obtain is the following: a user sends the registration request the user is saved in the database but remains inactive an email is sent to the admin informing that a new subscription has been requested the admin activates the user from django admin panel when the user has been activated, an email confirming the activation is sent to him. I can do this with django in the following way: signals.py @receiver(post_save, sender=User, dispatch_uid='register') def register(sender, instance, **kwargs): if kwargs.get('created', False) and not instance.is_active: mail_admins('User registration request', f"A registration request was made by the user:\n\n{ instance.username }\n{ instance.email }", fail_silently=False, ) @receiver(pre_save, sender=User, dispatch_uid='active') def active(sender, instance, **kwargs): if instance.is_active and User.objects.filter(pk=instance.pk, is_active=False).exists(): subject = 'Account activation' mesagge = '%s your account has been successfully activated!' %(instance.username) from_email = settings.EMAIL_HOST_USER send_mail(subject, mesagge, from_email, [instance.email], fail_silently=False) views.py class UserRegisterView(CreateView): form_class = UserRegisterForm template_name = 'users/register.html' success_url = reverse_lazy('login') def form_valid(self, form): user = form.save(commit=False) user.is_active = False user.save() return redirect('request') forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', … -
adding and displayin E-Books in django
I am working on a project for selling E-Books but I want to know the best way to display E-Books and handling them considering that users can not download or copy E-Books and can just read them can anyone help me what can I do? -
How can I listen for changes in the Django database?
I have two separate Django projects. Project B shares project A's database by referencing project A's database in it's models Meta class (db_table). Otherwise the projects are completely separate and run in different containers. I want to execute a function in Project A after Project B creates or updates a Model field in the shared database. I have tried using Model signals (post_save) in Project A, but it does not trigger when the Model field is saved in Project B when it is created or updated. How can I pass a signal from Project B to Project A to execute code in Project A, without writing the functionality I want to execute into Project B? Or how can I listen for changes in the database in Project A? -
Django Nginx: Gives WARNING:django.request:Not Found: When running server
I am trying to use Nginx with django to run my server but when i try to run i get these WARNING:django.request:Not Found: errors. normal python manage.py runserver works fine. Also i used this tutorial. Any idea why i am getting these errrors and how to fix them? Full Traceback Not Found: /boaform/admin/formLogin WARNING:waitress.queue:Task queue depth is 1 WARNING:django.request:Not Found: /boaform/admin/formLogin Not Found: /robots.txt WARNING:waitress.queue:Task queue depth is 2 WARNING:django.request:Not Found: /robots.txt Not Found: /boaform/admin/formLogin WARNING:waitress.queue:Task queue depth is 2 WARNING:django.request:Not Found: /boaform/admin/formLogin Not Found: /.env WARNING:waitress.queue:Task queue depth is 2 WARNING:waitress.queue:Task queue depth is 3 Not Found: /HNAP1/ WARNING:django.request:Not Found: /.env WARNING:django.request:Not Found: /HNAP1/ WARNING:waitress.queue:Task queue depth is 3 Not Found: /HNAP1/ WARNING:waitress.queue:Task queue depth is 2 WARNING:waitress.queue:Task queue depth is 3 Not Found: /boaform/admin/formLogin WARNING:waitress.queue:Task queue depth is 4 WARNING:django.request:Not Found: /boaform/admin/formLogin WARNING:django.request:Not Found: /HNAP1/ WARNING:waitress.queue:Task queue depth is 5 Not Found: /.env WARNING:django.request:Not Found: /.env Not Found: /.env WARNING:django.request:Not Found: /.env Not Found: /assets/global/plugins/jquery-file-upload/server/php/index.php WARNING:django.request:Not Found: /assets/global/plugins/jquery-file-upload/server /php/index.php Not Found: /boaform/admin/formLogin WARNING:waitress.queue:Task queue depth is 1 WARNING:waitress.queue:Task queue depth is 2 Not Found: /favicon.ico WARNING:waitress.queue:Task queue depth is 3 WARNING:django.request:Not Found: /boaform/admin/formLogin Not Found: /.env WARNING:django.request:Not Found: /favicon.ico Not Found: /robots.txt WARNING:waitress.queue:Task queue depth is 4 WARNING:django.request:Not … -
how to make a button that redirects to the previous page only if it is on my site
I would like to make a button that redirects the user to the previous page only if it is on my site, otherwise this button would redirect to the home page I read in the doc that we could not read the history urls but only redirect, so I ask the question if anyone knows any tips to do this function Back_on_site() { if (previous_domain == my_domain) history.back() else window.location.href = "my_site/home" } -
How to fix this Exception and Type Error? (Django)
I was following this tutorial by Tech with Tim, but suddenly after adding a few lines of code I only gett type errors or exception errors when I try to see my webpage. My code: views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import Item, ToDoList from .forms import CreateNewList # Create your views here. def index(response): return HttpResponse("<h1>Hello, world!</h1>") def item_by_id(item_id, id=None): item = Item.objects.get(pk=item_id) return HttpResponse(f"Item: {item.title}, published on {item.datetime_found}") def home(response): return render(response, "myapp/home.html", {}) def base(response): return render(response, "myapp/base.html", {}) def itemlist(response, list_id): ls = ToDoList.objects.get(id=list_id) return render(response, "myapp/itemlist.html", {"ls": ls}) def create(response): if response.method == "POST": form = CreateNewList(response.POST) # Takes POST and uses data for form if form.is_valid(): # is_valid() checks class-fields for valid input n = form.cleaned_data["name"] # Clean and un-enc data, specify field "name" t = ToDoList(name=n) # Use data to create new ToDoList t.save() return HttpResponseRedirect("itemlist/%i" % t.id) # Redirect to page that shows the list else: form = CreateNewList() return render(response, "myapp/create.html", {"form": form}) models.py from django.db import models from django.forms import model_to_dict from django.utils.timezone import now class Item(models.Model): title = models.CharField(max_length=200) # Short description of the item datetime_found = models.DateTimeField(default=now, blank=True) # Date and time … -
Need help rendering a view
I am making a blog like app to help record what I did for a certain project for work. I am able to successfully make a list of the projects I am currently working on and I can successfully render the one I want to edit. However, once I open the project I want to edit it and I click the submit button, I am unable to redirect it back to the view for that one project. This is the project I want to edit. I try to update it like the following. When I click the update button it just refreshes the page and the update doesn't take effect. Any ideas as to why this is happening? Here is my code. views.py from django.shortcuts import render,redirect from .models import CR,GC from .forms import CrForm,GcForm # Create your views here. def Home(request): return render(request,'base.html') def crlistview(request): crs = CR.objects.all() context = {'crs':crs} return render(request,'cr_list.html',context) def CreateCr(request): form = CrForm() if request.method == 'POST': form = CrForm(request.POST) if form.is_valid(): form.save() return redirect('crlist') context = {'form':form} return render(request,'cr_form.html',context) def UpdateCr(request,pk): cr = CR.objects.get(id=pk) form = CrForm(instance=cr) context = {'form':form,} if request.method == 'POST': form = CrForm(request.POST,instance=cr) if form.is_valid(): form.save() return redirect('crlist') return … -
No filter named 'linebreaks'
I am using Jinja2 and Django's template system. When I try to use linebreaks or linebreksbr template filter, I get an Exception: jinja2.exceptions.TemplateAssertionError: No filter named 'linebreaksbr'. Example: <div> {{ object_instance.text_content|linebreaksbr }} </div> Other default filters like capfirst are working as they should. -
Error "This field is required" when setting forms initial data to user data
I'm creating a signup feature for my website. When a person sign-up, a new user is created and then they are redirected to a view where a doctor is created (a user is a doctor in my case). The login works fine, but when I try submit the form to create the doctor using the users name and surname, I get an error saying the fields are required - but the form fields have been populated - and my cleaned_data dictionary is empty. Any idea as to what I am doing wrong? Here is my view.py: def createDoctor(request): # user = None # name = None # surname = None # if request.user.is_authenticated: # user = request.user # name = user.first_name # surname = user.last_name if request.method == 'POST': user = get_user(request) doctor_form = DoctorCreationForm(data=request.POST, prefix='docForm') if doctor_form.is_valid(): doctor_form.save() return redirect('medical:doctors-list') else: print(doctor_form.errors) else: user = get_user(request) doctor_form = DoctorCreationForm(initial={'doctor_name': request.user.first_name, 'doctor_surname': request.user.last_name}) context = {'doctor_form': doctor_form} return render(request, 'medical/create_doctor.html', context) -
Django: Socialapp matching query does not exists
É simple e facil de resolver este erro. caso vc não tenha um usuario no projeto, é necessario criar um com: python manage.py createsuperuser logo apos é necessario realizar o login na pagina administrativa do seu site. para isso primeiro inicie o servidor: python manage.py runserver e entre na url de admin, exemplo: localhost:8000/admin ou 127.0.0.1:8000/admin apos a autenticação no sistemas, você deve ir para sessao de aplicações socias, e cadastrar sua app, informando sua secret_key e id_client depois de realizar esses passos seu sistema deve funcionar -
Django showcasing videos being sent to users
I have a Django application where a user can submit a form and send an email to someone with a file attached to it (usually a video). My question is, is it possible to grab that attachment and showcase it somewhere on the dashboard I have set up? I'm trying to make it look like this: my send mail view looks like this: def send_mail_plain_with_file(request): if request.method == "POST": message = request.POST.get('message', '') subject = request.POST.get('subject', '') mail_id = request.POST.get('email', '') email = EmailMessage(subject, message, request.user.username, [mail_id]) email.content_subtype = 'html' file = request.FILES['file'] email.attach(file.name, file.read(), file.content_type) email.send() messages.success(request, "Your message has been sent.") return redirect('dashboard') return render(request, 'sendattachments.html') the HTML file that holds the form is in sendattachments.hmtl and looks like this: {% extends 'base_generic.html' %} {% load static %} {% block content %} <div class="container border py-4 my-4 w-75"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label class="form-label">Send to Email:</label> <input type="text" name="email" class="form-control" id="title"> </div> <div class="mb-3"> <label class="form-label">Subject:</label> <input type="text" name="subject" class="form-control" id="title"> </div> <div class="mb-3"> <label for="desc" class="form-label">Message:</label> <textarea name="message" class="form-control" rows="5">Coming from: {{user.first_name}} {{user.last_name}}</textarea> </div> <div class="mb-3"> <label for="filename" class="form-label">Select File:</label> <input type="file" name="file" class="form-control"> </div> <button type="submit" class="btn btn-primary">Send Mail</button> </form> </div> {% … -
How to fix: TypeError: a bytes-like object is required, not 'str'
I have recently started programming. I am trying to simulate an ethereum transaction with the help of Ropsten. When I try to run the function (sendTransaction ("message")) with the Django's shell I get this error: TypeError: a bytes-like object is required, not 'str'. The full errors track is the following: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Francesco\bakeka\bloggo\utils.py", line 18, in sendTransaction tx = w3.eth.sendTransaction(signedTx.rawTransaction) File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\eth.py", line 577, in send_transaction return self._send_transaction(transaction) File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\module.py", line 53, in caller (method_str, params), response_formatters = method.process_params(module, *args, **kwargs) # noqa: E501 File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\method.py", line 179, in process_params params = self.input_munger(module, args, kwargs) File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\method.py", line 168, in input_munger root_munger(module, *args, **kwargs), File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\eth.py", line 120, in send_transaction_munger if 'from' not in transaction and is_checksum_address(self.default_account): TypeError: a bytes-like object is required, not 'str' (Francesco is my username, bakeka is my project, globale is my venv) from web3 import Web3 def sendTransaction(message): w3 = Web3(Web3.HTTPProvider('My Ropsten Ip')) address = 'my addres' privateKey = 'my private key' nonce = w3.eth.getTransactionCount(address) gasPrice = w3.eth.gasPrice value = w3.toWei(0, 'ether') signedTx = w3.eth.account.signTransaction(dict( nonce = nonce, gasPrice = gasPrice, gas = 10000, to = '0x0000000000000000000000000000000000000000', value = value, data = message.encode('utf-8'), ), privateKey) … -
django get method with argument not working
I am trying to make a get request with an ID argument in django as the doc says in https://docs.djangoproject.com/en/3.2/topics/class-based-views/ but I can't seem to make it work. The request is arriving in the backend as expected. "GET /api/acordo-parcela/1/ HTTP/1.1" 200 348 where 1 is my ID. but even after creating a new urlpattern it does not reach the view class The urlpattern: path('/acordo-parcela/<int:clienteId>/', GetParcelas.as_view()), The GetParcelas class: class GetParcelas(APIView): print("test") def get(request, clienteId): print("inside") I have read the docs on https://docs.djangoproject.com/en/3.2/topics/http/urls/ and tried with views.AcordoParcelaViewSet (a viewset I created accordingly) but keep getting a 'has no attribute' error. What is the easyer way to make this get request with an argument?