Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError at /register/ NOT NULL constraint failed: auth_user.description
I'm in the last stages of deploying my django application onto a web server, but recently have been getting this error when trying to register a new user IntegrityError at /register/ NOT NULL constraint failed: auth_user.description I re-ran the error with DEBUG turned on and it says that the direct cause of the problem is in line 17 in the register section of my views.py file, which looks like this: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit= False) username = form.cleaned_data.get('username') is_teacher = form.cleaned_data.get('is_teacher') if is_teacher == True: user.is_staff = True user.save() *LINE 17* else: user.is_staff = False user.save() messages.success(request, f'Tu cuenta se ha creado correctamente, ahora puedes iniciar sesión') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) The problem is that I don't understand why it's saying that's the problem, since I had tested that feature many times in my local server. Any kind of help would be greatly appreciated. -
Django Allauth block domain
I am currently working on Google and LinkedIn authentication with Django Allauth on the project. When a user wants to register via Google or LinkedIn, I need to prevent registration requests with gmail.com and ensure that they only register with business mail. As far as I understand, Allauth cannot provide me with this directly. What is the best practice to do that? -
Django Rest Framework change admin form
I want to change forms of admin page of DRF. below link shows how it can change the form. https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#a-full-example But the sample can affect only Django, not DRF? How can I change the DRF admin page form? -
Django template doesn't display the model items
sorry, I'm very new as a member (and as developer too). I've recently started to work with Django, and I'm trying to display on a page, a list of articles with some elements (title, image, created_at, content), already done in a model. The views, the template and the path (urls) were bilt too. But when I Run the server and open the browser it only displays the title I passed as the render parameter in the view, not the object (articles = Article.objects.all()), created in the view. blog/models.py from django.shortcuts import render from blog.models import Article, Category # Create your views here. def list(request): articles = Article.objects.all() return render(request, 'articles/list.html', { 'title' : 'Articles', 'articles': articles } ) blog/urls.py from django.urls import path from . import views urlpatterns = [ path('list/', views.list, name='list_articles'), ] blog/views.py from django.shortcuts import render from blog.models import Article, Category # Create your views here. def list(request): articles = Article.objects.all() return render(request, 'articles/list.html', { 'title' : 'Articles', 'articles': articles } ) blog/list.html {% extends 'layouts/layout.html' %} {% block title %} {{title}} {% endblock %} {% block content %} <h1 class= "title">{{title}}</h1> {% for article in articles %} <article class="article-item"> {% if article.image != 'null' and article.image|length … -
How to add overwrite unique data using django-import-export?
I need to overwrite existing data from Microsoft Excel file & If the data is not in Database it should get added using Django Admin & Django Import Export. -
How can I get image url in queryset.values()?
I have a user model like this: class CustomUser(AbstractUser): ... email = models.EmailField(unique=True) profile_pic = models.ImageField(null=True, blank=True, upload_to=content_file_name) def content_file_name(obj, filename): ext = filename.split('.')[-1] filename = "profile_pic_{0}.{1}".format(str(obj.user.id), str(ext)) return os.path.join(filename) I know I can get the profile_pic image media path using user.profile_pic.url. But, how can I get the image media path in queryset.values()? I tried this queryset.values("profile_pic_url") and queryset.values("profile_pic__url") but It doesn't work. I can annotate the profile_pic using F-Objects and add the media path as a prefix using f-string like below users = queryset.annotate(image_path=F("profile_pic")).values("image_path") and then I can add prefix like f"/media/{user.image_path}" -
How to upload an Image File modified by OpenCV using FileSystemStorage in Django?
I am taking an uploaded image from the user and then sending it to a YOLO model which then returns me an image. I want to store that returned image in my Local Directory and then display it on the user interface. This is the Code of views.py that takes in an image and sends it to the Yolo Model, def predictImage(request): # print(request) # print(request.POST.dict()) fileObj = request.FILES['filePath'] fs = FileSystemStorage() filePathName = fs.save(fileObj.name, fileObj) filePathName = fs.url(filePathName) testimage = '.'+filePathName # img = image.load_img(testimage, target_size=(img_height, img_width)) img = detect_image(testimage) filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR filePathName = fs.url(filePathName) This is the function of YOLO Model that uses OpenCV to read the image (Image is sent as argument to the function) and then returns that image, import numpy as np import cv2 def detect_image(img_path): confidenceThreshold = 0.5 NMSThreshold = 0.3 modelConfiguration = 'cfg/yolov3.cfg' modelWeights = 'yolov3.weights' labelsPath = 'coco.names' labels = open(labelsPath).read().strip().split('\n') np.random.seed(10) COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8") net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights) image = cv2.imread(img_path) (H, W) = image.shape[:2] #Determine output layer names layerName = net.getLayerNames() layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()] blob = cv2.dnn.blobFromImage(image, 1 / 255.0, … -
How to include ManyToMany Fields in DjangoRestFramework Post Request?
I have this serializer (there are more fields in entity model, but they're irrelevant since the only problem i have is with the M2M) class EntityServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = '__all__' class EntityCreateSerializer(serializers.ModelSerializer): entity_service = EntityServiceSerializerThrough(read_only=True, source='serviceschedule_set', many=True) class Meta: model = Entity fields = '__all__' Model looks like this class Entity(models.Model): entity_service = models.ManyToManyField(Service, through='ServiceSchedule') class ServiceSchedule(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) entity = models.ForeignKey(Entity, on_delete=models.CASCADE) class Service(models.Model): service_name = models.CharField(max_length=256, null=True) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) animal = models.ForeignKey(Animal, on_delete=models.CASCADE, default=None) The thing is, when i put in body "entity_service": [1,2] in the response i still get = []. Even though i have in my database Services with pk 1,2,3,4. Do you know how can i make it work? -
How to Implement CSP for Ckeditor in Django
I'm not using CDN or any link for CKEditor but I have PIP installed it using pip install django-ckeditor. I have added all necessary CSPs and CKEditor configurations in settings.py file but CKEditor is not working in html. In settings.py CSP_DEFAULT_SRC = ("'self'", ) CSP_BASE_URI = ("'none'", ) CSP_FRAME_ANCESTORS = ("'none'", ) CSP_FORM_ACTION = ("'self'", ) CSP_STYLE_SRC = ("'self'", 'cdnjs.cloudflare.com','fonts.googleapis.com', 'stackpath.bootstrapcdn.com', 'getbootstrap.com') CSP_SCRIPT_SRC = ("'nonce-value'", 'cdn.ckeditor.com','ajax.googleapis.com', 'stackpath.bootstrapcdn.com', 'code.jquery.com', 'unpkg.com', 'cdnjs.cloudflare.com', 'code.jquery.com', 'getbootstrap.com') CSP_IMG_SRC = ("'self'", 'cdn.ckeditor.com' ,'cdn0.iconfinder.com', 'media.giphy.com','res.cloudinary.com') CSP_FONT_SRC = ("'self'",'cdnjs.cloudflare.com','fonts.googleapis.com', 'fonts.gstatic.com') CSP_INCLUDE_NONCE_IN = ("script-src", "style-src") -
django.core.exceptions.FieldError: Cannot resolve keyword 'date' into field. Join on 'date' not permitted
Here, is my model serializer. class DailyCustomerBuySellAPIView(APIView): def get(self, request): customer_buy_sell = CustomerBuySell.objects.extra(select={'day': 'date( date )'}).values('day').order_by( 'date__date').annotate(available=Count('date__date')) serializer = CustomerBuySellSerializer(customer_buy_sell, many=True) return Response({"customer_buy_sell": serializer.data}) -
Django error: ModuleNotFoundError: No module named 'mydjangoprojstudentsstudents'
This is the error in my git bash console. I'm just beginning Django hence don't know where to search for the error. My settings.py file My urls.py file My apps Please let me know if I need to provide any more info. Any help would be appreciated. Thanks in advance. -
how to fix moduleNotfoundErreor on deplying Django app to Heroku?
I have been trying to deploy my django project on heroku but Heroku is not tracking my project app name as presented in the Procfile. Honestly django_profile_viewer is the excact name of the project that has my settings file... #My procfile web: gunicorn django_profile_viewer.wsgi:application --log-file - --log-level debug python manage.py collectstatic --noinput manage.py migrate #Heroku logs 2022-02-13T10:46:43.042362+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-02-13T10:46:43.042362+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2022-02-13T10:46:43.042363+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2022-02-13T10:46:43.042363+00:00 app[web.1]: ModuleNotFoundError: No module named 'django_profile_viewer' 2022-02-13T10:46:43.042446+00:00 app[web.1]: [2022-02-13 10:46:43 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-02-13T10:46:43.054936+00:00 app[web.1]: [2022-02-13 10:46:43 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-02-13T10:46:43.154082+00:00 app[web.1]: [2022-02-13 10:46:43 +0000] [4] [INFO] Shutting down: Master 2022-02-13T10:46:43.154125+00:00 app[web.1]: [2022-02-13 10:46:43 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-02-13T10:46:43.344541+00:00 heroku[web.1]: Process exited with status 3 2022-02-13T10:46:43.459875+00:00 heroku[web.1]: State changed from starting to crashed 2022-02-13T10:52:53.470088+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=profile-viewer-app.herokuapp.com request_id=430d2f5f-4ba3-4780-8cf8-ce1990237951 fwd="197.239.4.35" dyno= connect= service= status=503 bytes= protocol=https 2022-02-13T10:52:59.973950+00:00 heroku[web.1]: State changed from crashed to starting 2022-02-13T10:53:04.200202+00:00 heroku[web.1]: Starting process with command `gunicorn django_profile_viewer.wsgi:application --log-file - --log-level debug` 2022-02-13T10:53:05.838609+00:00 heroku[web.1]: Process exited with status 3 2022-02-13T10:53:05.951233+00:00 … -
"FIELD_ENCRYPTION_KEY must be defined in settings" - encrypted_model_fields error
Python 3.8.10 Django 4.0.2 django-encrypted-model-fields: 0.6.1 I am using encrypted_model_fields to encrypt a model field. The field I am encrypting is a password used to access a user account for another app via an api. According to the docs I need to import the module and then wrap the model field as follows: Models.py from encrypted_model_fields.fields import EncryptedCharField account_password = EncryptedCharField(models.CharField(max_length=20, blank=True)) In addition to that I need to add a FIELD_ENCRYPTION_KEY to settings.py, which I have done, as per the docs. Settings.py FIELD_ENCRYPTION_KEY = os.environ.get('FIELD_ENCRYPTION_KEY') I have also added 'encrypted_model_fields' to installed apps in settings.py and the encryption key to .env, which is in place of the placeholder below..env: export FIELD_ENCRYPTION_KEY=my_encryption_key_place_holder When I run makemigrations I receive the following error: django.core.exceptions.ImproperlyConfigured: FIELD_ENCRYPTION_KEY must be defined in settings I have defined it - so why is it not found? -
Does anyone know how to use Django and Brownie libraries together (python)?
Does anyone know how to use Django and Brownie libraries together (python)? Thanks for any information. -
Django: background image it does not appear after Generating a PDF from HTML in my Django project
Hi people there i want to set a background image for my printout pdf , I have already rendered it from html to pdf. I have tried much solutions but it doesn't work with me to set a background (It doesn't appear); Here are my tries: First Try: go to models.py: and write this method: def image_as_base64(image_file, format='png'): if not os.path.isfile(image_file): return None encoded_string = '' with open(image_file, 'rb') as img_f: encoded_string = base64.b64encode(img_f.read()) return 'data:image/%s;base64,%s' % (format, encoded_string) then go to the class of the model that am working with and write this method : with specifying on the path of the image: Here is the code: class Formulaires(models.Model): def get_cover_base64(self): return image_as_base64('/home/diva/.virtualenvs/django-projects/example/static/img/background.png') then I have go to the template.html and call the method "get_cover_base64" that contain the path on the tag "div" from the body (background-image:) <body style="font-size: 12px; "> <div id="divid" style="padding: 0.01rem; background-image: "{{ post.get_cover_base64 }}";" class="container"> PS: 2nd try: i have tried storing online my image - background and call with url and also it doesn't work ; here is the code: <body style="font-size: 12px; background-image: url('https://....');> 3rd try: using the staic files <body style="font-size: 12px; background-image: url('{% static "img/background.png"%}');> --> it doesn't work with … -
Django 4.0.2 | Python 3.9.7 | TypeError: __init__() missing 1 required positional argument: 'get_response'
I wrote a custom authentication and added a csrf check middleware in the authentication process. I am calling the below function in the authentication function. def enforce_csrf(self, request): """ Enforce CSRF validation """ check = CSRFCheck() check.process_request(request) reason = check.process_view(request, None, (), {}) if reason: # CSRF failed, bail with explicit error message raise PermissionDenied('CSRF Failed: %s' % reason) The CSRFCheck() function is a custom middleware and it looks like this. class CSRFCheck(CsrfViewMiddleware): def _reject(self, request, reason): return reason Now when I am trying to process the request, which requires authentication, I am getting the error: TypeError: init() missing 1 required positional argument: 'get_response' the same code is working perfectly in Django 3.2 Now, as far as I was able to debug, the CSRFCheck function is expecting a get_response method which I don't know where it is coming from. -
Run Django server as a daemon process when start/reboot the GCP virtual machine
I'm connecting to GCP virtual machine through ssh-key in visual studio code. I've created a Django API and want to start the server as a daemon process when I start the virtual machine. I've created a script file run_script.sh cd /home/s4cuser/poc_system python3 manage.py runserver 0.0.0.0:8000 where s4cuser is the user and poc_system is my django project folder I've created a crontab file and added @reboot <path to run_script.sh> at the bottom of crontab file. But when I reboot the virtual machine and check whether process got started or not by typing below command, nothing comes. ps aux | grep manage.py What could be the reason for it? -
How to know which conditions gives error in mongodb query then able to error handling
I'm use pymongo and django. In my case I want know which one of my conditions in find or find_one or find_one_and_update mongo query returns false. for example, we have this document: { { "key": 1, "name": "my_name" }, { "key": 2, "uesrname": "username" } } and need to find a document with key =2 and name have the field name query = collention.find_one( {"key":2,"name":{$exists:true}} ) The above query gives us an empty dictionary. I tried using explain() but in find_one I got an error 'NoneType' object has no attribute 'explain' and in find({...}).explain() it does not specify which condition is wrong. Now, how could I error handling ?? -
Django - Implement and test cache busting
It looks like I'm facing cache issues with my application so I would like to implement this cache busting feature as it was recommended to me. The context: my application is already in a production server (alpha version) and as this is an evolution of the ground settings, I would like to take this opportunity to train myself to prepare, test and deliver such technical updates. I'll take the opportunity to better understand static files management. Currently, the js and css files are not properly propagated and my production app still uses older versions, so I need to enforce a server cache refresh. As I'm not comfortable at all with all of this stuff and static files management, I would like to double check the process and understand how I could test it before pushing to production. How to proceed As far as I understand, what I have to do is to change my settings file and add the following line: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' I'm wondering if I need to change anything else. Here are my current settings about static files management: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = [] I've mainly seen several approaches for STATICFILES_DIRS (either … -
Unable to install web3 despite having microsoft build tools
I used cmd pip install web3, but it is not working -
Timeout issue in django with nginx and gunicorn
I have few rest API,s in django that take more then one minute to get Data. Because there are more then 20 million records in database. But It show time out after one minute . How to increase timeout ?. I have searched the internet and made changes in Nginx and Gunicorn accordingly but It still show time out after one minute when i hit the API with postman. Nginx Config file - location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/neeraj/run/gunicorn.sock; proxy_connect_timeout 500; proxy_read_timeout 500s; } Gunicorn.service file - ExecStart=/home/neeraj/cashvenv/bin/gunicorn --error-logfile /home/neeraj/run/gerror.log --workers 3 --timeout 500 --bind unix:/home/neeraj/run/gunicorn.sock Cash.wsgi:application Please help me out with this. -
Change quantity of product in django ecommerce website? DJANGO
It's not giving an error. The quantity is being changed only in the first product, even if when I press arrow of second product, the quantity of first product is being changed. cart.js var changeQ = document.getElementsByClassName('increase') for (i = 0; i < changeQ.length; i++) { changeQ[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) if (action == 'plus'){ Increase(productId, action) } else if(action=='minus'){ Decrease(productId, action) } }) } function Increase(productId,action){ console.log('Increase') var quantity = Number(document.getElementById("quantity").value); quantity = quantity+1; document.getElementById("quantity").value = quantity; console.log(quantity); } function Decrease(productId,action){ var quantity = Number(document.getElementById("quantity").value); console.log('Decrease') quantity = quantity-1; document.getElementById("quantity").value=quantity; } template <div class="counter"> <div class="arrow-up increase" id="arrow-up" data-product="{{item.product.id}}" data-action="plus" ><i class="fa fa-arrow-up"></i></div> <div class="quantity"><input type="number" id="quantity" value="1"></div> <div class="arrow-down increase" id="arrow-down" data-product="{{item.product.id}}" data-action="minus"><i class="fa fa-arrow-down"></i></div> </div> It's in Django. So what can I do to indicate the specific product. Can someone help me to solve this problem, please! -
Django form submit through Javascript returns empty fields
I have a form in my HTML document for which I suggest a few examples on how to fill it. The user can click on one of these examples and it will call a javascript function that pre-fill and submits the form. The submit function works correctly but it returns empty fields. Do you have any idea why? My HTML: form has 5 fields (amount, category, title, expiration, priority), 4 examples: <form method="POST" id="myform"> {% csrf_token %} <label for="amount" class="form-label h6 mb-0 text-dark font-weight-bold" style="width: 120px;">Target amount</label> <input name="amount" id="amount" placeholder="0" style="width: 200px;"> <input type="hidden" name="category" id="category"> <input type="hidden" name="title" id="title" value=""> <input type="hidden" name="expiration" id="expiration"> <input type="hidden" name="priority" id="priority"> <div class="goals-template align-items-center text-center mb-4"> <a class="template" onclick="FormSubmit(this)"><img class="template-item" src="{% static 'img/undraw_emergency2.svg' %}">Emergency Fund</a> <a class="template" onclick="FormSubmit(this)"><img class="template-item" src="{% static 'img/undraw_car2.svg' %}">New car</a> <a class="template" onclick="FormSubmit(this)"><img class="template-item" src="{% static 'img/undraw_house2.svg' %}">House</a> <a class="template" onclick="FormSubmit(this)"><img class="template-item" src="{% static 'img/undraw_wishlist2.svg' %}">Wishlist</a> <button type="submit" class="d-none" id="Go">Save goal</button> </div> </form> My JS: function FormSubmit(e) { var myform = document.getElementById("myform"); document.getElementById('category').value = 'RETIREMENT'; document.getElementById('title').value = '10'; document.getElementById('amount').value = 10; document.getElementById('expiration').value = '2022-12-31'; document.getElementById('priority').value = 'NEED'; getCookie('csrftoken'); var hiddenField1 = document.createElement("input"); hiddenField1.setAttribute("type", "hidden"); hiddenField1.setAttribute("name", 'csrfmiddlewaretoken'); hiddenField1.setAttribute("value", getCookie('csrftoken')); myform.appendChild(hiddenField1); myform.submit(); } The response in my console: -
Django Rest framework foreign key problem
I have this problem insert or update on table "Auth_user_org" violates foreign key constraint "Auth_user_org_user_id_id_465bfad2_fk_auth_user_id" DETAIL: Key (user_id_id)=(1) is not present in table "auth_user". this is my model.py class User(models.Model): id = models.AutoField(primary_key=True) FirstName = models.CharField(max_length=100) LastName = models.CharField(max_length=100) mail = models.CharField(max_length=100) def __str__(self): return str(self.id) class Organization(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(default='0000000',max_length=100) type = models.CharField(default='0000000',max_length=20) def __str__(self): return str(self.name) class User_org(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(User,default=1,related_name='UserInfo', on_delete=models.CASCADE) organization_id = models.ForeignKey(Organization,related_name='orginfo',on_delete=models.CASCADE) def __str__(self): return str(self.user_id) can not add in User_org ,user_id and organization_id. what is solution? -
Django response Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
my model has attributes fields as file and the person who uploaded it ,in my case i would want to show the error no file found on my website front end when there is no data in model but instead it is taking me to this error i have implemented my code like this @api_view(('GET',)) def template_view(request): data = Mymodel.objects.first() try: if data: response = HttpResponse( data.file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, ' 'application/vnd.ms-excel', ) return response except FileNotFoundError: raise ValueError('No file found')