Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
boto3 conflict with endpoint url and bucket causing error
The correct file url from S3: https://video-sftp.s3.amazonaws.com/600.mp4 Now when attempt to generate presigned url with boto3 the file url is incorrect: https://video-sftp.s3.amazonaws.com/video-sftp/600.mp4 the bucket name is being appended as directory? AWS_S3_ENDPOINT_URL='https://video-sftp.s3.amazonaws.com' AWS_S3_REGION_NAME='us-east-1' Here is code: def post(self, request, *args, **kwargs): session = boto3.session.Session() client = session.client( "s3", region_name=settings.AWS_S3_REGION_NAME, endpoint_url=settings.AWS_S3_ENDPOINT_URL, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) url = client.generate_presigned_url( ClientMethod="put_object", Params={ "Bucket": "video-sftp", "Key": f"{json.loads(request.body)['fileName']}", }, ExpiresIn=300, ) return JsonResponse({"url": url}) It appears to be looking for directory video-sftp in the bucket video-sftp? How do i solve? I've tried changing the endpoint url to https://s3.us-east-1.amazonaws.com, which results in 403 forbidden. I have updated CORs policy to allow PUT. -
How to setup django rest framework app outside project
I want to setup app app2 outside project directory. If you check following screenshot, I have created djnago project project, inside this project, created app app1 and created app 'app2' outside project. Now how to include app2 and urls.py in project settings and urls.py. INSTALLED_APPS = [ . . '../common_functions/app2', ] I tried above but getting errors: **TypeError: the 'package' argument is required to perform a relative import for ../common_functions/app2 -
Deleting User not working due to ManyToMany fields on another app
I am using django-tenants and django_tenant_users with the following apps (settings.py): SHARED_APPS = ( 'django_tenants', 'django.contrib.contenttypes', 'tenant_users.permissions', # Defined in both shared apps and tenant apps 'tenant_users.tenants', # defined only in shared apps # everything below here is optional ... 'tenants', # list the app where your tenant model resides in. Must NOT exist in TENANT_APPS 'apps.users', # Custom app that contains the new User Model. Must NOT exist in TENANT_APP 'debug_toolbar', ) TENANT_APPS = ( # for django-tenant-users 'django.contrib.auth', # Defined in both shared apps and tenant apps 'django.contrib.contenttypes', # Defined in both shared apps and tenant apps 'tenant_users.permissions', # Defined in both shared apps and tenant apps # your tenant-specific apps 'apps.jobs', ) And this is my jobs models.py: class Job(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) title = models.CharField(_('Title'),max_length=80, blank=True, default="") details= models.CharField(_('Details'), max_length=250, blank=True, default="") jobarea = models.ForeignKey('JobArea', verbose_name="Job Area", on_delete=models.CASCADE, null=True) def __str__(self): return self.title class JobArea(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) name = models.CharField(_('Title'),max_length=80, blank=True, default="") details = models.CharField(_('Details'), max_length=250, blank=True, default="") owners = models.ManyToManyField(settings.AUTH_USER_MODEL) def __str__(self): return self.name class Urel(models.Model): employee = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) job = models.ForeignKey('Job', on_delete=models.CASCADE) When I try to delete a User that is on the public tenant, I get the following error: relation "jobs_jobarea_owners" does not exist … -
Update Django model field when actions taking place in another model
I want to make changes in a model instance A, when a second model instance B is saved,updated or deleted. All models are in the same Django app. What would be the optimal way to do it? Should I use signals? Override default methods[save, update,delete]? Something else? Django documentation warns: Where possible you should opt for directly calling the handling code, rather than dispatching via a signal. Can somebody elaborate on that statement? -
Record not getting edited in django form using instance
The model is not getting updated in the database while using the below methods. This is upload form in views This is my edit function in views Tried editing the record but it is not getting updated. -
Auto hide Row / Column of Table if specific field exists in MySQL Database using Django
I am working on a Django project and I am stuck in a situation where I want to hide a row in a table if specific entity exists in column in database. I am using MYSQL database. I want auto hide row without clicking on any button or any checkbox. page.html: <table border="2"> <tr> <th> ID</th> <th> NAME</th> <th> PASSWORD</th> <th> IP</th> <th>PORT</th> </tr> {% for data in Cvs_logs %} <tr> <td>{{data.id}}</td> <td>{{data.user}}</td> <td>{{data.pass}}</td> <td>{{data.ip}}</td> <td>{{data.port}}</td> </tr> {% endfor %} </table> views.py: def home_view(request): auth = Cvs_logs.objects.all() return render(request, 'page.html', {'Cvs_logs': auth }) models.py: class Cvs_logs(models.Model): id = models.BigIntegerField ip = models.CharField(max_length= 100) port = models.CharField(max_length= 100) user = models.CharField(max_length= 100) pass = models.CharField(max_length= 100) class Meta: db_table = "xyz" The condition is if name == 'abc', then It should hide data automatically without clicking on any button -
Call one serializer's update() method from another serilaizer's create() method
I have 2 serializers serializer_1 and serializer_2 which are both model serilizer i want to execute update method of serializer_1 from create method of serializer_2 how can i achieve that? class serializer_1(serializers.ModelSerializer): date = serializers.DateTimeField(required=False, allow_null=True) ispublic = serializers.BooleanField(allow_null=False) details_api_url = serializers.SerializerMethodField() dispute_types = OtherSerializer(many=True, required=False, write_only=True) nature_of_dispute_list = serializers.SerializerMethodField() plaintiff = OtherSerializer(many=True, required=False, write_only=True) defendant = OtherSerializer(many=True, required=False, write_only=True) claims_rep = OtherSerializer(many=True, required=False, write_only=True) class Meta: model = Media fields = "__all_" def update(self, instance, validated_data): date = validated_data.pop('close_out_date', None) plaintiff_data = validated_data.pop('plaintiff', []) defendant_data = validated_data.pop('defendant', []) claims_rep_data = validated_data.pop('claims', []) is_summary_public_previous = instance.is_summary_public obj = super().update(instance, validated_data) return obj class serializer_2(serializers.ModelsSerializer): class Meta: model = Fedia fields = "__all__" def create(self, validated_data): request = self.context['request'] serilizer_1_data = validated_data.pop('serialzer_1_data', None) is_final = validated_data.get('is_final') serializer_1_object = Media.object.create(**serializer_1_data) if is_final: **Call Serializer Update method** -
Expired access token accpeted and return the data from view in django
I'm creating an app that sends both a refresher and access tokens; also, in this app, there are a ModelViewSet called Users (returns all users in the database) where permission_classes for the IsAuthenticated only, everything seems to work perfectly. But when the access token expires and sets the header for the Authentication = 'Bearer ${access_token},' the ModelView returns the data despite the expiration of the access_token, and checks the same token with the TokenVerifyView, its returns: { "detail": "Token is invalid or expired", "code": "token_not_valid" } I'm using rest_framework and rest_framework_simplejwt the ACCESS_TOKEN_LIFETIME equal to 10sec and the DEFAULT_AUTHENTICATION_CLASSES are the default from the lib itself class UserViewSet(ModelViewSet): permission_classes = [permissions.IsAuthenticated,] queryset = User.objects.all() serializer_class = UserSerializer SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } Should I create an authentication class and add it to the DEFAULT_AUTHENTICATION_CLASSES, or is there a predefined way to handle this problem, so if the token is expired, return status with … -
How to modify django's request.user in a Middleware?
What I'm trying to do is to detect the type of logged-in user and then setting a .profile parameter to request.user, so I can use it by calling request.user.profile in my views. To do this, I've wrote a Middleware as follows: class SetProfileMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user, token = JWTAuthentication().authenticate(request) profile_type = token.payload.get("profile_type", None) request.user.profile = User.get_profile(profile_type, request.user) request.user.profile_type = profile_type response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): print(request.user.profile) # Works here Now I can access request.user.profile in process_view however it does not exists in my views an causing an AttributeError stating that 'User' object has no attribute 'profile'. Seems my request.user is being overwritten by somewhere before hitting the view. -
How to prevent erasing data from django form?
I have two forms and two submit buttons. Because I can uplaod a pdf file and a excel file. But if I upload a pdf file and then I upload a excel file. The content of the pdf file will be erased. And vice versa. So I have it like this: <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id=""> <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_pdf" onclick="test()" class="btn btn-warning"> Upload! </button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </form> </div> </span> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id=""> <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" onclick="test()" class="btn btn-warning"> Upload! </button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="" cols="65" rows="25"> {{content_excel}}</textarea> </div> </div> </form> </div> </span> </div> <script type="text/javascript"> </script> </body> and one of my forms looks like in view.py: def post(self, request): filter_text = FilterText() extract_excel_instance = ExtractingTextFromExcel() types_of_encoding = ["utf8", "cp1252"] submitted_form = ProfileForm(request.POST, request.FILES) content = '' content_excel = '' if request.POST.get('form_pdf') is not None: if submitted_form.is_valid() and request.POST: uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() for encoding_type in types_of_encoding: with … -
Calling ListView Class from UpdateView class in Django
I am trying to call DealerEmployeeView class from DealerUpdateView Class. Problem is my DealerUpdateView class does not work without mentioning ModelFormMixin in class chain inheritance. But when I mention DealerEmployeeView after ModelFormMixin it cause an error TypeError: Cannot create a consistent method resolution order (MRO) for bases object, TemplateResponseMixin, ModelFormMixin, DealerEmployeeView Is there way to solve this class inheritance problem without creating new class view? DealerUpdateView class DealerUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView, ModelFormMixin, DealerEmployeeView): permission_required = '' model = Dealer fields = ['dealer_name', 'contact_name', 'contact_surname', 'partita_iva', 'email', 'phone_number', 'description'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) DealerEmployeeView class DealerEmployeeView(ListView): order_type = 'asc' def get(self, request, *args, **kwargs): dealer_id = kwargs['pk'] dealer_employees = User.objects.filter(dealer_id=dealer_id) if 'search_employee' in request.GET: filtered_name = request.GET.get('search_employee') filtered_dealer_employees = dealer_employees.filter(first_name__icontains=filtered_name) context = {'dealer': filtered_dealer_employees, 'form_employee': DealerEmployeeCreationForm, 'dealer_id': dealer_id, 'DEALER_ROLES_TRANSLATED': User.DEALER_ROLES_TRANSLATED, 'order_type': self.order_type} return render(request, 'comprital/add_distributor_field.html', context) -
Python makemigrations does not work right
I use Django framework This is my models.py from django.db import models # Create your models here. class Destination(models.Model): name: models.CharField(max_length=100) img: models.ImageField(upload_to='pics') desc: models.TextField price: models.IntegerField offer: models.BooleanField(default=False) and here is my migrations folder-0001_initial.py: # Generated by Django 4.1.3 on 2022-11-17 10:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Destination', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] it don't migrate my model, i deleted 0001_initial.py and pycache and migrate again but it worked the same How can i make migrations with my models ? -
TypeError: Connection.__init__() got an unexpected keyword argument 'username'
I have integrate the celery with Django in our project but getting this error when I am running the celery server with this command my project name is claims_dashboard: python -m celery -A claims_dashboard worker Error: TypeError: Connection.__init__() got an unexpected keyword argument 'username' I followed documentation given here: celery integrate with django -
can't multiply sequence by non-int of type 'QuerySet'
I just start learn django, and i want to ask to solve my problem here my models.py class LotSell(models.Model): rate = models.DecimalField(max_digits=5, decimal_places=4) at django admin input with value 0,0666 or something views.py def result(request): price_buyer = request.GET['price_buyer'] temp_price = LotSell.objects.values_list('rate') tot_price = price_buyer * temp_price data = { 'tot_price': tot_price, } return render(request, 'resultsell.html', data) resultsell.html <body> {{tot_price}} </body> index.html <form action="{% url 'resultsell %}" method="get"> {% csrf_token %} <input type="text" name="price_buyer"> <br> <button type="submit"> Submit</button </form> in the end, i want to showing to user with the total price by: rate (input by admin as decimal or percentage) multiply the price_buyer where input by user Thank you -
Pushing existing repository to local git project
After creating repository, I got 3 lines of code 1.git remote add origin https://github.com/Username/profiles-rest-api. 2.git git branch -M main 3. git push -u origin main When am copy pasting it in git bash, after pasting 3-line code (git push -u origin main) it is showing me as $ git push -u origin main fatal: helper error (-1): User cancelled dialog. error: unable to read askpass response from 'C:/Program Files/Git/mingw64/bin/git-askpass.exe' Username for 'https://github.com': remote: No anonymous write access. fatal: Authentication failed for 'https://github.com/Vijaya-1106/profiles-rest-api.git/' Why this is happening I tried this so many times, but I got the same error -
Python: Get multiple id's from checkbox
I wanted to get multiple id's from a list using checkbox. I got an error Field 'id' expected a number but got []. Below is my code. sample.html <button href="/sample/save">Save</button> {% for obj in queryset %} <tr> <td><input type="checkbox" name="sid" value="{{obj.id}}"></td> <td>{{ obj.sample_name }}</td> <td>{{ obj.sample_type}}</td> <td>{{ obj.number}}</td> </tr> {% endfor %} views.py def sample(request): if request.method == 'GET': queryset = SampleList.objects.all() return render(request, 'lab_management/sample_out.html', {'queryset': queryset}) def save_doc(request): sid = request.POST.getlist('sid') sample = SampleList.objects.filter(id=sid)[0:10] template = DocxTemplate("doc.docx") context = { 'headers' : ['Name', 'Type', 'Number'], 'doc': [], } for samp in sample: list = [samp.name, samp.type, samp.number] context['doc'].append(list) template.render(context) template.save('new_doc.docx') -
How to verifify Shopify webhook in Django?
How can I verify the incoming webhook from Shopify? Shopify provides a python implementation (of Flask), but how can I do it in Django/DRF? -
Unable to perform user registration with Facebook using allauth and django-rest-auth. getting incorrect value error
I am trying to implement social authentication, I am using django-allauth, django-rest-auth for this. my views from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client class FacebookLoginView(SocialLoginView): adapter_class = FacebookOAuth2Adapter client_class = OAuth2Client on making post request in the above view with access_token it returns the error {"non_field_errors":["Incorrect value"]} -
How to pass data from frontend to admin by using ForeignKey
how to pass data from frontend to backend usinf Fk in Djnago. if requset.method == "POST": Person_name=requset.POST["Person_name"] gender=requset.POST["gender"] #print(Person_name,gender) #data1=Gender(gender=gender) data2=People(Person_name=Person_name,gender=gender) #data1.save() data2.save() -
Filter birthday with less than 60 months Django
model.py class Preschooler(Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birthday = models.DateField(null=True, blank=True) def age_months(self): today = date.today() date_diff = today - self.birthday in_days = date_diff.days return int((in_days) / (365 / 12)) I want to filter preschooler that are less than 60 months using their birthday like this: Preschooler.objects.filter(birthday__month__lst=60) How can I achieve this? Thank you. -
Using jinja variable as dictionary key
I'm making a django app to do with tests/exams. Two of the models in this app are the "Question" and "Answer" model which have a one-to-many relationship. On the page, each question will be listed with all of its possible answers below it which the user can choose from. In my views.py file, after getting the list of question objects, the best way I thought of for storing the answers was in a dictionary like so: answers = {} for question in questions: answers[question.id] = Answer.objects.filter(question=question.id) Then, for the template, I thought I would be able to do something like: {% for question in questions %} <h2>{{ question.title }}</h2> <ul> {% for answer in answers.{{ question.id }} %} <li>{{ answer.title }}</li> {% endfor %} </ul> {% endfor %} The error arises in this line - {% for answer in answers.{{ question.id }} %}. I've tried rewriting this line as per this post which suggested things like: {% for answer in answers[question.id] %} and {% for answer in answers.get(question.id) %} but none of these worked. Please let me know if there is a syntax in Jinja that allows this or else if there is a better way of me passing the … -
Saving multiple data entries to database with Django
in my project that I created with django, I duplicate the data entries with the help of a button, but when I want to save them to the database, it always saves the last added data. models.py medications = models.CharField(max_length=200, null=True,blank=True) scale_used = models.CharField(max_length=200, null=True,blank=True) views.py if request.method == "POST" and 'registrationSave' in request.POST: records = Records() records.medications = request.form.getlist('medications[]') records.scale_used = request.form.getlist('scale_used[]') print(records.medications) print(records.scale_used) records.save() return redirect('/index/tables') else: return render(request,'registration_form.html') registration.html <div class="row" id="InputsWrapper"> <div class="row justify-content-start"> <div class="col-4"> <!-- <textarea type="text" class="form-control" id="record_medications" name="medications" style="height: 100px" placeholder="İlaçlar" required></textarea> --> <label for="">İlaç Adı:</label> <select class="form-select form-select-lg" name="medications[]" id="medications"> <option>Lütfen İlaç Seçiniz</option> {% if medicationName%} {% for medicationName in medicationName %} <option value="{{medicationName.medicationName}}">{{medicationName.medicationName}}</option> {%endfor%} {%endif%} </select> </div> <div class="col-4"> <label for="scale_used" class="form-label">Kullanılan Ölçek</label> <input type="text" class="form-control" id="scale_used" name="scale_used[]"> </div> <div class="col-4"> </br> <button type="button" class="btn btn-primary" id="add_medications">İlaç Ekle+</button> </div> </div> </div> <script> $(document).ready(function() { var MaxInputs = 20; var InputsWrapper =$("#InputsWrapper"); var AddButton =$("#add_medications"); var x = InputsWrapper.length; var FieldCount = 1; $(AddButton).click(function(e) { if(x <= MaxInputs) { FieldCount++; $(InputsWrapper).append('<div class="row justify-content-start"><div class="col-4"><label for="">İlaç Adı:</label><select class="form-select form-select-lg" name="medications[]" id="medications_'+FieldCount+'"><option>Lütfen İlaç Seçiniz</option>{% if medicationName%}{% for medicationName in medicationName %}<option value="{{medicationName.medicationName}}">{{medicationName.medicationName}}</option>{%endfor%}{%endif%}</select></div><div class="col-4"><label for="scale_used" class="form-label">Kullanılan Ölçek</label><input type="text" class="form-control" id="scale_used_'+FieldCount+'" name="scale_used[]"></div></div>'); x++; } return … -
Django querry set SQL
in want and equivalent of this sql query in Django SELECT Gender, ServCode FROM [openimisproductTestDb_16_08_22].[dbo].[tblInsuree] JOIN [openimisproductTestDb_16_08_22].[dbo].[tblServices] ON [openimisproductTestDb_16_08_22].[dbo].[tblInsuree].AuditUserID = [openimisproductTestDb_16_08_22].[dbo].[tblServices].AuditUserID WHERE Gender = 'F' AND ServCode = 'F4' THIS IS THE MODEL ` def assisted_birth_with_cs_query(user, **kwargs): date_from = kwargs.get("date_from") date_to = kwargs.get("date_to") hflocation = kwargs.get("hflocation") format = "%Y-%m-%d" date_from_object = datetime.datetime.strptime(date_from, format) date_from_str = date_from_object.strftime("%d/%m/%Y") date_to_object = datetime.datetime.strptime(date_to, format) date_to_str = date_to_object.strftime("%d/%m/%Y") dictBase = { "dateFrom": date_from_str, "dateTo": date_to_str, } dictGeo = {} if hflocation and hflocation!="0" : hflocationObj = HealthFacility.objects.filter( code=hflocation, validity_to__isnull=True ).first() dictBase["fosa"] = hflocationObj.name claimItem = Insuree.objects.filter( validity_from__gte = date_from, validity_to__lte = date_to, **dictGeo, gender = 'F' ).count() data = Service.objects.filter(code = 'F4').count() | Insuree.objects.filter(gender = 'F').count() dictGeo['health_facility'] = hflocationObj.id dictBase["post"]= str(data) return dictBase ` I tried like that but the one just adds when I want the women included in the insured table and the F4 code contained in the service table. both tables have the auditUserID column in common -
How can i not set <pk> at my url to get certain data?
I am trying to not set str:pk behind my url while updating or deleteing certain data with restframework ` class BarrelAPIView(APIView): def get(self,request): barrel = Barrel.objects.all() #queryset serializer = BarrelSerializer(barrel, many=True) return Response(serializer.data) def post(self,request): serializer = BarrelSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self,request): try: data = request.data Barrel.objects.filter(code=data['code']).delete() return Response(status=status.HTTP_204_NO_CONTENT) except Exception as error: return Response( status=status.HTTP_400_BAD_REQUEST) ` it can be done on postman by passing the 'code'. but when i try on restframework default api browser the delete button showed up but nothing happen after that -
Javascript keeps repeating itself [closed]
I have a js that shows the previews of images before there upload after the frst image is inputted the sceond image gets doubled and the third images gets trippled and so it continues I honestly don't know what am not so god with js