Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How inheritance works in object-oriented programming in Python
The Question from a noob :) Creating a text field in a model in Django, we do the following: class Book(models.Model): title = models.CharField(max_length=200) CharField, is a class with the following chain of inheritance File: django.db.models.fields.init Classes: class Field(RegisterLookupMixin) / class CharField(Field) And models.Model that is used to registrate a model, in turn, has the following chain of inheritance: File: django.db.models.base Classes: class ModelBase(type) / class Model(metaclass=ModelBase): Questions: How models works when registering a model.CharField ? CharField is not a direct descendant of models, then why can we specify them after each other? When registering a model, we declare class Book(models.Model). Specify CharField in the fields. Why can we do this, despite the fact that they are not directly related by inheritance? -
Creating a list in JavaScript from django variable is autoparsing strings as dates
I'm working in a django project and I'm sending a dataframe with "to_dict" to the template. The dataframe consist of dates and extra info that I deleted for ease of understanding. Im using that data in javascript, but I need the date as a string as the lib I'm using doesn't support date objects for some reason. The problem comes that when I make a list out of the parameter the dates get parsed automatically without me doing anything extra. So for this lines of code: listData = {{data|safe}}; console.log({{data|safe}}); console.log(listData); I get this result: So what i need is that creating a list doesn't parse the string to date and if possible the reason why is this happening. -
KeyError 'Django' and ValueError: source code string cannot contain null bytes
I'm working on an API project. I just stopped my server using CTRL + C as usual only for me to restart the server and i'm getting this error below. I have tried downgrading django but still same error and this the first time i'm having such error since i started this project. from rest_framework import VERSION, exceptions, serializers, status File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\rest_framework\serializers.py", line 27, in <module> import coreapi File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\__init__.py", line 2, in <module> from coreapi import auth, codecs, exceptions, transports, utils File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\codecs\__init__.py", line 3, in <module> from rest_framework.compat import postgres_fields File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\rest_framework\compat.py", line 32, in <module> from coreapi.codecs.corejson import CoreJSONCodec File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\codecs\corejson.py", line 8, in <module> import coreapi File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\__init__.py", line 2, in <module> import coreschema File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreschema\__init__.py", line 6, in <module> from coreapi import auth, codecs, exceptions, transports, utils File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\codecs\__init__.py", line 3, in <module> from coreschema.encodings.html import render_to_form File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreschema\encodings\html.py", line 2, in <module> from coreapi.codecs.corejson import CoreJSONCodec File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreapi\codecs\corejson.py", line 8, in <module> import jinja2 ValueError: source code string cannot contain null bytes import coreschema File "C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\coreschema\__init__.py", line 6, in <module> PS C:\Users\Chika Precious\Documents\GitHub\vicsite> -
How edit the value of post inside serializer in Django?
I am using Django and Django Rest Framework. Below the Register serializer is given and the user's birthday in datetime format. However the birthdate sent inside post is in timestamp format. I want to convert timestamp that posted from user's device to datetime inside serializer. How to do it? class Register_Serializer(serializers.ModelSerializer): password2 = serializers.CharField(style={"input_type": "password"}, write_only=True) class Meta: model = Tuser fields = [Constants.EMAIL, Constants.PASSWORD, Constants.PASSWORD2, Constants.BIRTH_DATE] extra_kwargs = { "password": {"write_only": True} } def save(self): user = Tuser(email=self.validated_data[Constants.EMAIL]) password = self.validated_data[Constants.PASSWORD] password2 = self.validated_data[Constants.PASSWORD2] birthday = self.vlidated_date[Constants.BIRTH_DATE] if password != password2: raise serializers.ValidationError({"password": "Passwords do not match"}) user.set_password(password) user.save() return user -
Django Rest Framework return one model inside another model's detail view
Trying to build a forum clone. There are a list of boards. Each board contains a list of threads. Each thread contains a list of posts. I'm confused about some things. Is the BoardDetail view returning a list of threads the correct approach? I'm not sure how that can be achieved. Here is my attempt. views.py class BoardDetail(generics.ListAPIView): # what needs to be done here to return the threads belonging to a particular board? queryset = Thread.objects.filter() serializer_class = ThreadSerializer models.py class Board(models.Model): name = models.CharField(max_length=25, primary_key=True) created = models.DateTimeField(auto_now_add=True) board_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='board_admin') board_moderator = models.ManyToManyField(User, related_name='board_moderator') class Meta: ordering = ['created'] class Thread(models.Model): title = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) thread_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='thread') board_id = models.ForeignKey(Board, on_delete=models.CASCADE, related_name="thread") class Meta: ordering = ['created'] -
How do I get the id of a Foreign Key
I am trying to autofill these fields if the foreign key is selected The Base Class: class ScreeningCamp(models.Model): beneficiary=models.ForeignKey(Beneficiary,on_delete=models.CASCADE) name=models.CharField(max_length=200,default=Beneficiary.objects.get(id=beneficiary.id).name,blank=True) dob=models.DateField(default=Beneficiary.objects.get(id=beneficiary.id).dob,blank=True) gender=models.CharField(max_length=200,choices=GENDER_CHOICES,default=Beneficiary.objects.get(beneficiary.id).gender,blank=True) fatherName=models.CharField(max_length=200) motherName=models.CharField(max_length=200) careGiver=models.CharField(max_length=200,default=Beneficiary.objects.get(id=beneficiary.id).careGiversName,blank=True,null=True) relationship=models.CharField(max_length=200,choices=RELATIONSHIP_CHOICES,default=Beneficiary.objects.get(id=beneficiary.id).relationship,blank=True,null=True) address=models.TextField(Beneficiary.objects.get(id=beneficiary.id).address,blank=True,null=True) village=models.CharField(max_length=200,default=Beneficiary.objects.get(id=beneficiary.id).village,blank=True,null=True) phone=models.CharField(max_length=13,blank=True,null=True,default=Beneficiary.objects.get(id=beneficiary.id).phone,) designation=models.CharField(max_length=200,choices=DESIGNATION_CHOICES,default=Beneficiary.objects.get(id=beneficiary.id).designation,blank=True,null=True) disability=models.CharField(max_length=200,choices=DISABILITY_CHOICES) visitedBy=models.CharField(max_length=200) def __str__(self): return self.name The Parent Class: class Beneficiary(models.Model): image=models.ImageField(upload_to='home/images/',blank=True,null=True) name = models.CharField(max_length=200) gender=models.CharField(max_length=6,choices=GENDER_CHOICES,default='male') dob=models.DateField() registrationDate=models.DateField() uidOrAadhaar=models.CharField(blank=True,max_length=12,null=True) careGiversName=models.CharField(max_length=200,blank=True,null=True) reletionship=models.CharField(max_length=200,choices=RELATIONSHIP_CHOICES,default='other',blank=True,null=True) beneficiaryType=models.CharField(max_length=200,choices=BENIFICIARY_TYPE_CHOICES,default='active') statusOfBeneficiary=models.CharField(max_length=200,choices=STATUS_OF_BENIFICIARY_CHOICES,default='red') address=models.TextField(blank=True,null=True) district=models.CharField(max_length=200,blank=True,null=True) city=models.CharField(max_length=200) pinCode=models.CharField(max_length=200,blank=True,null=True) addressType=models.CharField(max_length=200,choices=ADDRESS_TYPE_CHOICES,blank=True,null=True) phone=models.CharField(max_length=13,blank=True,null=True) email=models.EmailField(blank=True,null=True) diagonisis=models.CharField(max_length=200,choices=DIAGONISIS_CHOICES) diagnosedBy=models.CharField(max_length=200,choices=DIAGNOSED_BY_CHOICES,default="") informedBy=models.CharField(max_length=200,default='') designation=models.CharField(max_length=200,choices=DESIGNATION_CHOICES,default="") symptomsAsInformed=models.TextField(blank=True,null=True) educationHistory=models.CharField(max_length=200,choices=EDUCATION_HISTORY_CHOICES) maritialStatus=models.CharField(max_length=200,choices=MARTIAL_STATUS_CHOICES,blank=True,null=True) occupation=models.CharField(max_length=200,blank=True,null=True) skill=models.CharField(max_length=200,blank=True,null=True) birth=models.CharField(max_length=200,choices=BIRTH_CHOICES,blank=True,null=True) durationOfIllness=models.CharField(max_length=200,choices=DURATION_OF_ILLNESS_CHOICES,blank=True,null=True) pastPyschiatricIllness=models.CharField(max_length=200,choices=PAST_PYSCHIATRIC_ILLNESS_CHOICES,blank=True,null=True) gp=models.CharField(max_length=200) village=models.CharField(max_length=200) family_history_of_MI_present_or_absent=models.BooleanField(default=False) if_present_schizophrenia_or_mania_or_depression=models.BooleanField(default=False) def __str__(self): return self.name class Meta: verbose_name_plural = "Beneficiaries" I just want to autofill name, dob etc from the beneficiary class when the foreign key is selected When it is not selected we have to manually do it I think just getting the id of the selected object will help Can anyone please tell me how to do that? -
How to fix Django's "too many values to unpack (expected 2)" error?
I was trying to create the sending-verification-code system for the whole afternoon. It's like this: serilizer.py class RegisterationSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True, help_text=_("Enter a valid password")) repeated_password = serializers.CharField(write_only=True, required=True, help_text=_("Enter your password again")) def to_internal_value(self, data): email = data["email"] user = User.objects.get(email=email) if User.objects.filter(email=email, is_active=False).exists(): if VerficationCode.objects.filter(user=user).values("expire_date")[0]['expire_date'] < utc.localize(datetime.now()): VerficationCode.objects.filter(user=user).delete() verification_code = give_code() VerficationCode.objects.create(user=user, code=verification_code) send_mail("Verification Code", f"your code is: {verification_code}", "nima@gmail.com", [email]) return Response({"Message": "A verification code has been sent to your email"}, status=status.HTTP_200_OK) elif VerficationCode.objects.filter(user=user).values("expire_date")[0]['expire_date'] >= utc.localize(datetime.now()): raise serializers.ValidationError(_("Your verification code is still valid")) return super().to_internal_value(data) class Meta: model = User fields = ["email", "username", "name", "password", "repeated_password"] extra_kwargs = { 'email': {'help_text': _("Enter your email")}, 'username': {'help_text': _("Enter your username")}, 'name': {'help_text': _("Enter your name"), 'required': False, 'allow_blank': True}, } def validate(self, data): print(User.objects.filter(email=data["email"], is_active=False)) if data["password"] and data["repeated_password"] and data["password"] != data["repeated_password"]: raise serializers.ValidationError(_("Password and repeated password must be the same")) if data["email"].strip() == data["username"].strip(): raise serializers.ValidationError(_("Email and username must be different")) return data This code is overriding the is_valid() method in the user registration serializer. But when I send another response with the username and password of an account that is existed but it's not active and the first inner if in the to_interval... β¦ -
Django cannot show image
I use django in Ubuntu. I set static_url, static_root, media_url and media_root in settings.py like this code. settings.py DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'static','media') In index.html I set image like this code. index.html <img class="rounded mx-auto d-block" width="25%" src="../media/images/iot_logo.png"> After that, I use command django-admin collectstatic and open website but it not show image. How to fix it? -
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?