Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to grant atomicity on clean() method in django Models
I'm currently using django's clean() method to implement custom validations in a Model. A have a DB for example that is 1:m and have the following structure: | Id | Foreign Key | Date | |:-----------|------------:|:------------:| | 1 | 1 | 20-11-2019 | | 2 | 1 | None | The custom validation grants that for the same Foreign Key, there is only one row where date = None As save() is not called in this method, @transaction.atomic would not work, hence, what is the best way to grant atomicity with this method? I'm using python 3.7, django 2.2.6 and Postgresql -
Django Cron, execute def from views
I have a problem. I needto implement a function that will be called cyclically this cron.py: from django_cron import CronJobBase, Schedule from django.shortcuts import get_object_or_404, render, redirect from django.http import HttpResponse, HttpResponseRedirect, Http404 class MyCronJob(CronJobBase): RUN_EVERY_MINS = 60 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'CRM.my_cron_job' def do(self): return redirect('dashboard/dashgenerate/') dashgenerate is a def from another app in project: def dashgenerate(request): ..... -
ModuleNotFoundError: No module named <module_name> although module was installed
I'm trying to run server for my django app, and I've used TinyMCE editor for admin panel. Although I've installed it with command pip3 install django-tinymce application returns me such error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'tinymce' -
How do I change the default Django engine database from db.sqlite3 to a mysql database populated with test data?
This is my first time doing this so please bear with me. What I am trying to do: Change the 'DATABASES' setting in my 'settings.py' from the 'ENGINE: 'django.db.backends.sqlite3' to a pre-populated mysql database with test username data. More specifically, I want to change the default django database from db.sqlite to a mysql database. The mysql database I am trying to use instead of the default already has user information which I want to use and test. What I have done so far: I have already authenticated a couple of users(using the default db.sqlite3) to be able to add blog posts on my website which is currently hosted on a domain. What I am not sure about: Was changing the settings.py DATABASE default something I should have done at the very beginning ?? Or can I change it at any time without risking previously made changes? Does replacing the DATABASE default settings with something like the one below affect already existing user data ?? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '{{projectName}}', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '3306', } } What is the proper way to go about this given that I already have my blog website … -
How to route to a url based on data entered in Django form?
At first , I would like to take an integer input from user . After getting the input , I would like to go to the url based on what the user has entered . However , I am not able to implement it . Here's my urls.py file: urls.py urlpatterns = [ path('',views.page1), re_path(r'^form/(?P<data>[1-4]{1})',views.page2), ] Here's my views.py file: views.py from django.shortcuts import render from .forms import CustomForm1 from django.http import HttpResponse import requests # Create your views here. def page1(request): if request.method == 'POST': form = CutsomForm1(request.POST) if form.is_valid(): data = form.cleaned_data['data'] else: form = CustomForm1 data = 0 return render(request,'homepage/base.html',{'form':form,'data':data}) This is my forms.py file: forms.py from django import forms class CustomForm1(forms.Form): data = forms.IntegerField(label='data',required=True) And here's the HTMl: HTML <form method="POST" action="form/{{ data }}"> {% csrf_token %} {{ form.as_p }} <ul class="actions"> <li><input type="submit" value="Send Message" class="primary" /></li> <li><input type="reset" value="Clear" /></li> </ul> </form> Initially , when the form is loaded , my data variable has value 0 , but I want to it get the value which is entered by user , hence , I can then route to the desired url as per the updated data variable which is passed as context . For … -
Django Webhook creates double database entries
I'm currently using Django to code a webhook application for google Dialogflow. It was working fine, I was basically done. For some reason, I now started encountering various randomly appearing problems, one of the worst being the following: Whenever the webhook executes the user account creation call, it creates a double-database entry, which crashes the program (because my .get suddenly returns multiple elements instead of a single user). I'm using the following simple models: # model to create user entries class TestUser(models.Model): name = models.CharField(max_length=200) userID = models.CharField(max_length=12, blank=True) registrationDate = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name # model to add watched movies to user class Movie(models.Model): username = models.ForeignKey(TestUser, on_delete=models.CASCADE) title = models.CharField(max_length=200, blank=True) genreID = models.IntegerField (blank=True) def __str__(self): return self.title def list_genre_id(self): return self.genreID The part that gets executed in my webhook while the problem occurs should be the following: if action == "account_creation": selection = req.get("queryResult").get("parameters").get("account_selection") if selection == "True": q = TestUser(name=f"{username}", userID=idgen()) q.save() userID = TestUser.objects.get(name=f"{username}").userID fullfillmenttext = {"fulfillment_text": "Alright, I created a new account for you! Would you like to add " "some of your favorite movies to your account?", "outputContexts": [ { "name": f"projects/nextflix-d48b9/agent/sessions/{userID}/contexts/create_add_movies", "lifespanCount": 1, "parameters": { "data": "{}" } }]} This … -
Django Custom Permissions not synced to DB
I am newbie to Python and Django. I am trying to addd custom permissions using Django documentation. I added new permissions to model meta data. class Project(models.Model): class Meta: permissions = [ ("create_project", "Can create project"), ("update_project", "Can update project"), ("view_project", "Can view project") ] Then I ran python3 manage.py makeintegrations [app_name] and output was app/migrations/0009_auto_20191209_1848.py - Change Meta options on project Then I ran python3 manage.py migrate [app_name] and output was Applying app.0009_auto_20191209_1848... OK But I do not see new permission added to auth_permission. I tried --run-syncdb option but that did not work as well. What I am doing wrong and how I can debug this issue? thanks, -
Django rest_ramework error "Object of type UserToken is not JSON serializable"
I use django_rest framework and do authorization manually. I use tokens, which I also generate myself. When trying to authorize an error occurs "Object of type UserToken is not JSON serializable". I know that there is a lot of what's wrong here, but still, what is the error? (password verification I will do later) My view class: class SinginUserView(generics.GenericAPIView): serializer_class = SigninUserSerializer model = get_user_model() def post(self, request): username = request.POST["username"] user_id = User.objects.get(username=username).id token = UserToken.objects.get(id=user_id) return Response({'token': token}) My Serializer class: class SigninUserSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = ("username", "password") -
Why does Django REST Framework PATCH add a list element but will not remove an element?
I'm writing a unit test for my /api/users/:id/ endpoint exposed using Django REST Framework. I know that PATCH works properly because the following test passes as expected: Successful Test: Add Group to User def test_add_group_to_user(self): self.client.login(username=self.admin.username, password=self.admin_password) url = f'/api/users/{self.user_a.id}/' groups_before = self.client.get(url).data['groups'] # Groups: [] self.client.patch(url, data={'groups': [self.group.id]}) groups_after = self.client.get(url).data['groups'] # Groups: [1] self.assertTrue(len(groups_after) == len(groups_before) + 1) However, when I attempt to remove the group from the user using the same PATCH endpoint, the response returns a 200 but the groups collection still contains the item. See the failing test below. Unsuccessful Test: Remove Group From User def test_remove_group_from_user(self): self.client.login(username=self.admin.username, password=self.admin_password) url = f'/api/users/{self.user_a.id}/' self.client.patch(url, data={'groups': [self.group.id]}) groups_before = self.client.get(url).data['groups'] # Groups: [1] self.assertTrue(self.group.id in groups_before) response = self.client.patch(url, data={'groups': [g for g in groups_before if g != self.group.id]}) groups_after = self.client.get(url).data['groups'] # Groups: [1] self.assertTrue(self.group.id not in groups_after) I know the list comprehension [g for g in groups_before if g != self.group_id] returns the expected value, [], and I have also tried passing [] directly into the PATCH data. Why won't PATCH update groups to the data I provide? -
Add custom log records in Django
I've added the following logging configuration to my Django App's settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } Now, I simply want to add some custom log records to one of my views in views.py, but it appears the logger is NOTSET, which means only levels of warning and higher are logged: import logging from django.http import JsonResponse logger = logging.getLogger(__name__) def testing(request): logger.info("Doesn't show...") logger.warning(f"Log Level: {logger.level} = {logging.getLevelName(logger.level)}") return JsonResponse({"Hello": "World"}) The snippet above logs the following: Log Level: 0 = NOTSET Am I doing something wrong? Why is the logger's level not set (even though I clearly set it in settings.py)? -
Django - save changes made to model objects and render when published
I am new to Django and working on my first project in Django. I am providing a simpler example for my application where - I have 3 different types of users for the application. Teacher's Assistant - Schedules/plans the timetable and courses for the teacher depending on day's agenda Teacher - approves the items on the agenda and marks if an item on the schedule is completed Student - views the schedule of an individual teacher Currently, I have this whole application ready with all its functionalities, where the assistant would create a timetable/schedule (ie., add/edit/delete various model objects which are subjects) for the teacher depending upon her courses and agenda for the class. Currently, when the assistant, makes changes to the schedule (such as deletes, or edits an existing model object) these changes directly update the model object. What I would want to achieve is that, only when the Assistant publishes the schedule, the teacher can approve and students should be able to view it, and the assistant should have his own version of the schedule where he can make changes and edits to it (These changes and edits should not be viewed by other two roles unless they … -
How to use Google Drive to save media files for a Django app that is deployed in Heroku?
Is it possible to use Google Drive to save all the media files (image files which users will upload) from a Django app? This app will be deployed in Heroku (free). I am also aware of Amazon S3 but I want to avoid it as its not free after 12 months. I noticed that after deploying the app in Heroku, the static images are loading fine (using whitenoise) but those which are uploaded using ImageField from a model are not loading. I do not have any experience with Google APIs or even with Heroku for that matter and I could not find much information on if this integration is possible. If yes, it would be really great if I can get more details on how to go about it. I am currently using the latest version of Django (V3.0) along with Python 3.7.5 (64 bit). -
How to transfer GeoQuerySet.distance(geom, **kwargs) from Django 1.8 to Django 3.0?
I found this example in the Django 1.8 documentation. And it’s very important for me to follow the same steps, but in Django 3.0 (or 2.2). class AustraliaCity(NamedModel): point = models.PointField() radius = models.IntegerField(default=10000) allowed_distance = models.FloatField(default=0.5) pnt = AustraliaCity.objects.get(name='Hobart').point for city in AustraliaCity.objects.distance(pnt): print(city.name, city.distance) But AustraliaCity.objects.distance(pnt) causes an error in Django 3.0. AttributeError: 'AustraliaCity' object has no attribute 'distance' I will be grateful for any advice. -
Is there a way to filter for more than one value in the same column of a table?
I am realy frustrated and don't know what to do. I build a Website, where you can filter for beverages with many parameters, for example for the name of an Item, for the brand usw... But I also want to add a checkbox field, where you can mark certain volumes and filter my database for them. So lets say, I want to filter by the name Cola, by brand Coca Cola and by Volume 0.7L and 1L. Now I want that all Items in my table get displayed, wich have the name Cola brand Coca Cola and wich have a volume of 0.7 liter and 1 liter This does not work, because I filter for two different values in one column, wich is not possible in this way, because the field "volume" cant be 0.7 and 1. qsf = Content.objects.all().filter(Q(products__icontains=Cola) & Q(volume=0.7) & Q(volume=1) & Q(brand=Coca Cola)) I cant use the or operator (|) eather, because than my filter don't work. This is like my 3 post, because I don't know how to solve this problem, I realy hope you guys can help me. -
Customizing JWT error exceptions using PyJWT library in django
How can I customize JWT exceptions in pyjwt? For instance normally in pyjwt the response that is returned when someone does not provide credentials would be: { "detail": "Authentication credentials were not provided." } But I want to customize the response to return something like this: { "success": False, "msg": "Authentication credentials were not provided.", "data": None } -
unique_for_date parameter for SlugField
First, I am reading a book on django and from it have created the following models.py (entire models.py included at the end, the two fields related to the question are here): slug = models.SlugField(max_length = 250, unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus we can retrieve single posts using date and slug publish = models.DateTimeField(default = timezone.now) Anyway, I have been searching online and have seen that you can use the unique_for_date parameter when creating a DateTimeField() but when it comes to using the parameter in a SlugField() I found one question asked on here almost ten years ago (How to create a unique_for_field slug in Django?) and so figured it wouldn't hurt to ask. If this can be done, can someone explain what that parameter is doing? Is this maybe something that is now obsolete in django? Thanks in advance. models.py: # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Pusblished'), ) title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus … -
django filling a text field based on a button it is redirected from
I am trying to create a project management app each user has multiple projects which he creates my projects app is as follows class projectsmodel(models.Model): added_by = models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True,on_delete=models.SET_NULL) projects=models.CharField(max_length=300) def save_model(self,request,obj,form,change): obj.added_by=request.User super().save_model(request,obj,form,change) def __str__(self): return self.projects I filtered the projects which the user has created now i have my models.py file for boq app as follows Projects html file is as follows <tbody> <tr> <td style="vertical-align: top;">Projects<br> </td> <td>Open</td> <td>Edit</td> <td>Delete</td> </tr> {% for projectsmodel in projects1 %} <tr> <td>{{projectsmodel.projects}}</td> <td><button class="btn btn-warning">Open</button></button> <td><a href="{% url 'projectsedit' pk=projectsmodel.pk %}"<button class="btn btn-warning">Edit</button></a></button> <td><a href="{% url 'projectsdelete' pk=projectsmodel.pk %}"<button class="btn btn-warning">Delete</button></a></button> </td> </tr> {% endfor %} Every project has a home page whose template is as follows {% block content %} Project name : <br> Planned start :<br> Planned finish :<br> Actual start:<br> Actual finish :<br> Planned cost:<br> Expected cost of completion:<br> Percentage completion till date :<br> Cost incurred till date :<br> {% endblock %} When a user goes to the projects list and click a open button corresponding to a project then the homepage should be loaded with project name autofilled from corresponding field of the button he clicked -
Django: return list/tuple of element.id and min(element.price) from chunks of queryset
I've a cart_detail view that will be used to offer 3x2 discounts. So I'm making chunks of 3 elements from every element in my queryset. Using: def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n] Queryset and Chunks generated: pack_items = PackItem.objects.filter(cart=cart) pack_items_grouped_by_3 = chunks(pack_items, 3) Now, from every chunk I need to return a list or tuple with the min price of all 3 elements and the ID of the element with the min price. I can return the min price of every chunk, but how to return also the ID of the pack from that chunk that has the min price? for e in pack_items_grouped_by_3: product_with_min_price = min(pack.pack.price for pack in e) #product_id = e.index(min(pack.pack.price for pack in e)) #print(product_id) Error: In the for loop above I've tried: product_id = e.index(min(pack.pack.price for pack in e)) print(product_id) But Erro says: ValueError at /carrito_de_compras/ 10 is not in list 10 is the min value for every chunk, in this case, maybe in the future 2 items can have price of 10 and one price of 8, and 8 would be the min price. -
How to check if a child in firebase database exists using Django?
I tried the following code, but it throws attribute error ''Database' object has no attribute 'exists''. I need to check if the number exists in the database or not since I want the existing users to log in using number and password. from django.shortcuts import render from django.views import View from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect import pyrebase from django.contrib import auth import json import requests from . import services from .models import Product authe = services.firebase_key().auth() database = services.firebase_key().database() def Login(request): return render(request, "Login.html") def postsign(request): data = services.get_products() print(data) context = {'data': data} number = request.POST.get('number') password = request.POST.get("password") if database.child("users").child(number).exists(): user = database.child("users").child(number).get().val() if user['number'] == number: if user['password'] == password: return render(request,"Welcome.html",context) -
Django says SECRET_KEY must not be empty
I imported a Django project from a repo, and when I try to make the migrations with python manage.py makemigrations, I get the following exception: File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\conf\__init__.py", line 161, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. After looking online, I read that adding from base import * to __init__.py could solve it, but it just sends a different error: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\conf\urls\static.py", line 22, in static raise ImproperlyConfigured("Empty static prefix not permitted") django.core.exceptions.ImproperlyConfigured: Empty static prefix not permitted My 'base.py' settings do have SECRET_KEY = 'my_key_value' , and my 'local.py' settings first line is from.base import *, and it doesn't override the SECRET_KEY, so I don't know why it says the SECRET_KEY is empty. I do not see any other settings through the project, so I don't know where else to look, I'm new to django, so I'm a bit lost here and have been stuck for a few days. -
Run a test on a Python/Django cronjob
I am trying to create some tests for my Django cronjobs. I have a file called cronjob.py: from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() from mailer.send_mail import send_a_mail @sched.scheduled_job('cron', hour=4) def send_test_mail(): send_a_mail( 'email', # email 'password', # password 'recipient', # recipient 'Test Mail', # subject 'test') # message I would like to create a test for this like so: from django.test import TestCase from cronjob import send_test_mail class TestCronjobs(TestCase): def test_send_test_mail(): send_test_mail() But when i run the test it starts, but nothing happens, not even an error. It looks like the code is waiting for "hour 4" to run the send_test_mail() function. Does anyone have an idea on how to by-pass the waiting time? Or how to run these cronjob tests? -
Django loading javascript static files
i am trying to load a javascript static file into my Django template but only the css file loads and not the javascript file. Ive ran through the Django documentation and i cant find any information on this... Has anyone encounter any problems like this before? Thanks, much appreciated settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'dist') STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),] index.html {% load static %} <html> <head> <style type="text/javascript" src="{% static 'polls/js/jsfile.js' %}"></style> <link rel="stylesheet" type="text/css" href="{% static 'polls/css/back.css' %}"> </head> <body> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p>. {% endif %} <p id="test"></p> </body> </html> jsfile.js function codeAddress() { document.getElementById("test").innerHTML=Date(); } window.onload = codeAddress; Results1 Results 2 -
Thermal Printing with ExpressJS and Angular
So, I have a client who needs restaurant billing software along with android app for the waiters to take the order. I am all ok with the android app and the related API Backend. I have planned to do the backend in ExpressJS. But what I can't understand is how can I interface with the thermal printer. I am in the liberty of choosing a thermal printer of my choice. But where do I being ? I found this Option 1 and this option 2 and this is from where I can download the drivers for option 2 link. As you could have noticed, my budget for a thermal printer is not that high. But I still don't know how to proceed with printing from ExpressJS. I found these packages but I seriously can't understand anything. package 1 - NPM , package 2 - NPM. Also, I am familiar with Python (Django). So if anybody knows how to tackle this problem in Django, I am comfortable with the solution. -
combine() argument 1 must be datetime.date, not str
When using queryset in Django date range getting error from_date = request.POST.get('from_date') to_date = request.POST.get('to_date') min_dt = datetime.datetime.combine(from_date, datetime.time.min) max_dt = datetime.datetime.combine(to_date, datetime.time.max) daily_en = All_enquiries.objects.filter(enquired_at__range = (min_dt, max_dt)) when using variable manually value its working fine below from_date = datetime.date(2019, 12, 9) to_date = datetime.date(2019, 12, 9) -
Creating hierarchical relationships like REST Api with Django
New to Django. I know there is Django to Swagger generator is there but what I want is other way around. I want to create REST API: GET api/job/{id} POST api/job/{id} GET api/job/{id}/status POST api/job/{id}/status I don't think this project needs relational database, but for now I'm stuck with it. My model file looks like: class Job(models.Model): job_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) some_arg = models.TextField() class ChoicesEnum(Enum): @classmethod def choices(cls): return tuple((i.name, i.value) for i in cls) class Status(models.Model): class JobStatus(ChoicesEnum): NOT_STARTED = 0 IN_PROGRESS = 1 SUCCEEDED = 2 FAILED = 3 job_id = models.OneToOneField( Job, on_delete=models.CASCADE, primary_key=True, ) job_status = models.CharField(max_length=1, choices=JobStatus.choices()) But I'm not sure how am I supposed to create views for those two such a way they will be related. Sounds simple but can't wrap my head around.