Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where is this mystery cache in Apache?
I have a django app running in a virtualenv on Windows 10 WSL1 (Ubuntu). The python version is 3.6.8. When using the django development web server, python manage.py runserver, everything is fine. I access that with http://localhost:8000/<my app name>/ But when using apache2, version 2.4.29, months-old javascript code shows up in the browser debugger in a VMxxx file, though I haven't yet found an eval() that's generating that. Also, old server-side code shows up: an old javascript error that resulted from the django python code sending the wrong content type - a bug that was fixed a couple of weeks ago. I'm accessing apache2 with http://localhost/<my app name>/ I disabled mod_cache: a2dismod cache Module cache already disabled. Also ran htcacheclean -r -l1k and manually looked at the page cache directory, which was empty. I clear the Chrome cache on every page load, but also get the same errors when using a different browser (Firefox) that wasn't even installed when this old code that's showing up was written. I put in a HTTP header to request no caching: <meta http-equiv="Cache-Control" content="no-store" /> The closest thing to a cache that I have configured in Django settings is SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db', no CACHES … -
Model to Insert multiple values for the same field?
The goal is to put multiple status_code and event_code for 1 instruction. So 1 instruction can be associated with one or multiple scrap_code or event_code. But a single scrap_code or event_code cannot have more than 1 instruction. class Instruction(models.Model): name = models.CharField(max_length=100) I have made 2 separate models for scrap_code and event_code class ScrapCodeInstruction(models.Model): scrap_code = models.IntegerField() instruction = models.ForeignKey(Instruction) class EventCodeInstruction(models.Model): event_code = models.IntegerField() instruction = models.ForeignKey(Instruction) I need to register it in admin in the way that for 1 instruction there can be multiple scrap_code or event_code. Also scrap_code(s) and event_code(s) can share the same Instruction. I can use InlineModelAdmin like TabularInline or StackedInline in admin. But it would be great if the values come as comma separated rather than Tabular of Stacked. How can I make it as comma separated in admin?(2nd way to have multiple fields together) -
Django 'trans' Tag: display {% trans 'test' %} instead of test
I try to implement internationalization on my Django project I have installed gettext and run makemessages and compilemessage that create my 2 .po and .mo files base.html {% load static i18n %} {% load static %} test_translation.html {% extends 'layouts/base.html' %} {% load i18n %} ... <h2>{% trans 'test translation' %}</h2> but it does not work as it seem 'trans' tag seem not to be interpreted in fact, browser display {% trans 'test translation' %} (with the bracket and %) instead of test translation -
Consistent Wagtail menus showing parents, children and siblings
I have a simple Wagtail site made of several pages of type HomePage I want use Wagtails in-built menu system for all pages created from the HomePage model and home_page.html template. All the pages have Show in menus: selected. Using this guide here, I have created the following get_context method : class HomePage(Page, Dreamer, Seo): def get_context(self, request): context = super(HomePage, self).get_context(request) context['menuitems'] = self.get_children().filter(live=True, show_in_menus=True) ... and placed the following code in my template : {% for menu in menuitems %} <a class="nav-item nav-link active" href="{{menu.url}}">{{menu.title}}</a> {% endfor %} Other than the root HomePage not showing at all, the menu displays the child pages, until I follow a link to a child page when all the links disappear (because the pages are no longer children). Question: how do I get the menu show the root HomePage and also the child pages even when I am on a sibling, parent or child page? Any help greatly received. -
Endpoints sharing part of an URL
I'm currently building an API and I want to have two viewsets. One related to my User model, and one single route to verify a User email (you POST the currently-valid token to the endpoint). So it looks like this: UserViewSet, which allows POST, GET, PUT, PATCH, DELETE VerifyUserViewSet, which only allows POST In my router, here's my config: router = routers.DefaultRouter() router.register("users", UserViewSet, "users") router.register("users/verify", VerifyUserViewset, "users/verify") My problem is as follows: "users/verify" allows a GET request (when it shouldn't) because it is targeting the "users" endpoint with "request" as the user id. If I change the order in my router, then "users" only accept POST because the endpoints targets "users/verify". This seems to be happening because they share the same url part "users". Is there a way to bypass this behavior so that they don't overlap without changing the endpoints url? Thanks -
automatic field update when GET object is called. is it right and possible? drf
What is the best way to implement the next situation: I need that when some object endpoint is GET called then isCalled change to True. for example when api/objects/1 my model: class Object (models.Model): someObject = models.ForeignKey(User, on_delete=models.CASCADE) isCalled = models.BooleanField(default=False) # dateCalled = models.DateTimeField(auto_now=True, null=True) my views.py: class SingleMessageView(generics.RetrieveUpdateDestroyAPIView): queryset = Message.objects.all() serializer_class = MessageSerializer # def get(self)? : #function to implement the solution should be here? is it possible? what is the most efficient way to implement it and where (views.py/ serializers.py) to put the solution? THANKS!! -
Login with Email and Password in Django
I Want to login using Email and Password in Djnago so I took help from Youtube and Other StackOverflow's answers but It can't work. Problem : I can't find out any problem in my code(given below) but IT IS NOT WORKING!! backends.py(inside 'account' named app) from django.contrib.auth.models import User class EmailBackend(object): def authenticate(self, username=None, password=None, **kwargs): try: user = User.object.get(email=username) except User.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None views.py(inside 'page' named app) def login(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] user = authenticate(username=email, password=password) if user is not None: print("You are Logged in") else: print("Please Enter Valid Email or Password") return render(request, "page/login.html") settings.py AUTHENTICATION_BACKENDS = [ 'account.backends.EmailBackend' ] Note: It works good with default username and password authentication. Please help me to solve this problem.. Thank You!! -
User object .save() does not save after upgrading django 2.1 => 2.2
I am experiencing a very strange bug where I can create and save a User from the django shell, but when I exit and reopen the shell, the User disappears. This is in a prod-like environment with a proper backing DB. The issue goes away if I downgrade Django 2.2 -> 2.1. >>> u = User(id=123131323122, first_name='hi', last_name='sup', email='test@mysupertest.com', birthdate='2000-01-01') >>> u.set_password('foobar') >>> u.save() >>> User.objects.count() 1059790 >>> u.refresh_from_db() >>> u <User: test@mysupertest.com> >>> now exiting InteractiveConsole... myuser$ python manage.py shell Python 3.6.9 (default, Nov 23 2019, 07:02:27) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from mypackage.models import User >>> User.objects.count() 1059789 >>> User.objects.get(email='test@mysupertest.com') Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name mypackage.models.User.DoesNotExist: User matching query does not exist. -
Django, add table row using javascript
How to if the teacher select Items (4) using JavaScript, as you can see, the table row adjust, it depends on what Items that the user select, please help me guys here's the example: if the user select Items (3) here is my html <table class="tableattrib" id="myTables"> <tr> <td colspan="1" class="tdhead1">Class</td> <td colspan="20" class="tdcell"> &nbsp;&nbsp; <select> <option>Grading Categories</option> </select>&nbsp;&nbsp; <select onchange="myFunction()"> <option>Items</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select>&nbsp;&nbsp; <select> <option>Section</option> </select> </td> </tr> <tr> <td class="tdnb" colspan="21"><input id="myInput" type="text" placeholder="Search Student" class="search"></td> </tr> <tr> <td colspan="1" class="tdhead">Student Name</td> <td class="tdcell1"><input type="text" name="" id="datepicker" placeholder="mm/dd/yyyy" title="Quiz Date"/></td> <td class="tdcell1"><input type="text" name="" id="datepicker1" placeholder="mm/dd/yyyy" title="Quiz Date"/></td> <td class="tdcell1"><input type="text" name="" id="datepicker2" placeholder="mm/dd/yyyy" title="Quiz Date"/></td> <td class="tdcell2">Average</td> </tr> <tbody id="myTable"> <tr id="myRow"> <td colspan="1" class="tdcell">Marvin Makalintal</td> <td class="tdcell1"><input type="text" name=""/></td> <td class="tdcell1"><input type="text" name=""/></td> <td class="tdcell1"><input type="text" name=""/></td> <td class="tdcell1"><input type="text" name=""/></td> </tr> <tr> <td class="tdbtn" colspan="21"><button type="button" class="save">&plus;&nbsp;Save</button> &nbsp;<button type="button" class="save">&check;&nbsp;Finalize</button></td> </tr> </tbody> </table> </body> <script> function myFunction() { var row = document.getElementById("myRow"); var x = row.insertCell(1); x.innerHTML = "New cell"; } </script> -
Why is VS Code debugger not working for Django mutations?
I'm trying to debug django in VS Code. Breakpoints work when the startup code runs, but when I execute a mutation, it doesn't. Anyone knows why that could be? this is what my configuration file looks like: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Django: Runserver", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", ], "django": true, } ] } Any ideas or pointers are highly appreciated. -
remove % symbol in Django JavaScript Uncaught SyntaxError: Unexpected token ']'
Hi i am a newbie please help. I can't remove this % symbol for high charts to use it, how can i make sure its not a string and just a float WITHOUT THE %. please help series: [{ name:'Top Priority Services', data: [] },{ name:'Central Wiki Service', data: [99.75%] },{ -
django shop, add_to_cart, counter product
I have a big problem. I create a shop without payment support. Only display of ordered products in the administration panel. Each user has a different product price. I would like to add the option to add products to 'Cart'. Product name, product price multiplied by its quantity and total payment. Unfortunately, my code does not work, I'm already slightly lost in it. My file offers/models.py class Product(models.Model): product_name = models.CharField(max_length=100) category = models.CharField(max_length=50) weight = models.FloatField() description = models.TextField(blank=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.product_name class UserProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product_name = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField() is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return str(self.user.username) if self.user.username else '' class OrderProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) quantity = models.IntegerField(default=1) def __str__(self): return str(self.product) if self.product else '' class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) products = models.ManyToManyField(OrderProduct) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def get_total(self): total = 0 for order_product in self.products.all(): total += order_product.get_final_price() return total def __str__(self): return str(self.user.username) if self.user.username else '' And my views.py It's mainly about the function add_to_cart def index(request): context = { … -
Django timesince filter showing '0 minutes' when it is less than one day. How can I fix this?
I am trying to show time since I added a post with following code - {{ listing.list_date|timesince }} and it is showing "0 minutes". But it is showing correctly when it is more than one day. How can I show times less than one day with hours and minutes? -
Django Query Issue (int() argument must be a string, a bytes-like object or a number, not 'BoundField')
So I'm having issues with a query i am running on views.py . Basically on my html page there is a drop down list that has all classroom lists, when you select a class from the drop down list, all the students on the page change to that particular class. Problem with the query is the drop down menu displays the name of the class in a string format and it wants the ID number of class to pass through. Here is my code, I have no idea how to fix this. I appreciate the help. Thank you in advance. Here is the error i am getting : int() argument must be a string, a bytes-like object or a number, not 'BoundField' views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import NhsPointsForm, K8PointsForm from .models import K8Points , NhsPoints, TeacherClass, Student from django.db.models import Sum import datetime @login_required def Nhs_Points(request): if request.method == 'POST': form = NhsPointsForm(request.POST) if form.is_valid(): #username = form.cleaned_data.get('username') points = form.save(commit=False) points.save() return render(request, 'points/nhs_points.html', {'form': form}) else: form = NhsPointsForm() return render(request, 'points/nhs_points.html', {'form': form}) @login_required def K8_Points(request): if request.method == 'POST': form = K8PointsForm(request.POST) if form.is_valid(): … -
How to tell which django forms widget has triggered a POST?
In the following scenario (code in forms.py): class MyForm(forms.Form): option_one = forms.CharField(label='Pick 1st option', widget=forms.Select(attrs={'onChange': 'form.submit();'})) option_two = forms.CharField(label='Pick 2nd option', widget=forms.Select(attrs={'onChange': 'form.submit();'})) The request.POST dictionary will contain both option_one and option_two keys and their values regardless of which onChange event triggered the POST (unlike submit button where the key is only present if it caused the POST). How can I tell which widget actually changed to trigger the POST so that I can work with that info in views.py? -
wrap_socket() got an unexpected keyword argument '_context'
I'm currently trying to put in production a django project using nginx and gunicorn for the first time. The project consist on a register page in wich the user access, fills a form and the data is used to make a request to another server to create a profile using the data taken from the form of my app. To do such task i have the following libraries: requests 2.22.0 gunicorn 20.0.4 eventlet 0.25.1 (with greenlet 0.4.15) The project was entirely tested and functional in a testing enviroment inside an ubuntu 18.04 virtual machine. Now the server in production is a Debian 10. Every web page of the project works corretly and so does the django admin page. The thing is that when i try to fill the form to actually register on the databese of the second server it returns the following error: Environment: Request Method: POST Request URL: http://reg.rocstar.tv/register/customer/ Django Version: 2.2.7 Python Version: 3.7.5 Installed Applications: ['reg.apps.RegConfig', 'import_export', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/rocstar/.local/share/virtualenvs/register-page-Z_TgQ-vY/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/rocstar/.local/share/virtualenvs/register-page-Z_TgQ-vY/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/rocstar/.local/share/virtualenvs/register-page-Z_TgQ-vY/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. … -
How to connect django db.sqlite database using python sqlite module
def getConnection(database_type): properties = Settings.getProperty() if database_type.upper() == "SQLITE": DatabaseConnectionFactory.connection = sqlite3.connect(properties.get("DATABASE","SQLITE_PATH")) print("Database Connection created successfully") path in property file - C:\Users\vipin\PycharmProjects\PythonBehaveFramework\db.sqlite3 -
Django ensure you only use CORS Simple Request
My Django app is contacting another server that has OPTIONS Method disabled. As a result CORS rejects the PREFLIGHT request, which should be valid GET request (it's only a basic redirect with HttpResponseRedirect). How do I ensure that I'm only sending CORS headers valid for a Simple request so the preflight never occurs? I'm basing my understanding of CORS simple / preflight requests off this article: https://dev.to/effingkay/cors-preflighted-requests--options-method-3024 -
Website home page prompts to download file
I am facing a irritating issue with my django website hosted in Heroku. It was running well earlier but now when someone click xyz.com, it prompts to download a file which contain source of the home page. other pages like xyz.com/about working fine. Even in Localhost facing same issue. I tried deleting everything from home page and still same issue. So I think home page source code is not causing this. Its been 3 days I am unable to fix it. Anyone please help what might be the reason for it? -
What uses the memory of my python process?
If I execute the Python interpreter it needs roughly 111 MByte: >>> import psutil >>> psutil.Process().memory_info() pmem(rss=19451904, vms=111677440, shared=6905856, text=4096, lib=0, data=12062720, dirty=0) After importing django it uses 641 MByte >>> import django >>> django.setup() >>> psutil.Process().memory_info() pmem(rss=188219392, vms=641904640, shared=27406336, text=4096, lib=0, data=284606464, dirty=0) And the WSGI process (which has already executed some http requests) 919 MByte: >>> psutil.Process(13843).memory_info() pmem(rss=228777984, vms=919306240, shared=16076800, text=610304, lib=0, data=485842944, dirty=0) I think that's too much. What can I do to investigate this in more detail? What occupies the memory? -
Post JS variables to Django view and display as context variables in separate template
I'm trying to achieve three things: collect some user input using standard HTML forms in one template (questions.html below); post that input to my views.py; and finally display that input as context variables in a separate template (results.html below). Once I get this to work, I'll do some processing of the input in the views.py before passing some output on as a context variable - but first I need to figure out the basic principle of moving from user input in one template --> views.py --> context variables in another template. Also, I'm deliberately doing this without touching any database, since I don't want to save any user data. Here's what I have for my questions.html, collecting age and level of education: <script type="text/javascript"> $(document).ready(function(){ $('#submit_answers').submit(function (event) { var user_age = document.getElementById("age-choice").value; var user_education = document.getElementById("education-choice").value; $.ajax({ type:"POST", url:"{% url 'results' %}", data : { 'age': user_age, 'education': user_education, 'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val() }, }) } )}); </script> <p>Please answer the following questions:</p> <p>What is your age?</p> <form action="" method="GET" id="age-dropdown"> {% csrf_token %} <select class="browser-default custom-select" id="age-choice"> <option value="18-30">18-30</option> <option value="30-40">30-40</option> <option value="40-50">40-50</option> <option value="50-65">50-65</option> <option value="65-100">Over 65</option> </select> </form> <p>What is your highest level of education?</p> <form action="" method="GET" id="education-dropdown"> {% … -
File manipulation in Django models.py
I am building a Django app that saves an .stl file passed using a formulary and my goal is to open the file, extract some information with a script that is already tested, and save this information in the same register that the file. I am doing this: def informationGeneration(stl_route, *args, **kwargs): # scripts that generates the information class Piece(models.Model): """Piece model.""" # ... file = models.FileField(upload_to='pieces/files', default='NA') # ... information = models.IntegerField(default=0) def save(self, *args, **kwargs): """Overriding the save method.""" self.information = informationGeneration(self.file) super().save(*args, **kwargs) def __str__(self): # ... The problem is that when I try to save a new instance, numpy-stl detects an error, self.file is not the .stl file, is an alement of the formulary. How can I pass the file and not the route? -
How to make a form in django that can hold a list of questions, and submit them at once
Is there a way to create a form that can hold a list of data in Django, as it is with django-rest serializers? The form must look like this -
How to fix Django 'Can't find msguniq' error
I try to use internationalization in my Django project I follow a tutorial: https://www.youtube.com/watch?v=xI97sLMd1rM but author skip the configuration for gettext I have installed gettext librairie and seems to be OK: xgettext --session in a prompt confirm it is installed And I follow beginning of the tutorial settings.py LOCALE_PATHS = [ os.path.join(BASE_DIR,'locale'), ] base.html {% load static i18n %} {% load static %} # don't know if should import twice static test_translation.html {% extends 'layouts/base.html' %} {% load i18n %} h2>{% trans "A test of translation" %}</h2> however, when I run in my env (env) PS myproject > django-admin makemessages -l fr I got the following error: CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. Do I need to install somethings else? -
Django ModelForms - Display different choice than what will be saved
From the title this sounds like something I shouldn't wanna do. But I have two models. Both have AutoField PK's and model B has a foreign key ID for A. In my form to create B, I have all of B's fields including the foreign key ID. This simply shows up to the user as something like "B Object 1". This is absolutely useless to me as when I have more items I'd rather have a name to identify it to the user. So my question is: can I substitute A.name in place of the foreign key ID, but still save just the foreign key when it comes to saving the model?