Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert my current django app to REST API?
I need to convert my current django app which is a UserCreationForm with email and phone numbers validation to a REST API. But first I need to register the text fields to the django admin site to have the phonenumber, email and password fields. However in my admin.py at "admin.site.register(UserRegisterForm)", when I run python manage.py makemigrations, an error occurred and it states TypeError: 'ModelFormMetaclass' object is not iterable. I'm not sure if maybe the admin.site does not accept the fields in any UserForms and they only accept models. Here is my code: /* forms.py */ import re import phonenumbers from phonenumbers import carrier from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from validate_email import validate_email # from django.db import models # from django_countries.fields import CountryField, countries # from phonenumber_field.formfields import PhoneNumberField class UserRegisterForm(UserCreationForm): email = forms.EmailField() # phone_number = PhoneNumberField() phone_number = forms.CharField(max_length=100) # country = CountryField(blank_label='Select Country').formfield() country = forms.CharField(max_length=2) class Meta: model = User fields = ['username', 'email', 'country', 'phone_number'] def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, check_mx=True, verify=True): raise forms.ValidationError("Invalid email") return email def clean_phone_number(self): phone_number = self.cleaned_data.get("phone_number") clean_number = re.sub("[^0-9&^+]", "", phone_number) # alpha_2 = self.cleaned_data.get("country") alpha_2 = self.cleaned_data.get("country") z = … -
Django background task is locked when there are too many task at the same time
On my server when the user upload multiple files, the python code will be run to process it. I can upload 100 files successfully, But if the files is over than that the task will be lock(I look in Django Admin page) and no more files can be process. Here is the code @background(schedule=datetime.timedelta(seconds=1)) def reflect_upload_data(): . . . But If I comment the @background line out, The problem will not occur. How can I make Django Background Task work in this situation? -
Hello, I'm using python and have the following error: local variable 'my_total' referenced before assignment
UnboundLocalError at /products/forms/ local variable 'my_total' referenced before assignment -
Save the username of the loggedin user in the database instead of the userid
I would like to save the username of the loggedin user in the database. But only the userid shows up in the databse, and i can't seem to work out how to change it to the username. Can you help me get this ? Thanks Here is my code models.py from django.db import models as db_models from django.contrib.auth.models import User from django.contrib.gis.db import models class Fertidb(models.Model): user = db_models.ForeignKey(User, on_delete=models.CASCADE) culture = models.CharField(max_length=50) area = models.IntegerField() plot = models.FileField(upload_to='KML_FILES', blank=True) def __str__(self): return f' Parcelles de {self.user.username}' Forms.py from django import forms from django.contrib.auth.models import User from .models import Fertidb class FertidbForm(forms.ModelForm): class Meta: model = Fertidb labels = { "plot": "Importez votre fichier KML" } fields = ['culture', 'area', 'plot'] views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import FertidbForm from django.contrib.auth.models import User title = 'FERTISAT' @login_required def fertisatmap(request): if request.method == "POST": o_form = FertidbForm(request.POST, request.FILES) if o_form.is_valid(self, o_form): o_form.save(commit=False) fertidb.user = request.user # o_form.user = request.user.username() username = fertidb.cleaned_data.get('username') fertidb.save() messages.success(request, f'Vos informations ont été envoyées') return redirect('fertisat-map') else: o_form = FertidbForm() context = {'title': title, 'o_form': o_form} return render(request, 'fertisat/fertisatmap.html ', context) -
How to do filtering in Django Rest ModelViewset
I have signup api. I'm adding signup details, data adding fine but I don't want to add same data multiple time.For example username="abc", email= "abc@example.com", phone_no="1234567890" data already present in database but its adding same data again and again. I'm trying to avoid this. How to do that modes.py class Signup(models.Model): email = models.EmailField(max_length=50, blank=True, null=True) phone_number = models.CharField(max_length=12, blank=True, null=True) username = models.CharField(max_length=300, blank=True, null=True) password = models.CharField(max_length=50, blank=True, null=True) serializers.py class SignupSerializer(serializers.ModelSerializer): class Meta: model = Signup fields = '__all__' views.py class SignupViews(viewsets.ModelViewSet): queryset = Signup.objects.all() serializer_class = SignupSerializer urls.py router = routers.DefaultRouter() router.register('api/signup', views.SignupViews) urlpatterns = [ path('', include(router.urls)) ] -
How to access client camera for Face recognition using openCV in Django?
I'm trying to build a website using Django, I have a concept of integrating face login for my website and It's perfectly working on the server computer and when I try to access the same from the client computer, the camera pop-ups in server computer rather in the client computer. I couldn't able to understand how I can access the client camera and pass it to my face recognition code? I have written Django code for face signup using the basic OpenCV concept for face recognition. And Its perfectly working on the server computer and when I access from the client the camera pop-ups from the server computer. All I used on my code is a simple signup form and OpenCV for face recognition. What should I need to pass for the object VideoCapture( ) in order to access the client camera and can anyone suggest me any other possible ways to build a face login module. -
No matching distribution found for Django pip3
I am using Ubuntu 16.04.i have installed python 3 when i run following commands python --version Python 2.7.12 python3 --version Python 3.5.2 pip3 -V pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5) when i try to install Django pip3 install --user Django Got following error Could not find a version that satisfies the requirement Django (from versions: ) No matching distribution found for Django even i mentioned django version pip3 install --user Django=2.2 Since i am new to python.i have searched and tried many threads but not use -
Python convert DOCX to PDF after modifying document and export PDF to download (DJANGO)
I have a Django app that reads a document template (DOCX) and modifies it. The program is working well, but it is returning to download a DOCX document (as expected). So, I want to edit the download file format to PDF. I thought of converting the DOCX file to PDF but I couldn't find a working way to do that. My actual code looks like this: f = io.BytesIO() document.write(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + formular.name + '.docx' response['Content-Length'] = length return response I want to find a working method of converting the DOCX file f to a PDF file before returning that as response. -
ValueError: Missing staticfiles manifest entry for 'favicon.png' when DEBUG = False
raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'favicon.png' when DEBUG = False I only get this error when DEBUG = False, I do not get any error when DEBUG = True To fix this issue while keeping DEBUG = False, I must add back in favicon.png (which I had deleted a while back) to the static_root folder and then run python manage.py collectstatic I checked all my files and all my html documents have the link favicon.png line commented out, so that is not the issue. settings.py has the following: STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR, 'static_root'), ] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(BASE_DIR, 'static/') urls.py has following: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to add placeholder text to a Django Admin field
I'd like to add placeholder text to a field in the Django Admin change form. In a regular ModelForm you can do this by overriding the field's widget or by modifying self.fields['my_field'].widget in the ModelForm __init__() method. How do I do something similar for a Django Admin? -
DRF ignoring permission classes for owner
I implemented BasePermission class in project but when I am going to retrieve logged user with his token it says You don't have a permission to perform this action permissions.py class IsLoggedInOrAdmin(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.user == request.user or request.user.is_staff class IsAdminUser(permissions.BasePermission): def has_permission(self, request, view): return request.user and request.user.is_staff def has_object_permission(self, request, view, obj): return request.user and request.user.is_staff and my views file looks like this class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def get_permissions(self): permission_classes = [] if self.action == 'create': permission_classes = [AllowAny] elif self.action == 'retrieve' or self.action == 'update' or self.action == 'partial_update': permission_classes = [IsLoggedInOrAdmin] elif self.action == 'destroy' or self.action == 'list': permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] here what i have done so far. I created simple user and took token If I send GET request in Postman I am getting a detail error but it works fine with superuser's token but not owner. Where Am I making mistake? Any help please? Thanks in advance! -
Django using icontains filter with multiple values from dictionary
Hi i'm trying to run a model search query through a dictionary data which i got like so: { "city":5, "direction":"ne", ..other data that can be dynamic... "address__icontains" = ["word1", "word2", "word3"], } My search query: Models.objects.filter(**query_dict) since the other data are dynamic that why i use filter with dictionary.And i'm using __icontains to search up field address(string value) that contains those 3 words in that string, so the problem right now is since __icontains doesn't accept array like so in the query set: Models.objects.filter(other keys and values from dictionary, address__icontains= ["word1", "word2", "word3"]) How would i make this work with the dictionary filter search ? I also tried changing the dictionary to "address__icontains" = "word1 word2 word3" but it also doesn't work Thank for reading -
Django update_or_create results in a duplicated row
I'am trying to update or create an entry. Here are my relevent codes: Models.py class Comment(SafeDeleteModel): id = models.AutoField(primary_key=True) content1 = models.TextField() content2 = models.TextField() fieldA = models.ForeignKey('A') fieldB = models.ForeignKey('B') views.py class CommentViewSet(viewsets.ModelViewSet): def post(self, request): comment, created = Comment.objects.update_or_create( fieldA =request.data.fieldB, fieldB =request.data.fieldB, defaults={ 'content1': request.data.content1, 'content2': request.data.content1, } ) return Response(comment, created) At this point, every time i'm trying to edit a comment where fieldA and fieldB already exist, i got a duplicated row. I sure tried to add unique_together unique_together = (('fieldA', 'fieldB', ),) I now get an integrity error, saying fieldA and fieldB have to be a unique set. Looks like my post class is ignored. Any help would be greatly appreciated. Thanks -
How to have a ModelChoiceField show only one attribute of the class?
I have a model that uses a bunch of foreign keys. That model has its own form and view which works perfectly fine. But one field in the form needs to call only one attribute from the foreign key's class in models. At the moment the dropdown field on the form shows ALL of the info from that model Models: class Book(models.Model): book = models.Charfield(max_lenght=255) author = models.Charfield(max_lenght=255) summary = models.TextField() def __str__(self): field_values = [] for field in self._meta.get_fields(): field_values.append(str(getattr(self, field.name, ''))) return ' '.join(field_values) class BookInventory(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) serial_number = models.CharField(max_length=255) Form: class BookInventoryForm(forms.ModelForm): book_title = forms.ModelChoiceField(queryset=Book.objects.all()) # book_title field should only list books author = forms.ModelChoiceField(queryset=Book.objects.all()) # author field should only show authors summary = forms.TextField() serial_number = forms.CharField(max_length=255) supplier_name = forms.ModelChoiceField(queryset=Supplier.objects.all()) location_name = forms.ModelChoiceField(queryset=Location.objects.all()) class Meta: model = BookInventory fields = ["book_title", "author", "serial_number", "supplier_name", "location_name"] View: def book_inventory(request): if request.method == "POST": form = BookInventoryForm(request.POST) if form.is_valid(): form.save() return redirect("index") else: form = BookInventoryForm return render(request, "add_book_inventory.html", {"form" : form}) So on the add_book_inventory.html page's form there will be two dropdowns, one for author and one for title. At the moment the book title drop … -
Django - Create related object on first call
I have some models: class User(AbstractUser): cart = models.OneToOneField('cart.Cart', on_delete=models.SET_NULL, null=True, blank=True) class Cart(models.Model): products = models.ManyToManyField('product.Product') date_updated = models.DateTimeField(auto_now=True, editable=False) Now I need to create user cart instance at first call. if request.user.cart is None: request.user.cart = Cart.objects.create() request.user.save() This method is not good for me, because it leads to code duplication (every time I need to import Cart model and check the user's cart is it None or not). The best way that I can find is AutoOneToOneField in django-annoying, but unfortunately it absolutely broke current field autocomplete in PyCharm. What is the right way to do that? P.S. I really don't need to create user cart object at user creation moment. P.P.S. Sorry for my bad English. -
Django "OR queries in **kwargs" for filtering
I have an existing **filter_kwargs used for "and" filtering, how do I insert the "or" queries? currently the supposed "OR" queries are treated as "and" query. Here's my base code: search_text = form_data.get("search_text", "").strip(" ") filter_kwargs = { "is_active": True, "is_admin": False, } if search_text != "": // these are the supposed "OR" queries. how do I insert "OR" queries in kwargs? filter_kwargs['user__first_name__icontains'] = search_text filter_kwargs['user__last_name__icontains'] = search_text filter_kwargs['user__email__icontains'] = search_text Profiles = Profile.object.filter(**filter_kwargs) -
Include variables in one template file into another in Django
I have a template file temp1.html having code like this --- {% load customtags %} {% get_val 'VAR1' as var1 %} {% get_val 'VAR1' as var2 %} In second template file temp2.html i want to use these variables var1, var2 and var3. I am going to use these variables in multiple template files. So want to reuse the code every where. I am including the temp1.html into temp2.html but these variables are not accessible into the temp2.html {% include 'temp1.html' %} So how to use these variables in another template files ? Please any body suggest me ! -
how to adding new fields for django-registration form
I had a lotof things to enter in my registrations form but I'am use base registration form in django 2.2 version. But I can't make it, I am new from Django and not fully understrand how to add extra fields to the base registration form. I write like this code: models.py from django.db import models from django.shortcuts import reverse from django.conf import settings from home.models import Locations, Levels class User(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) photo = models.ImageField(upload_to='static/img/profile/', blank=True) levels = models.ManyToManyField(Levels, verbose_name='levls') name = models.CharField(max_length=120, db_index=True) first_name = models.CharField(max_length=120, db_index=True) birdate = models.DateField() locations = models.ManyToManyField(Locations, verbose_name='locl') telnum = models.IntegerField(null=True) levelreg = models.DateTimeField(auto_now_add=True) levelchange = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=120) aside = models.CharField(max_length=120, unique=True) bside = models.CharField(max_length=120, unique=True) friendusers = models.CharField(max_length=120, unique=True) rebuy = models.IntegerField(null=True) balls = models.IntegerField(null=True) total = models.IntegerField(null=True) date_pub = models.DateTimeField(auto_now_add=True) def __str__(self): return 'Profile for user {}'.format(self.user.username) forms.py from django.contrib.auth.models import User from .models import Profile from django import forms class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'name', 'first_name', 'birdate', 'telnum', 'email', 'aside', 'bside','rebuy', 'balls', 'total') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] class UserForm(forms.ModelForm): class Meta: … -
Serving Static File on Django
I have been trying to serve my static files at my Django project, however it cannot find or load it. I have tried different approaches, but none seems to fix the issue. The static folder is in the same directory as the manage.py. Also, I have installed the WitheNoise but it also did not solve the problem. In addition: I am using docker, I have done the collect static and checked the container. All the files are correctly there. setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') html file {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static "css/bootstrap.css" %}"> <link rel="stylesheet" href="{% static "css/jquery.bxslider.css" %}"> <!-- Custom --> <link rel="stylesheet" href="{% static "css/style.css" %}"> <link rel="stylesheet" href="{% static "css/animate.css" %}"> <title>SOS Media</title> </head> Let me know if there is anything else that I need to add to the post that will help you. Thank you, -
Pytest-Django does not specifically support Django’s multi-db and fails Database access not allowed
I was trying to run the testing with multi-db setup with the unmanaged (read-only) models. when I ran test the import functionality in the serailizers.py is failing and test database is not accessible. settings.py if 'test' in sys.argv or 'test_coverage' in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', }, 'test_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } INSTALLED_APPS += ['test'] pytest.ini [pytest] DJANGO_SETTINGS_MODULE=apps.settings models.py from django.db import models class TestModelA(models.Model): testid = models.CharField(max_length=200) class Meta: managed = False db_table = 'TestD' serializers.py from rest_framework import serializers from apps.services import get_testid class SearchSerializer(serializers.Serializer): application_names = serializers.MultipleChoiceField( choices=get_testid(), required=False, style={'base_template': 'select_multiple.html'} ) services.py from apps.models import TestModelA def get_testid(): return TestModelA.objects.values_list('testid ', flat=True) tests.py import pytest from django.test import RequestFactory, TestCase from appsviews import ( details ) class MyTestCase(TestCase): def setUp(self): self.request = RequestFactory().get('/details/') @pytest.mark.django_db def test_my_function(self): response = details(self.request) self.assertEqual(response.status_code, 200) Error apps/tests/tests.py:4: in <module> from apps.views import ( <frozen importlib._bootstrap>:971: in _find_and_load??? <frozen importlib._bootstrap>:955: in _find_and_load_unlocked ??? <frozen importlib._bootstrap>:665: in _load_unlocked ??? /tmp/lib/python3.6/site-packages/_pytest/assertion/rewrite.py:149: in exec_module exec(co, module.__dict__) apps/views.py:6: in <module> from apps.serializers import ( <frozen importlib._bootstrap>:971: in _find_and_load ??? <frozen importlib._bootstrap>:955: in _find_and_load_unlocked ??? <frozen importlib._bootstrap>:665: in _load_unlocked ??? /tmp/lib/python3.6/site-packages/_pytest/assertion/rewrite.py:149: in exec_module exec(co, module.__dict__) apps/serializers.py:9: in <module> … -
Django API - Chart.js
Im having difficulties using json data from a model in the template. I set the api endpoint, but the data from the model does not come through. views.py class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self,request,format=None): mobilen = Mobiles.objects.all() serializer = DeviceSerializer(mobilen,many=True) labels = ['Jan','Feb','March','Jan','Feb','March','Jan','Feb','March'] out = serializer.data data = { "labels":labels, "default":out, } return Response(data) index.html {% block jquery %} var endpoint = '/api/chart/data/' var defaultData = [] var labels = [] $.ajax({ method: 'GET', url: endpoint, success: function(data){ labels = data.labels defaultData = data.default setChart() }, error:function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: '#', data: defaultData, }] } }) } {% endblock %} I get the data from the labels, but no data from the model in the chart. Thank you for any help -
How to link a profile to a newly created user using Django
Just finished a website using Django and i got stuck after creating a user or superuser. For some reason the same code i used before does not work anymore, and now whenever i create a new user it is saved (because i cant create another one with the same name) but not a profile for it. So now, after the registration form, the user should be redirected to the profile page which brings back an error. If i try to restart the server and login again, same error appears. Here is my signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() and models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) TypeError at /register/ save() got an unexpected keyword argument 'force_insert' -
validate_email python library working on local machine but not on aws elasticbean
validate_email is a python library to verify if an email exists or not.I have been using it in my local machine for a long time but when I made a web app using django,and hosted it on aws elasticbean it is not able to validate and always returns None.code is: from validate_email import validate_email choice="someoneeg@somedomain.com" is_valid = validate_email(choice,verify=True) I suspect if it is problem of some port or some firewall issue ,I have tried adding http listener at port 25 but still it didn't work. I also tried directly using the validate.py file of the developer which is available on github ,still results are same (I have validate_email and Py3DNS installed as required) -
How use class-based views inheritance to override to parent class?
In my ShowChart has model called Electronic(Electronic.objects.values..etc) , in my inheritance class(ChartElectrical) it need to changed to to Electrical (Electronic.objects.values..etc), here i just pass it. I don't know how to do it class ShowChart(View): def get(self, request): my_count = Electronic.objects.values('allocated_time')\ .annotate(complete=Count('allocated_time', filter=Q(batch_18=True)), not_complete=Count('allocated_time', filter=Q(batch_18=False)), complete_1=Count('allocated_time', filter=Q(batch_19=True)), not_complete_1=Count('allocated_time', filter=Q(batch_19=False)), complete_2=Count('allocated_time', filter=Q(batch_20=True)), not_complete_2=Count('allocated_time', filter=Q(batch_20=False)), complete_3=Count('allocated_time', filter=Q(batch_21=True)), not_complete_3=Count('allocated_time', filter=Q(batch_21=False))) class ChartElectrical(ShowChart): pass -
How to use for loop tag inside chart.js template
Hello guys i am having trouble using for loop in chart.js template i do not know how to use for loop tag inside chart.js template in order to get some data dynamically i am unable to find complete tutorial of chart.js and django kindly help me please. template var endpoint = '/api/chart/data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(i){ labels = i.newlabels defaultData = i.newdata var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: '# of Votes', data: defaultData, backgroundColor: "#4e73df", hoverBackgroundColor: "#2e59d9", borderColor: "#4e73df" borderWidth: 1 }] }, }); }, error: function(error_data){ console.log("error") console.log(error_data) } }) views.py class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): qs_count = User.objects.all().count() av = Add.objects.aggregate( bud=Sum('budget'), exp=Sum('expense'), budexp=Sum('budget')-Sum('expense')) # I WANT TO DISPLAY THIS DATA labels = ["Black", "Blue", "Yellow", "Green", "Purple", "Orange"] default_items = [qs_count, 23, 2, 3, 12, 2] data = { "newlabels": labels, "newdata": default_items, } return Response(data)