Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i send email ( django )
I have a form in index page and i have 12 inputs in forms , so if user submits the form i need all 12 inputs in body of my email . I tried different methods and tried searching on google and youtube but could not find the solution. My urls.py code from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.index,name='index'), path('about/', views.about,name='about'), path('contact/', views.contact,name='contact'), ] my views.py code from django.shortcuts import render from django.http import HttpResponse from django.core.mail import send_mail # Create your views here. def index(request): def form(request): if request.method == "POST": year = request.POST['year'] make = request.POST['make'] part = request.POST['part'] engine = request.POST['engine'] transmission = request.POST['transmission'] name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] state = request.POST['state'] zipcode = request.POST['zipcode'] address = request.POST['address'] form = "Year: " + year + "Make: " + make + "Part: " + part + "Engine: " + engine + "transmission: " + transmission + "Name: " + name + "Email: " + email + "Phone: " + phone + "State: " + state + "Zipcode: " + zipcode + "Address: " + address send_mail( 'Mail from carparts', form, 'arshadkhanak05@gmail.com.', ['arshadkhanak05@gmail.com'], fail_silently=False, … -
How to deploy multiple services from the same Django project to Google App Engine?
Google App Engine allows developers to deploy multiple services from the same project structure. But I couldn't realize how it would to deploy them from an unique Django project. I'm already aware about How to deploy a Django project on Google App Engine, as well as How to deploy multiple Services with Google App Engine and how GAE expect a dispath.yaml to serve multiple services from a same deploy. In their description, the dispath.yaml should point to each service root, where service's app.yaml will be placed. However, I don't intend to have multiple Django projects in the file structure. I was expecting to be able to select each set of Django apps I want to be served in each App Engine service Someone thinks a manner to achieve it? Or there's another way of reuse same django project settings to reach it? -
Distribute tasks evenly which communicates via serial port, making sure that every celery worker is connected to a different serial port?
I have 10 IoT devices connected to the server, and I send/receive data via serial. I have 2 different types of tasks that gets executed via API call.. I might receive 1000 requests and I need to distribute them on these 10 devices, 1 worker per device, because of the Serial protocol limitations. Some of these devices are for task 1 and some are for task 2. I can create a queue per device and solve it, but the problem is if we plug in more devices later, it's gonna be a bit troublesome. I'd rather just assign the right task to the right device, and make sure it's executed one at a time. Any idea what I can do here? -
How do I solve a skel is not defined at skel-layers-min.js django framework error
Hello there my fellow devs, I am a backend beginner django developer and I used a premade template from Htmlup.com. I have changed all the links to {'static "{file location}"'}. When I run it on localhost it gives me this error: **init.js:15 Uncaught TypeError: {(intermediate value)} is not a function at init.js:15** I have tried adding: **var helios_settings = { //other settings here skel: {prefix: "{% static '/css' %}" }, // other settings here }** to the init.js file but it's still not working. Please what do I do? -
django canvas filter data and make the union of arrays filtered
I have a django canvas web app The user can draw on canvas and the drawing is saved in json as coordinates my model is as follows class Drawing(models.Model): drawingJSONText = models.TextField(null=True) project = models.CharField(max_length=250) drawingJSONTEXT contains the coordinates project contains the name of project i need to filter the data based on a specific project and i need to make a union of coordinates (drawingJSONText) filtered based on criteria Right now the code is able to filter and union two data based on their id def load(request): """ Function to load the drawing with drawingID if it exists.""" try: #filterdata = Drawing.objects.filter(project=a) drawingJSONData1 = json.loads(Drawing.objects.get(id=1).drawingJSONText) drawingJSONData2 = json.loads(Drawing.objects.get(id=2).drawingJSONText) drawingJSONData = dict() drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData1["points"] drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData2["lines"] drawingJSONData = json.dumps(drawingJSONData) # Sending context with appropriate information context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response I need it to filter the data dynamically such that all data which has project name= a are filtered and added into drawingjsonData and displayed on canvas -
Google Cloud Secret Manager returns 'Invalid constructor"
Here's my code: from google.cloud import secretmanager client = secretmanager.SecretManagerServiceClient() secret= client.access_secret_version("projects/#/secrets/SECRET_KEY/versions/3").payload.data.decode("utf-8") I get the error: Invalid constructor input for AccessSecretVersionRequest: 'projects/#/secrets/SECRET_KEY/versions/3' How can I solve this? I tried to follow Google's documentation exactly. (PS I used # instead of my project ID) -
mock.called returning False when should return True
I have a signal that is called when users are saved and a test for this signal: from django.db.models.signals import post_save from django.dispatch import receiver from notifications.signals import notify @receiver(post_save, sender='users.User', dispatch_uid='Testing_post_save') def testing_notification_signal(sender, instance, **kwargs): notify.send(verb='was saved', sender=sender, recipient=instance) from unittest import TestCase from unittest.mock import patch from users.models import User class SignalsTestCase(TestCase): def setUp(self): self.user = User( email='testing@example.com', first_name='test', last_name='test', username='test123' ) self.user.save() @patch('notifications_center.notifications.signals.testing_notification_signal') def test_if_signals_test_is_being_called(self, mock): self.assertTrue(mock.called) self.assertEqual(mock.call_count, 1) My test is returning False for the assertions, but if I put prints inside the signal, the function signal is being called. Why is this happening? How can I make this test pass? -
Filtering objects and and there instances using filter and exclude
I am trying to filter like this: #models.py class A(models:Model): all_letters = models.ManyToManyField(Letters, related_name="all_letters") selected_letters = models.ManyToManyField(Letters, related_name="selected_letters") #views.py a = A.objects.get(pk=pk) array_one = a.all_letters.all().exclude(a.selected_letters.all()) I know you can't filter based on instances but is the only equivalent way of doing this using some sort of manual python searching? -
aos.css is not working on django back end website
I have a django back end website and I tried to load the css in HTML as follows. {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/aos.css' %}" rel="stylesheet"> <link href="{% static 'css/index.css' %}" rel="stylesheet"> however this makes my website completely white. I can still see the letter is there by cursoring but in white color. I tried to not add aos.css but with bootstrap.min.css and inde.css and they worked fine. Is aos.css not compatible is django framework? -
ModuleNotFoundError: No module named 'core'
Django Version: 3.1.5 folder structure So, I'm studying Django. When I try to generate random data for my project I get this error: Traceback (most recent call last): File "C:\PythonProjects\DJANGO\myblogsite\blog\management\commands\create_data.py", line 2, in <module> from core.models import Category, Post, Comment ModuleNotFoundError: No module named 'core' Process finished with exit code 1 create_data.py from django.core.management.base import BaseCommand from core.models import Category, Post, Comment from random import randint import datetime Has anybody a clue how to deal with this problem? -
how to write lambda function to get true or false
this is django queryset - available_for_entry = Forms.objects.filter(deactivate_date__gte=today_date).exists() I have to use available_for_entry value in many other places. I can use it by creating an separate function. But just for learning purpose I wanted have lambda function instead of named function to get available_for_entry value. Can anyone help me on this? -
how to check a condition before exectuing any apis - python
My project has many APIs. but now I have to put a check in all of these APIs before start executing the codes in it. I have to make sure that API only returns data if that particular form's deactivation date is grater than datetime.date.today(). Queryset would be - available_for_entry = Forms.objects.filter(form_id=form_id, deactivate_date__gte=today_date).exists() One way to do this to write that query set in each of APIs and then use if available_for_entry: condition. But, I was wondering if there is any other way to achieve this without writing similar conditions so many times. I tried to achieve this with writing decorator but I could not able to pass the form_id value from function based API to that decorator. snapshot of the code is... def is_form_available(func): def checking(): today_date = datetime.date.today() available_for_entry = Forms.objects.filter(form_id=form_id, deactivate_date__gte=today_date).exists() if available_for_entry: func() else: print('form is not available now') return checking @api_view(['POST']) @is_form_available def question_list(request): form_id = request.POST.get('form_id') parameter_list = (FormParameters.objects.filter(mappings__form__formparametermappings= form_id).all()) serializer = FormParametersQuizSerializer(parameter_list, many=True) return serializer.data -
it's possible to Convert, QueryDict list values to normal values, but keeping original type as a QueryDict?
I have a QueryDict like this: <QueryDict: {u'firstValue': ['abc'], u'secondValue': [[]}> It's possible to get this? <QueryDict: {u'firstValue': 'abc', u'secondValue': []}> I checked similar answers like this: Convert QueryDict to key-value pair dictionary, but the original type changed. I also tried this: import json QueryDict(json.dumps(myQueryDict),mutable=True).copy() But, I got: <QueryDict: {u'{"firstValue": "1285", "secondValue": []}': [u'']}> I couldn't find a previous question that keeps the original type. Thanks for any help -
Django datetime form field with timezone select
Say I have model MyEvent and datetime fields for start/end. The dates are saved to the db in UTC (server default). All good so far. Now I have a ModelForm, and I want to be able to enter the start/end times in any timezone. They will still be saved to the db in UTC. I just want the user to be able to enter the dates relative to any timezone (theirs or any other one). # models.py class MyEvent(models.Model): start_at = models.DateTimeField() end_at = models.DateTimeField() # forms.py class MyEventForm(forms.ModelForm): class Meta: model = MyEvent fields = ['start_at', 'end_at'] widgets = { 'start_at': SomeSpecialDateTimePickerWithTimezoneSupport(), 'end_at': SomeSpecialDateTimePickerWithTimezoneSupport(), } I'm not picky about the UI. It could be a fancy datetime picker or simply separate selectlists for year/month/day/hour/timezone. The important thing is being able to specify the timezone. I do NOT want to store the timezone to the model. The form backend should convert whatever is entered to UTC before it's saved to the db. Writing my own MultiWidget might be my best option, but I was hoping there's a solid, simple package for this already. -
What is the best language for simple features in web applications? [closed]
I made a little web application using django where a user can create posts and now want to add functionality for simple comment and like features, but... what coding language would be best for this? Would javascript here be easier than django or is better to have the same language for all these functionalities? And are features like this belonging to backend or frontend? Let me know ;) - Phiona -
Django Unable to access LiveServerTestCase (code 500)
I was following Django docs, but am still having problem with this example - I get 500 Internal server error when accesing the live server with Selenium. My code: import os try: browser_driver = os.environ['BROWSER_DRIVER'] except KeyError: raise ValueError("BROWSER_DRIVER env variable not specified. \nPlease specify path to your " "browsers driver, more information: " "https://selenium-python.readthedocs.io/installation.html#drivers") os.environ["PATH"] += browser_driver from django.contrib.staticfiles.testing import LiveServerTestCase from selenium import webdriver class TestMostCommonUserActions(LiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = webdriver.Chrome() cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def test_slicing_is_possible_after_adding_and_subtracting_custom_slicing_info(self): # Here is the problem self.selenium.get('%s%s' % (self.live_server_url, '/')) pass When I run my server on localhost and try to access with selenium localhost on port 8000, it works. But shouldn't be the whole point of LiveServerTestCase to not to have the real django server? -
create a default in one Model using values from another Model in Django
I have been struggling over this for days diving down stackoverflow rabbit holes, documentation, and youtube tutorials. I'm just running in circles at this point. So... I have two models Variables and Entry. The daily inputs for Entry are to be recordings associated with a given Variable. Ex. I want to track daily sleep as a variable. Then, using that variable, have daily data entry associated with that variable using the Entry model. My models are below... (I suspect my schema is a mess as well, but it's generally working. This is my first time) class Variables(models.Model): ENTRY_TYPE_CHOICES = [ ('numeric', 'enter a daily number'), ('scale', 'rate daily on a scale of 1-10'), ('binary', "enter daily, 'yes' or 'no' "), ] id = models.IntegerField(primary_key=True) dep_var = models.CharField(max_length=50, default='') dv_reminder = models.CharField(max_length=50, choices=ENTRY_TYPE_CHOICES, default="numeric") # id current user evoler = models.ForeignKey(get_user_model(), default='', on_delete=models.CASCADE) def __str__(self): return self.dep_var def get_absolute_url(self): return reverse('entry_new') class Entry(models.Model): id = models.AutoField(primary_key=True) evoler = models.ForeignKey(get_user_model(), default='', on_delete=models.CASCADE) # id the active user dep_variables = models.CharField(max_length=50, default = '') data = models.FloatField(default=0.0) date = models.DateField(default=datetime.date.today) I've tried writing a function that would identify the most recent variable from a given user and to use that as the default … -
Proper SSL settings for Django site
This article provides extensive information about security in Django, but honestly I don't know which settings is necessary for my particular setup. My site is hosted with ngnix and it is configured to redirect http to https. Valid SSL certificate is also installed. I have the following in my settings.py file: SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_SECONDS = 31536000 My site is working properly and I have no issues, but I'm worried about missing an important settings. Is what I have set currently enough? Anything else should be added? -
collections.OrderedDict' object has no attribute 'email_data_attachment'
getting below error while calling my api, please help what to do MY models.py file # Create your models here. class submission(models.Model): # fixed fields to show on today panel/pending panel email_id = models.CharField(max_length=200, primary_key=True) # CR 1 enquiry_id = models.CharField(max_length=10, null=True, blank=True) email_sender = models.CharField(max_length=200, null=True, blank=True) email_subject = models.CharField(max_length=257, null=True, blank=True) email_broker = models.CharField(max_length=200, null=True, blank=True) broker_email_id = models.CharField(max_length=250, null=True, blank=True) email_attachments = models.IntegerField(default=0) email_outlook_date = models.DateField() # fields for filter email_ml_recommendation = models.CharField(max_length=20, default='moreinfo') email_assigned_user = models.CharField(max_length=200, default='not_assigned') # fields for traffic signal email_updated_flag = models.CharField(max_length=50, default='0') # initial=True email_latest_mail = models.CharField(max_length=50, default='1') email_owners = models.CharField(max_length=1000, null=True, blank=True, default='sample') email_status = models.CharField(max_length=200, null=True, blank=True) email_data_attachment = jsonfield.JSONField(null=True, blank=True) # general helping fields email_uwriter_decision = models.CharField(max_length=50, default='not_taken') email_today_mail = models.CharField(max_length=50, default=1) # deafault= 'True' email_deleted = models.CharField(max_length=50, default=0) # deafault= 'True' email_created = models.DateTimeField(auto_now_add=True) email_last_updated = models.DateTimeField(auto_now=True) flag_value = models.BooleanField(null=True, blank=True, default=False) # CR 9.2 # tell Django to sort results in the created_on field in descending order using the negative prefix class Meta: # ordering = ('-email_last_updated','-email_created',) ordering = ['-email_outlook_date', '-email_last_updated'] # managed = True # Custom function to override models default save function # https://stackoverflow.com/questions/52070462/django-generate-custom-id def save(self, **kwargs): if not self.enquiry_id: # max = submission.objects.aggregate(id_max=Max('enquiry_id'))['id_max'] max … -
Vue + DRF - best way to get user
I'm writing a blogging app which is using Vue + DRF. I have a new post component, but i'm not sure which way is the best to pass post author to backend. There is a store used in frontend so it's possible to pass author with rest of post data, but there is also possibility to get user from request by overriding create method in post view set. The side effect from second method is that it's impossible to create new post as different than logged user via rest api panel so it's the reason why i'm wondering about it. What should i do in this case? -
how to get object where any list element present in class object
lst = ["A","B","C","D"] models.py class Notice(models.Model): title = models.CharField(max_length=100,default="") createdAt = models.DateTimeField(auto_now_add=True) batch = CharField(max_length=100,default="") how to get all object of Notice where any lst element == batch...? -
SlugRelatedField not saving null values
I have a serializer with one SlugRelatedField for my foreign key instance like this: class PageSerializer(ModelSerializer): # Some normal serializer fields book = serializers.SlugRelatedField(slug_field='unique_id', queryset=Book.objects.all(), allow_null=True) class Meta: model = Page fields = (<Page model_fields>, 'book') My Page model looks like this: class Page(models.Model): # some fields book = models.ForeignKey(Book, to_field='unique_id', null=True, blank=True) Now, if I am providing non-null values, the serializer is working perfectly and saving all the fields as expected. But when I am passing null to the book SlugRelatedField, it is not updating the foreign key to None. Previous book foreign key value is still present in the Page model. What I am doing wrong here, that it is not saving None to the foreign key? -
What it the best way to handle unique constraint validation errors on many to many relationships?
This is more of a general topic than a specific issue I am stuck on. My team and I are are arguing about the best way to handle unique constraint validation errors on M2M relationships. We have Django Rest Framework APIs for the backend and Vue.js apps for the frontend. This is a simplified example, say you have a Candidate and a City model and candidates can order their cities by priority. We have a form on the client side allowing them to rank their cities and setting the value of priority accordingly. So there is a unique constraint between a candidate and a city. class CandidateCity(models.Model): city = models.ForeignKey('components.City', on_delete=models.CASCADE) candidate = models.ForeignKey('candidates.Candidate', on_delete=models.CASCADE) priority = models.SmallIntegerField(null=True) Even if we do checks on the client side to avoid that, from time to time a POST request gets sent with an existing candidate-city pair. That's where we arguing about different options. Should the API just raise a ValidationError and let the frontend deals with it or should it handle the error itself? Some suggest for instance setting conditions in the methods handling the POST request to update the instance if it exists and create it if it does not. I'd … -
Value error: View didn't return an HttpResponse object. It returned None instead
def editProfilePage(request): if request.method =='POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('profile') else: return render(request,'editProfile.html', {'form':form}) form = UserChangeForm(instance=request.user) context = {'form': form} return render(request,'editProfile.html', context) -
Docker run container based on image created with docker-compose.yml
I have an image build with a docker-compose.yml file using pycharm IDE. My application run a django container and a mysql container, with 3 volumes. When I build this image with pycharm, container start automatically and it's working as expected. So I pushed this image on docker repository. But, when I pull this image on another device, I try to run it with following command: docker run my_repo/my_image I get this in the logs on the container: Python 3.8.7 (default, Feb 9 2021, 08:08:20) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. It seems that it only start python ! Mysql image required in docker-compose.yml file have not been pull, volumes have not been created, and my application is not running... I was thinking that running this image will use docker-compose.yml file inside the image to create and pull all necessary things... But it seems that I was wrong ! Someone can help me to understand what happen ?