Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Usage of AI algorithms to analyze trend and patterns in the digital health field
Main Goal : Analysing and Classification of medicine data using AI. The main goal is to create a web interface to analyse a dataset using various type of algorithm, in real-time. Data set : The dataset to create has some field predetermined on which the algorithms will be implemented and codified let me know some example of data sets i Mean which data set is suitable for this and how to solve this, i have no idea could you guys please help me with some links -
How to inherent from a class that is already inherited from AbstractBaseUser in Django
I am trying to make an inheritance from a User class that is already inherited from the AbstractBaseUser but I am receiving an error that is telling me AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed, I wonder how can I superpass this error and successfully inherent from the User Class this is the code: from time import timezone from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models class ResidentType(models.TextChoices): Family = ('FM', 'Family') Individual = ('IV', 'Individual') class UserManager(BaseUserManager): def create_user(self, username, first_name, last_name, email, password=None): if username is None: raise TypeError('User must have a username') if email is None: raise TypeError('User must have an Email') if first_name is None: raise TypeError('User must have a first_name') if last_name is None: raise TypeError('User must have a last_name') user = self.model(username=username, first_name=first_name, last_name=last_name, email=self.normalize_email(email), ) user.set_password(password) user.save() return user def create_admin(self, username, first_name, last_name, email, password=None): if username is None: raise TypeError('User must have a username') if email is None: raise TypeError('User must have an Email') if first_name is None: raise TypeError('User must have a first_name') if last_name is None: raise TypeError('User must have a last_name') admin = self.model(username=username, first_name=first_name, last_name=last_name, email=self.normalize_email(email), ) admin.set_password(password) Admin.admin β¦ -
Sentistrength setpath, method webapp django
I am trying to make a web application based on "sentistrenght" in django,html,css. how can i configure the absolute path for the .setpath method in sentistrength on the web server/hosting only this is holding the webapp back or its running like a charm on local host senti.setSentiStrengthPath('E:\college data\Final Year Project\Code\Final code\TensiStrength\TensiStrengthMain.jar') senti.setSentiStrengthLanguageFolderPath('E:\college data\Final Year Project\Code\Final code\TensiStrength\TensiStrength_Data') Anyone know anything? i tried senti.setSentiStrengthPath('.\sentistrength_files\TensiStrengthMain.jar') senti.setSentiStrengthLanguageFolderPath('.\sentistrength_file\TensiStrength_Data') but it does not work -
Record 15 sec video from webcam and store it in database in Django
Actually I was working on AI project to perform some processing on the video and I want to integrate this functionality with Django but I don't know how to Record the video and upload it to Django if you can guide me I will very appreciate that I have tried videojs-record library of JS but it is not working as I wish it to work -
Testing form_valid method in Django CreateView
I've been trying to test the form_valid() method in my Django createView and the assertion keeps returning false and i've tried using a normal post request with the client and also using the request factory but the outcomes are same. Below is my view and the approaches i've tried to used in doing the testing. class TextView(CreateView): model = Text form_class = TextForm @transaction.atomic() def form_valid(self, form): self.object = form.save() for i in range(1, form.cleaned_data.get('number_of_pages')+1): Page.objects.create(text=self.object, number=i) return super().form_valid(form) Below are the test i've class TestTextView(TestCase): def setUp(self): self.form_data = { 'name': 'test', 'template': SimpleUploadedFile('test.pdf', b'content') } def test_one(self): form = TextForm(data=self.form_data) self.assertTrue(form.is_valid()) def test_two(self): request = RequestFactory().post('/text') view = TextView() view.setup(request) form = view.form_valid(form=self.form_data) self.assertTrue(form.is_valid()) Both test are supposed to validate the form . But unfortunately this isn't the case. -
bash: open all django project app file on Mac
I am on a Mac with bash in terminal, I love writing bash scripts to speedup my developing: .bash_profile source /Users/qinyiqi/.bashrc .bashrc # command style PS1="πΉ " export PS1 cls(){ clear; pwd } randint(){ echo $(shuf -i $1-$2 -n 1) } canvas(){ startm cd /Applications/MAMP/htdocs/canvas/src if [ $# -eq 0 ]; then sublime draw.html sublime draw.css sublime draw.js open "http://localhost:8888/canvas/src/draw.html" else if [ ! -f "$1.html" ]; then # file not found touch "$1.html" fi if [ ! -f "$1.css" ]; then touch "$1.css" fi if [ ! -f "$1.js" ]; then touch "$1.js" fi sublime "$1.html" sublime "$1.css" sublime "$1.js" open "http://localhost:8888/canvas/src/$1.html" fi open . ls } now I am working with django, it has a basic app structure such as . βββ manage.py βββ media β βββ profile β βββ default.jpg βββ articles β βββ __init__.py β βββ admin.py β βββ apps.py β βββ models.py β βββ tests.py β βββ urls.py β βββ views.py βββ questions β βββ __init__.py β βββ admin.py β βββ apps.py β βββ models.py β βββ tests.py β βββ urls.py β βββ views.py βββ tags β βββ __init__.py β βββ admin.py β βββ apps.py β βββ models.py β βββ tests.py β βββ urls.py β β¦ -
how to fix tid is a key error - kakao pay in django app
hello I want to use kakao pay in my django app, I have installed django-pf-billing package in my settings.py # settings.py INSTALLED_APPS = [ ... 'pf_billing', ] KAKAOPAY_CID = "my kakaopay cid" KAKAOPAY_APP_ADMIN_KEY = "my kakao app admin key" I Run python manage.py migrate to create a Billing model. I Registered my domain in Kakao developers to get the CID and the key admin, but since I am working in the localhost .what should I put as link in my kakao developers application there to make a test?. in my views.py @login_required def kakaoPay(request): return render(request, 'base/kakaopay/kakaopay.html') @login_required def kakaoPayLogic(request): _admin_key = 'I put here my admin key from' # μ λ ₯νμ _url = f'https://kapi.kakao.com/v1/payment/ready' _headers = { 'Authorization': f'KakaoAK {_admin_key}', } _data = { 'cid': 'TC0ONETIME', 'partner_order_id':'partner_order_id', 'partner_user_id':'partner_user_id', 'item_name':'selectedUser', 'quantity':'1', 'total_amount':'1.55', 'tax_free_amount':'0', # λ΄ μ ν리μΌμ΄μ -> μ±μ€μ / νλ«νΌ - WEB μ¬μ΄νΈ λλ©μΈμ λ±λ‘λ μ λ³΄λ§ κ°λ₯ν©λλ€ # * λ±λ‘ : http://IP:8000 'approval_url':'http://127.0.0.1:8000/paySuccess', 'fail_url':'http://127.0.0.1:8000/payFail', 'cancel_url':'http://127.0.0.1:8000/payCancel' } _res = requests.post(_url, data=_data, headers=_headers) _result = _res.json() request.session['tid'] = _result['tid'] return redirect(_result['next_redirect_pc_url']) @login_required def paySuccess(request): _url = 'https://kapi.kakao.com/v1/payment/approve' _admin_key = 'I put here my admin key from' # μ λ ₯νμ _headers = { 'Authorization': f'KakaoAK {_admin_key}' } _data = { 'cid':'TC0ONETIME', 'tid': request.session['tid'], 'partner_order_id':'partner_order_id', 'partner_user_id':'partner_user_id', β¦ -
Django - Returning paged set of objects as a JSON response
I am using Django 3.2 I want to return a paged set of records as JSON. Here is my code snippet: class GetCommentChildren(SocialAppUserMixin, View): def post(self, request, *args, **kwargs): comment_id = self.request.POST['pid'] pagenum = self.request.POST.get('page', 1) comments_per_page = self.request.POST.get('per_page', 10) retval = False comments = [] try: comment = Comment.objects.get(id=comment_id) children = comment.get_children() paginator = Paginator(children, comments_per_page) try: comments = paginator.page(pagenum) except PageNotAnInteger: comments = paginator.page(1) except EmptyPage: comments = paginator.page(paginator.num_pages) except ObjectDoesNotExist: logger.exception(f"Caught ObjectDoesNotExist exception in GetCommentsChildren::post(). Comment id: {comment_id}") except Exception as e: logger.exception(f"Caught Exception in GetCommentsChildren::post(). Details: {e}") return JsonResponse({'ok': retval, 'comments': comments}) How do I return a paged set of records as JSON? -
Django password reset not sending mail
when i am resetting my password in django everything goes well but i am not getting any mail . urls.py path('password_reset/',auth_views.PasswordResetView.as_view(success_url=reverse_lazy('blogapp:password_reset_done')),name='password_reset'), path('reset_password_sent/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done'), path('password_reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='blogapp/password_reset_confirm.html',success_url=reverse_lazy('blogapp:password_reset_complete')),name='password_reset_confirm'), path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete'), ] -
Django doesn't use atomic transactions by default?
I read the django documentation about Database transactions. Then, this section says: Djangoβs default behavior is to run in autocommit mode. Each query is immediately committed to the database, unless a transaction is active. So, as the section says, Django doesn't use atomic transactions by default? So, if Django doesn't use atomic transactions by default, when updating data in Django Admin Panel, there can be Race Condition right? -
How to solve refused to connect problem in Kibana?
I wrote a function for creating charts in Kibana. Firstly, I installed Kibana and Elasticsearch on my local PC. I am sending a request for creating data and charts and taking the embedded iframe code from there. In this scenario everything is okay. I could create charts clearly and my functions are working great. I could show charts on my page. Then I installed my project, kibana and elastic search on a server. And I get this error inside of the iframe tag: 2**...**6 refused to connect. What can be the problem? part of my functions elasticsearch_address= 'http://localhost:9200' self.es = Elasticsearch([elasticsearch_address], use_ssl=False, verify_certs=False, ssl_show_warn=False, send_get_body_as='POST', ) It works fine. I can get and post requests to this address. So, I think the problem is in Kibana. part of my functions url3 = "http://localhost:5601/api/saved_obj..." headers3 = {"Accept-Language": "tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Referer": "http://localhost:5601/app/management/kibana/objects", "Content-Type": "multipart/form-data; boundary=-..." "Origin": "http://localhost:5601", "kbn-xsrf": "true", "Sec- Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin"} data3 = "--...." r3 = requests.post(url3, headers=headers3, data=data3) destinationid = re.findall(r"\"destinationId\":\"(.*?)\"", r3.text) destinationid = destinationid[-1] request_text = "http://localhost:5601/app/dashboards#..." user = request.user user.iframe = request_text.replace("localhost", "2**.***.***.**") user.save() in the part of user.iframe, I get the iframe code. I change it with the server's IP number β¦ -
Django - How to make a current object "ImageField attribute" as the pre-defined value in a Update_Object view?
I'm creating an update view using django-form for updating one of my objects that have the following fields: class Object(models.Model): name = models.CharField(max_length=40) logo = models.ImageField(upload_to='object_logo/') text_1 = models.TextField() text_2 = models.TextField() So, i have created the following form in forms.py: class ObjectForm(forms.ModelForm): class Meta: model = Object fields = [ 'name', 'logo', 'text_1', 'text_2', ] labels = { 'name': 'Name', 'logo': 'Logo', 'text_1': 'Text 1', 'text_2': 'Text 2', } and defined the following view called update_object: def update_object(request, value): object = get_object_or_404(Object, pk=value) if request.method == "POST": form = ObjectForm(request.POST, request.FILES) if form.is_valid(): object.name = form.cleaned_data['name'] object.logo = form.cleaned_data['logo'] object.text_1 = form.cleaned_data['text_1'] object.text_2 = form.cleaned_data['text_2'] object.save() return HttpResponseRedirect(reverse('myApp:detail_object', args=(value, ))) else: form = ObjectForm( initial={ 'name': object.name, 'logo': object.logo, 'text_1': object.text_1, 'text_2': object.text_2, } ) context = {'object': object, 'form': form} return render(request, 'myApp/update_object.html', context) My problem is: even with an "initial" value stetted up for logo, i have to select an image every time i will update my object (otherwise i receive the update_object page with the message "This field is required"). Is there a way to make the current object.logo as the pre-defined value of the input in my ObjectForm in the update_object view? I've already tried β¦ -
ImportError: cannot import name 'url' from 'django.conf.urls'
ImportError: cannot import name 'url' from 'django.conf.urls' (/home/chams/pfe_project/CarApp/venv/lib/python3.8/site-packages/django/conf/urls/_init_.py) I can't find any mistakes in my code ! -
add expire time for validation and verification in Djoser
I'm using Django==4.0.3 ,djangorestframework==3.13.1 and djangorestframework-simplejwt==5.1.0 and djoser==2.1.0 I have used djoser to authenticate, and all works fine. how can add expiration datetime for validation and verification link in Djoser ? any idea ? -
Error when running βvirtualenv <name>β command
Iβve tried a lot of things but itβs not working, itβs hitting me up with a prompt msg ββvirtualenvβ is not recognized as an internal or external command β Any solutions? -
Django error cannot import name 'views' from 'device' (unknown location)
I can create django project to run in server without error. After that, I upload project from my computer to replace same project name in the server. Then, it show error like this. Exception Type: ImportError at / Exception Value: cannot import name 'views' from 'device' (unknown location) In urls.py still import views like this code. from django.contrib import admin from django.urls import path from device import views from django.conf.urls.static import static from django.conf import settings It have no problem in my computer but it have problem when upload to server. where I should to check path? How to fix it? -
Revalidate on-demand a Next.js site from Django model's save method
I have a next.js site deployed to Vercel, that fetches data from an API provided by Django. Next.js has this new feature (Incremental Static Regeneration On-Demand) where you can rebuild a specific page without need to rebuild the entire site with an url like this: https://<my-site.com>/api/revalidate?secret=my-token I need the next.js site rebuild some pages when the database changes, so it shows the new data, and i tried to make a request (with requests package) in the save method like this: def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) r = requests.get("https://<my-site.com>/api/revalidate?secret=<my-token>") It seems to work when it trigger that url from my browser, but it doesn't work when i trigger it from Django. The response of this Response object (r) is a 200 Status Code, as expected, with {"revalidated":true} (r.text), but it doesn't update the site anyways. How can i implement this? -
Build folder ./build does not exist
I was trying to deploy my django project using render and I am getting this error that build does not exists.. I have no idea how to fix this. Can anyone help? I tried to look for any solutions on the internet but could not find any...I don't know if I typed any code wrong or am I missing some commands. -
Manager isn't available auuth.User has been swapped
As a precursor to asking, I have already looked at a few similar questions and answers. I am trying to extend my user class to include other fields and then pass down these extra fields as payload on my access_token. I get this error message when I try to run makemigrations/migrate or run my code AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomerUser' This is what I have in models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser # #extending user model to include class CustomerUser(AbstractUser): city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) serializers.py: from django.contrib.auth import get_user_model User = get_user_model() class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'bio'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], city=validated_data['city'], country=validated_data['country'], bio=validated_data['bio'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user #customizing the payload we get from our access tokens class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.country token['city'] = user.city token['bio'] = user.bio return token class UserSerializer(serializers.ModelSerializer): class Meta: model = User β¦ -
Adding extended user class fields to payload data in access token
I extended my user class to include other fields (city, country, bio). I would like to pass these down along to customizing my JWT access_token to include these fields as a payload in addition to username. This is what I have in my models.py (extending my user class): from django.db import models from django.contrib.auth.models import User #extending user model to include class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) def __str__(self): return self.user.username serializers.py: #changed from serializers.HyperLinked to ModelSerializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = Profile #removed url from fields fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'bio'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = Profile.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], city=validated_data['city'], country=validated_data['country'], bio=validated_data['bio'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user #customizing the payload we get from our access tokens class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.profile.country token['city'] = user.profile.city token['bio'] = user.profile.bio return token and api.py #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer #remove this if it doesn't work authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) β¦ -
How the through model object is created in django?
I want to overwrite a creation of M2M through model object. I thought that overwriting save method will be sufficient, but it appears that after saving admin form, the method is not called. I am having a hard time finding how this object is created. Here is the code snippet class ProductVariantToAttributeValue(models.Model): product_variant = models.ForeignKey(ProductVariant, on_delete=models.CASCADE) attribute_value = models.ForeignKey(AttributeValue, on_delete=models.CASCADE) attribute = models.ForeignKey( Attribute, on_delete=models.CASCADE, null=True, blank=True ) class Meta: db_table = "productvariants_to_attributevalues" unique_together = [("product_variant", "attribute")] verbose_name_plural = "Product Variants To Attribute Values" def save(self, **kwargs): self.attribute = self.attribute_value.attribute super().save(**kwargs) -
DRF Framework - allow User CRUD on another Users related field if they are in relationship through another model
I have a model Application that has fields applicant = ForeignKey('User'...) and coapplicant = ForeignKey('User'...). There is also a model Income that has field user = ForeignKey('User'.... I want to allow User A to create, edit, delete Income objects of User B if A and B are in a relationship through Application. That means: User A can CRUD Incomes of User B and vice-versa if there is such Application object where A is an applicant and B co-applicant or A is a co-applicant and B applicant. Do you know how to make that work? -
Django multiple image upload like ecommerce website
I want to let the user upload multiple images per model as Instagram or Amazon does. Till now I have title and featured_images fields in my model but the "multiple" attribute seems not to work. Thanks models.py class Project(models.Model): title = models.CharField(max_length=200) featured_images = models.ImageField(null=True, blank=True) forms.py class ProjectForm(ModelForm): class Meta: featured_images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) model = Project fields = ['title', 'featured_images'] views.py def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST, request.FILES.getlist('featured_images')) if form.is_valid(): project = form.save(commit=False) project.save() context = {'form':form} return render(request, 'projects/project_form.html', context) project_form.html <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <input type="submit" name="" id=""> </form> -
How to fetch integer values from the Django objects?
I already created integerField for saving data in the model. But showing the bellow error. How can I convert a string list into an integer list? Django Model: class Frontend_Rating(models.Model): Rating = models.IntegerField( null=True) Views: #index def index(request): frontend_all_ratings = Frontend_Rating.objects.all() number_of_frontend_rating = frontend_all_ratings.count() frontend_rating_list = [] total_ratings = 0 for frontend_rating_item in frontend_all_ratings: frontend_rating = int(frontend_rating_item.Rating) frontend_rating_list.append(frontend_rating) total_ratings = total_ratings+frontend_rating_list[frontend_rating_item] context = { "number_of_frontend_rating":number_of_frontend_rating, "frontend_rating_list":frontend_rating_list, "total_ratings":total_ratings } return render(request,'0_index.html',context) Erorr: TypeError at / list indices must be integers or slices, not Frontend_Rating Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: TypeError Exception Value: list indices must be integers or slices, not Frontend_Rating Exception Location: D:\1_WebDevelopment\Business_Website\business_app\views.py, line 33, in index Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 -
Catch errors in password validation in Django
i have a problem. I'm trying to catch errors from password validation in Django, but I don't know how to do it. Password validation is called in forms.py, and form.isValid() is called in views.py I'd like to know exactly what errors has been found in the password validation called in forms.py, so i can do use an if to launch a bootstrap warning chosen by me. Here is the code: forms.py class RegistrationForm(forms.Form): username = forms.CharField(label="Inserisci username", max_length=50) password = forms.CharField(label="Inserisci password", widget=forms.PasswordInput) repeatPassword = forms.CharField(label="Ripeti password", widget=forms.PasswordInput) def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError('Nome utente giΓ in uso') return username def clean_password(self): username = self.cleaned_data['username'] password = self.cleaned_data['password'] validate_password(password, username) return password def clean_password2(self): password = self.cleaned_data['password'] repeatPassword = self.cleaned_data['repeatPassword'] if password != repeatPassword: raise forms.ValidationError('Le password devono corrispondere') return password views.py def registration(request): if request.method == "POST": registrationForm = RegistrationForm(request.POST) if registrationForm.is_valid(): # Creazione utente username = RegistrationForm.cleaned_data['username'] password = RegistrationForm.cleaned_data['password'] playerStatistics = Statistics(health=randint(90, 110), armor=0, strength=randint(5, 15), speed=randint(15, 25), dexterity=randint(15, 25)) equipmentStatistics = Statistics(health=0, armor=0, strength=0, speed=0, dexterity=0) playerStatistics.save() equipmentStatistics.save() equipment = Equipment(statistics=equipmentStatistics) equipment.save() inventory = Inventory() inventory.save() newPlayer = Player(username=username, password=password, statistics=playerStatistics, equipment=equipment, inventory=inventory) newPlayer.save() return render(request, "playerHome.html") else: return HttpResponse("Errore nell'inserimento dei dati") β¦