Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Digital Ocen Internal Server Error on django project
I have a django project which i launched on digital ocean. This project uses a costume 404 page. The site works well except that when ever i type in a page that does not exit instead of getting a 404 page, i just get 'internal server error'. Locally, the 404 page works well. -
Colon removed from mail link button?
I send out and automated link like this: <a href="{{ protocol }}://{{ domain }}/offer/{{ offer.code }}/" target="_blank"> See Offer </a> But when I click on the link (rendered as button), I get this link: https://https//domain.com/offer/INW6/ The : is simply omitted. I tried replacing {{ protocol }}: with https:// but the same happens. Someone knows why? -
Specific user PKI to access admin login (Django)
I have a Django app with standard admin and users. I was recently told this wasn't enough to meet security standards at our site. In production, access to the site is already restricted by PKI. I was told I need to tie the admin account to a PKI, I'm assuming my own PKI. I'm assuming what they want is for anyone accessing the /admin page and trying to log in with the Admin account to provide PKI again, and if the PKI doesn't belong to me, the site maintainer, for login to fail. Maybe I'm a bit confused or ignorant, but is it even possible to do this? I have already been investigating django-pki. -
Example.com in django password reset
I have set up my django project to enable password reset but when the password reset mail is sent, i get the line https://example.com/accounts/reset/Mg/... . Exampple.com is not in any way related to my site. I have tried to remove it such that it reads my site url but to no avail -
Django: ERR_CONNECTION_REFUSED
I'm actually learning to use the Django framework with PostgreSQL with Docker and docker-compose. Regularly, when I make a mistake (for example a syntax error in the views.py file), I cannot reach my Django app anymore trough my web browser. Firefox tells me: Unable to connect Firefox can't establish a connection to the server at localhost:8000 Chrome tells me: This site can’t be reached localhost refused to connect. ERR_CONNECTION_REFUSED I had this several times and I always managed to find the error in my code, to correct it and then everything went well again. Currently, my code is working fine. But if I encounter this again (and this happens very often), I would like to be able to find the error quickly by myself. So here is my question: How can I see which file at which line contains the error ? I would like to have a correct error message telling me what went wrong instead of that annoying ERR_CONNECTION_REFUSED browser page over and over. I hope I explained my issue well because I struggled to describe it to Google. Thanks a lot in advance. :) FYI: Ubuntu 18.04.3 LTS Bionic (window manager i3wm) Docker 19.03.4 docker-compose 1.17.1 python … -
Django REST Framework serializer - turn id field into title while keeping the POST method
I am creating a cart with a list of products. I am trying to turn my product ids into titles while still being able to use my POST/ PUT methods on the products to be able to add/ remove the products. Previously my products in the cart was displayed as IDs, this was my serializer: class CartSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='cart-api:cart-detail', read_only=True, lookup_field='id', ) class Meta: model = Cart fields = [ "id", "url", "products", "sub_total", "shipping", "total", ] After making some changes, I was able to turn the product ids into titles and several other fields related to each product. Here is my serializer code after the changes: But my products disappeared from my put method and I am no longer able to add/ remove products. (snippet 2) How can we keep the the POST/ PUT methods on my product while displaying them as the way I want in snippet 2? Thanks so much in advance! class MyPaintingSerializer(serializers.ModelSerializer): painting_url = serializers.HyperlinkedIdentityField( view_name='paintings-api:detail', read_only=True, lookup_field='slug' ) class Meta: model = Painting fields = [ 'id', 'title', 'painting_url', 'price', ] class CartSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='cart-api:cart-detail', read_only=True, lookup_field='id', ) products = MyPaintingSerializer(many=True, read_only=True) class Meta: model = Cart fields = [ … -
Django silk deadlock (PostgreSQL)
I am receiving the following error on production server. How can I debug or fix this. I tried searching for answers but nothing makes sense. django: 2.2.3 django-silk 3.0.0 postgressql 9.5.14 django.db.utils.OperationalError: deadlock detected DETAIL: Process 11444 waits for ShareLock on transaction 28487795; blocked by process 11443. Process 11443 waits for ShareLock on transaction 28487803; blocked by process 11444. HINT: See server log for query details. CONTEXT: while deleting tuple (169,20) in relation "silk_response" -
how to access a field from a another in many to many relation?
I have two models "User" and "Role". Role model is like this: class Role(models.Model): ADMIN = 1 INFORMATIC = 2 REFEREE = 3 SPONSER = 4 STAFF = 5 PLAYER = 6 CUSTOMER =7 VISITOR = 8 ROLE_CHOICES = ( (1, 'admin'), (2, 'informatic'), (3, 'referee'), (4, 'sponser'), (5, 'staff'), (6, 'player'), (7, 'customer'), (8, 'visitor'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True , default=VISITOR) and here is my User model: class User(AbstractBaseUser,PermissionsMixin): username = models.CharField(max_length=150, unique=True, blank=True , null=True,) password = models.CharField(max_length=100, null=True , blank=True) roles = models.ManyToManyField(Role) now I have created some Role objects and some Users and assigned some Roles to some Users. now I want to know how can I determine which user has which roles? from request I have the user. I want to know if a User has a role, for example, sponsor, and grants him some permissions. how can i check this ? -
Using a variable in Django yesno template tag
This could rather be straightforward. However, allow me to ask. In the Django yesno inbuilt template tag, the syntax is given as {{ value|yesno:"yeah,no,maybe" }}. However, I want to out a variable value if it evaluates to true, something like: {{ request.user.profile.mobile_number|yesno:$variable1, 'string' }}. I have tried this {{ request.user.profile.mobile_number|yesno:"{{ request.user.profile.mobile_number }},No Contact" }} but I keep on getting an error: Could not parse the remainder: ':"{{ request.user.profile.mobile_number' from 'request.user.profile.mobile_number|yesno:"{{ request.user.profile.mobile_number' -
Django export multiple urls from same app and include on different prefix
I am trying to expose multiple routes from the same app to the top level urls file like so: # events/urls.py urlpatterns = [ path('', login_required(views.EventsList.as_view()), name='list'), ] # events/urls_admin.py urlpatterns = [ path('', admin_required(views.EventsAdminList.as_view()), name='admin-list'), ] # myproject/urls.py path('events/', include('events.urls')), path('admin/events/', include('events.urls_admin')), But that is giving me an error from the template finding the route: Reverse for 'admin-list' not found. 'admin-list' is not a valid view function or pattern name. Which is weird, since I can double check that python manage.py show_urls shows both events:list and events:admin-list. Please note that I want the final url to be admin/events and not events/admin, because if that was the cause Django docs explains how to do so. I know I could just hard code all the routes, but naturally I am trying to avoid that. I also looked into nested namespaces - something like admin:events:list and events:list - but didn't manage to get to work too. -
How to use dictionary keys as choices in Model?
I have many choice fields and each option corresponding to a number. This number will be used for later calculations. Here is an example. I defined a dictionary which defines the value to each input: driven_factors = { "Education":{ "A": 1.29, "B": 0.98, "C": 0.72, }, } and the model is like: Education_choices= list(driven_factors.get("Education").keys()) Education= models.CharField(max_length=50, choices=Education_choices) Unfortunately, it does not work, because Education_choices is like ['A', 'B', 'C'] other than a sequence of pairs like [('A', 'x'), ('B', 'y',...)] How should I fix this? Or are there other approaches to do this? -
Update the css of one loaded DOM asynchronously once another user clicks a button in his loaded DOM in a django webapp
I am developing a django webapp where I have one html that gets loaded for two different users (User1 and User2) with some slight changes in it. I want my user1 to disable/enable some of the fields (like field) of that html in runtime so that user2 can only update the ones that user1 has made enabled. Currently, user1 can disable/enable html elements via javascript but that changes are only being reflected in his html. User2 cannot see the changes in his html. What will be the perfect way to achieve this functionality? I am not very familiar with everything in Django. Pardon my obvious knowledge gaps. Thanks. -
FieldError at /registerdoctor.html Cannot resolve keyword 'email' into field. Choices are: experience, id, phone_no, user, user_id
I am trying to create a model 'Doctor' which has a OneToOne relationship with Django's builtin 'User' model. For some reason, the Doctor model isn't inheriting the email object from the User or at least that is what I think. Could someone tell me where my mistake is? Thanks! views.py from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth from django.contrib import messages from app1.models import Doctor def HomePage(request): return render(request,'homepage.html') def RegisterUser(request): if request.method =="POST": first_name = request.POST["fname"] last_name = request.POST["lname"] email_id = request.POST["mail"] password1 = request.POST["pass1"] password2 = request.POST["pass2"] username = request.POST["username"] if password1==password2: if User.objects.filter(email=email_id).exists(): messages.info(request,"This Email ID is already Registered!") return redirect("registeruser.html") else: if User.objects.filter(username=username).exists(): messages.info(request,"Username taken!") return redirect("registeruser.html") else: user = User.objects.create_user(first_name=first_name,last_name=last_name, email=email_id,password=password1,username=username) user.save() return redirect("/") else: messages.info(request,"Passwords Not Matching!") return redirect("registeruser.html") return redirect("/") else: return render(request,'registeruser.html') def RegisterDoctor(request): if request.method =="POST": first_name = request.POST.get("finame") last_name = request.POST.get("laname") email = request.POST.get("emailid") password1 = request.POST.get("userpassword") password2 = request.POST.get("conpassword") username = request.POST.get("username") phone_no = request.POST.get("phno") exp = request.POST.get("docexp") if password1==password2: if Doctor.objects.filter(email=email).exists(): messages.info(request,"This Email ID is already Registered!") return redirect("registerdoctor.html") else: if Doctor.objects.filter(username=username).exists(): messages.info(request,"Username taken!") return redirect("registerdoctor.html") else: user = Doctor.objects.create_user(first_name=first_name,last_name=last_name, email=email_id,password=password1,username=username,experience=exp,phone_no=phone_no) user.save() return redirect("/") else: messages.info(request,"Passwords Not Matching!") return redirect("registerdoctor.html") return redirect("/") else: return render(request,'registerdoctor.html') models.py from … -
How do I get the value of CharField() during instansiation?
I want to pass model fields values as arguments to another field. trademark_class.get_default() method is close to what I want, but I do not want solely the default value. I am also unable to use __dict__.['trademark_class'] in this case as I need a 'this' reference to the class and do not know the proper way to achieve that for this case. class Form_33_Model(models.Model): trademark_number = models.CharField(default='default number', max_length=30) trademark_class = models.CharField(default='default class', max_length=30) trademark_date = models.DateField(default=datetime.date.today) html = models.TextField(default=Form33StringClass(trademark_class=trademark_class.get_default(), trademark_number=trademark_number.get_default()).form_33_string) Instead of the default value only, I would like to get either the actual value of the Charfield or its default value. So something like : trademark_class.get_current_value_or_default() would be ideal for what I want. -
can i search from multi database in my model using django?
i have this code and work perfect .. but i want search in all my models how to do that ? any idea for that ? mycode Models.py: class OpratingSystems(models.Model): # def etc .. class AndroidGames(models.Model): # def etc .. class Antivirus(models.Model): # def etc .. class AndroidApks(models.Model): # def etc .. class PCgames(models.Model): # def etc .. class PCprogram(models.Model): # def etc .. class Homepage(models.Model): # def etc .. Views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: lookups= Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query) results= Homepage.objects.filter(lookups).distinct() context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') html page : {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h1> <small> Results for </small><b>{{ request.GET.q }}</b> : </h1> <br/><br/> {% for result in results %} <label id="label_main_app"> <img id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="170" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} <br> <br> <a href="{{ result.page_url }}" type="button" class="btn btn-primary"><big> See More & Download </big> </a> </p> </label> {% endfor %} {% else %} <h3> No results for this search </h3> {% endif %} {% endif %} this … -
Scheduling Emails with Django?
I want to schedule emails using Django. Example ---> I want to send registered users their shopping cart information everyday at 5:00 P.M. How would I do this using Django? I have read a lot of articles on this problem but none of them have a definite solution. I don't want to implement a workaround. Whats the proper way of implementing this? Can this be done within my Django project or do I have to use some third-party service? If possible, please share some code. Otherwise, details on how I can implement this will do. -
html table search using <a>
<div id="changelist-filter"> <h2>SEARCH BY:</h2> <h3> By Student Users </h3> <ul id="myUL"> <li class="selected"> <li> <a href="?Student_Users__id__exact=6" title="" id="myInput" onclick="myFunction()">Mark Joshua</a></li> <li> <a href="?Student_Users__id__exact=5" title="">Bea mae</a></li> <li> <a href="?Student_Users__id__exact=4" title="Marvin Salvahan Makalintal">John Mark</a></li> </ul> </div> <table id="result_list"> {% for student in studentsEnrollmentRecord %} <tr> <td class="action-checkbox"></td> <th class="field-lrn">{{student.Student_Users.lrn}}</th> <td class="field-Student_Users nowrap">{{student.Student_Users}}</td> <td class="field-School_Year nowrap">{{student.School_Year}}</td> <td class="field-Courses nowrap">{{student.Courses}}</td> <td class="field-Section nowrap">{{student.Section}}</td> <td class="field-Payment_Type nowrap">{{student.Payment_Type}}</td> <td class="field-Education_Levels nowrap">{{student.Education_Levels}}</td></tr> </table> <script> function myFunction() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("result_list"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> I have this code in my html, I just want if the user click the "Mark Joshua" it will search to the table if it is exist or not, please help me. -
Remember number of items as the previous one entered in form if no number of items is inputed from post
I have a form accepting the number of items to be listed on the page. I have implemented this form in a template (lets say it show.html).As the page is called initially it doesn't accept any value so i display the 5 list items by default.But the trouble comes as i am using the pagination . The pagination doesn't have any relation with form so when i click next in pagination the default value which is set by default( ie 5 in this case) when no post action is called is getting executed.My requirement is such that (at first i display 5 items).Then when i give value to the input box it must be remembered and this value must used to do the number of list items until and unless i change the number of items in the list. view def show(request): category_list= Category.objects.all() count= request.POST.get('noofitems',5) //number of items is 2 if no post request is send paginator = Paginator(category_list, count) # Show 25 contacts per page page = request.GET.get('page') categories = paginator.get_page(page) return render(request,"show.html",{'category':categories}) Form ------- <form action="/show" method="post"> {% csrf_token %} <label >Number of items </label> <input type="text" name="noofitems" /> <input type="submit" value="OK"/> </form> -
build Filter using Django RestFramework and Angular fronted
i try build a filter for my fronted Angular from Django backend, or how i can build filter using restframework_filter please people help , i have this in the backend viewset.py from snippets.models import Snippet from .serializers import SnippetSerializer from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from django_filters import rest_framework as filters class SnippetFilter(filters.FilterSet): class Meta: model = Snippet fields = { 'title': ['icontains'], 'created': ['iexact', 'lte', 'gte'], } class SnippetViewSet(viewsets.ModelViewSet): queryset = Snippet.objects.all() serializer_class = SnippetSerializer filterset_class = SnippetFilter @action(methods=['get'], detail=False) def newest(self, request): newest = self.get_queryset().order_by('created').last() serializer = self.get_serializer_class()(newest) return Response(serializer.data) -
Reconciling Global and Virtual uWSGI installs
Deploying Django backend to an Ubuntu 18.04 AWS EC2. uWSGI, NGINX, and Django (everything) works fine when I launch from my pipenv shell's virtual environment. When I try to use a global uWSGI install for automated startup, uWSGI fails with the apparently common "module not found" error. Ubuntu system python is 2.7.15. My app runs 3.7.3 and runs virtual install of uWSGI compiled with 3.7.3. I compiled a python3 uWSGI plugin from here: https://www.paulox.net/2019/03/13/how-to-use-uwsgi-with-python-3-7-in-ubuntu-18-x/ It fires, but still reports using python 2.7 (see example below). I built an .ini and I've tried so many different combinations of settings, I lost track of which ones. I've tried setting the virtual environment in python path twice. I've tried setting different uWSGI binaries. I've adjusted permissions. Here is what it currently looks like: [uwsgi] pythonpath=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9-/lib/python3.7/site-packages pythonpath=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9-/lib/python3.7/site-packages plugins=python37 binary-path=/usr/bin/uwsgi virtualenv=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9- pythonpath=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9-/lib/python3.7/site-packages chdir=/home/dpcii/tube-backend-django/ module=video_backend.wsgi:application home=/home/dpcii/.local/share/virtualenvs/tube-backend-django-S2uZEC9- master=false processes=10 threads=2 socket=video_backend.sock chmod-socket=666 vacuum=true When I fire up the Emperor using global (instead of python environment) uWSGI executable, this is what I get: *** Starting uWSGI 2.0.15-debian (64bit) on [Mon Oct 28 12:57:50 2019] *** compiled with version: 7.3.0 on 28 September 2018 15:41:15 os: Linux-4.15.0-1051-aws #53-Ubuntu SMP Wed Sep 18 13:35:53 UTC 2019 nodename: ip-172-30-0-12 machine: x86_64 … -
Adding tests and testing django-polls as its own package
Django newb here who recently finished the tutorial on the Django website. I was able to follow all 7 parts and then in the advanced tutorial I made the polls app its own package. Going through the 7 parts in order means that you test the polls app while it is still part of the overall django project and uses the project's settings with no issue. So I had no problem testing the polls app. Now that I've made the polls app into its own separate package, I'm confused as to how to test it exactly. Let me explain. In part 5 I was able to test the polls app while it was still inside the mysite project. To do so, I would run python manage.py test polls from the mysite directory, and that manage.py file contained the line os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings'). In other words, the polls app testing relied on the general project's settings at mysite/mysite/settings.py. Then, like I said, eventually the polls app became its own package (as instructed by the advanced tutorial). I was able to separate out everything related to the polls app and everything has been fine. Except now I decided to go back and add … -
Django - How to re-render a page to display data based on a form's field?
I have a form in which the first field is the User's ID #. What I'm trying to achieve is displaying the name on top of the field where they enter they number but I'm not sure how to do this. I was thinking about maybe somehow refreshing the page once the user tabs/clicks out of the field, but I don't know if there would be a more efficient way that could render in real time, in case the user fills out other fields before their ID# field. Currently, I have this in my views to get the User's name based on their #, but I'm not sure how to use this in the html part, or if something else needs to be modified too views.py def get_e_name(request): e_number = request.POST.get('e_number') e = Saved.objects.get(a_number=e_number) e_name = e.saved_name return e_name -
Django can not create test databse using MySQL
I'm developing a large Django project and I'm beginning to write some tests. But I ran into a problem when running them. When I run python manage.py test I get the following error: $ project/ python manage.py test project/env/lib/python3.7/site-packages/django/db/models/base.py:319: RuntimeWarning: Model 'accounts.manager' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class) Creating test database for alias 'default'... Got an error creating the test database: (1007, "Can't create database 'test_partyadvisor'; database exists") Type 'yes' if you would like to try deleting the test database 'test_partyadvisor', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "project/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "project/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "project/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 312, in _query db.query(q) File "project/env/lib/python3.7/site-packages/MySQLdb/connections.py", line 224, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1170, "BLOB/TEXT column 'content' used in key specification without a key length") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line … -
Cannot Install psycopg2 in virtualenv in windows
I am trying to install Psycopg2 in my VirtualEnv, initially i was facing error it could not find pg_config.exe and i solved it by adding complete path in PATH. But then it gave error Microsoft Visual C++ 14.0 is required. To remove this i have Installed VC_redist.x64 VC_redist.x86. I have also installed C++ development modules in VS community. but it still gives this Error. My Environment: Windows 10 SL, Python 3.8.0, VirtualEnv 16.7.7, pip 19.3.1 psycopgmodule.obj : error LNK2001: unresolved external symbol _PQfreemem psycopgmodule.obj : error LNK2001: unresolved external symbol _PQencryptPasswordConn psycopgmodule.obj : error LNK2001: unresolved external symbol _PQencryptPassword psycopgmodule.obj : error LNK2001: unresolved external symbol _PQinitOpenSSL psycopgmodule.obj : error LNK2001: unresolved external symbol _PQconninfoParse psycopgmodule.obj : error LNK2001: unresolved external symbol _PQerrorMessage psycopgmodule.obj : error LNK2001: unresolved external symbol _PQlibVersion psycopgmodule.obj : error LNK2001: unresolved external symbol _PQconninfoFree green.obj : error LNK2001: unresolved external symbol _PQclear pqpath.obj : error LNK2001: unresolved external symbol _PQbinaryTuples pqpath.obj : error LNK2001: unresolved external symbol _PQsetnonblocking pqpath.obj : error LNK2001: unresolved external symbol _PQgetvalue pqpath.obj : error LNK2001: unresolved external symbol _PQresultStatus pqpath.obj : error LNK2001: unresolved external symbol _PQoidValue pqpath.obj : error LNK2001: unresolved external symbol _PQcmdStatus pqpath.obj : error LNK2001: unresolved … -
How to dynamically pass in Model class name in Django view
"""Please, I have created some model classes in my django app.models. I want to access to objects of any of the models in my views based on request. My view looks like this: def profile(request, course): Course_name = course Contents = model.objects.get() context = {obj: contents} return render(request, "pro.html", context) """My question is, I want to replace model in model.objects.get() with the variable "course_name" But am getting this error, 'str' object has no attribute 'objects' Please Help"""