Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to setup virtual environment inside github desktop?
We recently started use github-pre-commits for django project since then I am not able to commit changes using github desktop. I have activate my virtual env and use terminal only for commiting changes can i make any changes which would let me commit changes from github desktop -
Django Models: Aggregate Avg def objects
I am looking to calculate an average of the "percent" by "name", the origins of the mother on one side and the father on the other. I made my dictionnary, but maybe I'm using the AVG method wrong. Here is my code, I specify that name and percent are not in the database and cannot be in it. @property def mother_origines(self): if self.mother and self.mother.total_origines != 0: return self.mother.total_origines['name'], self.mother.total_origines['percent'] else: return 0 @property def father_origines(self): if self.father and self.father.total_origines != 0: return self.father.total_origines['name'], self.father.total_origines['percent'] else: return 0 @property def total_origines(self): if self.mother_origines != 0 and self.father_origines != 0: ori = self.mother.total_origines, self.father.total_origines return ori.aggregate(models.Avg('name')) if self.birth: return {'name':self.birth, 'percent':100.00} else: return 0 -
Django - queryset chain condition to many_to_many relation
'''class Category(Model): name = models.CharField(max_length=45) class Animal(Model): name = models.CharField(max_length=45) categories = models.ManyToManyField(Category) @receiver(pre_save, sender=Animal) def animal_create_update(sender, **kwargs): # get the selected categories and do something print(categories)''' -
NetSuite Mass Update script runs sucessfully, but nothing gets updated
Have been a developer for years, but just getting into NetSuite scripting. I wanted to start simple and create a script that would update the COMMENT field for all items on a purchase order. I started off by following the tutorial found here. My modified script is below - it should update the MEMO field at the PO header and then every line's COMMENT field. I followed the steps in the article to save the script, create a Mass Update and then run it. In my criteria I set: "Transaction Number/ID" and "has keyword 90999" (just so it would only run on one specific purchase order). I confirmed my criteria was correct by clicking "Preview" and it only returns that one PO. When I run the Mass Update, it runs fine and says it has been run successfully on 1 record (which is good). The MEMO field at the PO header DOES get updated, but the COMMENT field for each line does not. Am I doing something wrong or missing something simple? Is the getLineCount call not the correct one to use? Note that I was doing all this in our Sandbox environment in case that makes any difference UPDATE: … -
Django Rest Framework filtering results displayed by serializer in a Model.objects.all() query
I am trying to query my entire user database but only add the user to the json response if the field account_type is "supplier", right now it is just adding every user to the json response models.py class UserProfile(models.Model): <omitted> account_type = models.CharField(max_length=200, default=None) ...<omitted> views.py class getusers(viewsets.ModelViewSet): # Database model queryset = UserProfile.objects.all() # Serializer - this performs the actions on the queried database entry serializer_class = GetUsersSerializer serializers.py class GetUsersSerializer(serializers.ModelSerializer): class Meta: model=UserProfile fields=['user','company','email','pk', 'account_type'] current JSON response [ { "user": 1, "company": "kyle att", "email": "<omitted>", "pk": 1, "account_type": "user" }, { "user": 2, "company": "kyle google", "email": "<omitted>", "pk": 2, "account_type": "supplier" } ] desired JSON response [ { "user": 2, "company": "kyle google", "email": "<omitted>", "pk": 2, "account_type": "supplier" } ] -
use validate method to post the data that is assigned to particular user in django rest Framework
I have user registration with user and project as foreign key and using serializer I wanted to choose only that project that is assigned to particular user but I can't figure out how to use validate method class ProjectUserRegistrationSerializer(ModelSerializer): class Meta: model = ProjectUserRegistration fields = ( 'id', 'date', 'start', 'start_note', 'started', 'started_at_location', 'end', 'end_note', 'ended', 'ended_at_location', 'project', ) def create(self, validated_data): user_obj = ProjectUserRegistration.objects.create( **validated_data, user=self.context['request'].user ) return user_obj and that's my viewset class ProjectUserRegistrationViewSet(viewsets.ModelViewSet): authentication_classes = [authentication.TokenAuthentication, authentication.SessionAuthentication] queryset = ProjectUserRegistration.objects.none() serializer_class = ProjectUserRegistrationSerializer def get_serializer_context(self): context = super(ProjectUserRegistrationViewSet, self).get_serializer_context() context.update({ 'request': self.request, }) return context -
setting up headers properly in nginx after a django app
How do I properly set up these headers from a django app on nginx CSRF_TRUSTED_ORIGINS = [] CORS_ALLOW_METHODS = [ "GET", "OPTIONS" ] SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin" X_FRAME_OPTIONS = 'SAMEORIGIN' CORS_REPLACE_HTTPS_REFERRER = True HOST_SCHEME = "https://" SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = True SECURE_FRAME_DENY = True /etc/nginx/sites-available/urban-train What I have so far current nginx file -
Python/Django Rest Framework put same value objects in one list of dictionaries
I want to put the datas to one list of dictionaries if the label value of the objects are the same Just like the example below: dataPoints: [ { x: new Date(2017,0), y: 1000, label:"Austria" }, { x: new Date(2018,0), y: 1111, label:"Austria" }, { x: new Date(2019,0), y: 2000,label:"Austria" }, { x: new Date(2020,0), y: 1224,label:"Austria" }, { x: new Date(2021,0), y: 4294,label:"Austria" }, ] For this i did something like this: class CustomBusinessIntelligenceList(generics.ListAPIView): queryset = BusinessIntelligence.objects.all().order_by("-years__year") serializer_class = BusinessIntelligenceSerializer filter_backends = [DjangoFilterBackend] filterset_class = CustomBusinessInteligenceFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) dummy_response = [] mapping = {} for count in range(0, len(queryset)): dummy_response.extend([{"x": datetime.datetime(queryset[count].years.year, 1, 1), "y": queryset[count].amount, "label": queryset[count].countries.name}]) for d in dummy_response: print(d) return Response(dummy_response) This gave me this response. That i do not want to see: { "x": "2014-01-01T00:00:00", "y": "51717.5", "label": "Austria" }, My best attempt was this and this did not give me the response that i wanted: class CustomBusinessIntelligenceList(generics.ListAPIView): queryset = BusinessIntelligence.objects.all().order_by("-years__year") serializer_class = BusinessIntelligenceSerializer filter_backends = [DjangoFilterBackend] filterset_class = CustomBusinessInteligenceFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) dummy_response = [] mapping = {} for count in range(0, len(queryset)): dummy_response.extend([{"x": datetime.datetime(queryset[count].years.year, 1, 1), "y": queryset[count].amount, "label": queryset[count].countries.name}]) for d … -
Django - user cannot login after password rest via rest api
I've created a custom user model as described in the django documentation https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project : from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Changed the AUTH_USER_MODEL in settings.py: AUTH_USER_MODEL = 'users.CustomUser' and created a serializer using django rest-framework: from rest_framework import serializers from users.models import CustomUser class CustomUserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = super().create(validated_data) # user = CustomUser.objects.create_user(**validated_data) if validated_data.get('password'): password = validated_data.get('password') user.set_password('password') print("set password to ", password) user.save() return user def update(self, instance, validated_data): if validated_data.get('password'): password = validated_data.get('password') instance.set_password('password') instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.email = validated_data.get('email', instance.email) instance.save() return instance class Meta: model = CustomUser exclude = ['last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined', 'groups', 'user_permissions'] Creating a new user and updating it via rest works fine. But I cannot login with that user and the given password. I've tried it via the api authentication given by the rest framework path('api-auth/', include('rest_framework.urls')), as well as tried to login into the admin backend after giving the user staff status there. The password string displayed in the admin interface for that user seems to be fine: algorithm: pbkdf2_sha256 iterations: 390000 salt: 2DrB5n**************** hash: eflTzs************************************** It seems, that calling set_password on the instance within the serializer methods works. However, no … -
HTML IF function with date.time
In my Django/Python app I have an queryset with 3 conditions: queryset = Post.objects.filter(verifikacija='False', status='Zatvorena', date_zatvoreno__lte=datetime.now(pytz.utc) - timedelta(days=30)) Now, I need to make those same conditions in my HTML IF function. {% if user.is_superuser or user.is_staff %} {% if object.status == 'Zatvorena' and post.verifikacija != 'True' and post.date_zatvoreno__lte == datetime.now(pytz.utc) - timedelta(days=30) %} <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> {% endif %} {% endif %} Problem is, I don't know how to check time or how to calculate time in HTML. Do I need to write a seperate script or? -
How to update user details in custom user model in django
i just created a custom user model from abstractuser. I can create user but update is not working showing some error. I am also week in english so idk how to share my problem. In short hand i want to edit email and password of a user. ###This is my user model class User(AbstractUser): roles =( ('Admin','Admin'), ('Placement Manager','Placement Manager'), ) username=models.CharField(max_length=100,null=True,blank=True) email = models.EmailField(max_length=50, null=True,blank=True) phone = models.IntegerField(unique=True) role = models.CharField(max_length=100,choices = roles,null=True,blank=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['email','username','role'] objects=UserManager() def get_username(self): return self.email ###This is my view def editPlacementManager(request): if request.method=='POST': name=request.POST.get('name') phone=request.POST.get('phone') email=request.POST.get('email') password=request.POST.get('password') userid = request.POST.get('pmId') User.objects.get(id=userid).update(username=name,phone=phone,email=email,password=password,role='Placement Manager') return redirect('listplacementmanager') return render(request,"index/placementmanager.html") ### The error is AttributeError at /editplacementmanager 'User' object has no attribute 'update' -
Problem django.core.exceptions.ImproperlyConfigured with django.test
I am trying to run a simple django test: tests.py from django.test import TestCase class EasyTest(TestCase): def test_1(self): x = 2 y = x * 2 self.assertEqual(y, 4) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db01', 'USER': 'admin', 'PASSWORD': '18101974Oo', 'HOST': 'localhost', 'PORT': 44321, }, } But I am getting an error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. If i use the same code but do import from unittest everything works -
Is there a way to render a docx file using Django Template?
I'm creating a function that takes two arguments: A list of documents, and a dictionary containing values with key names that matches the keywords in the documents, which are identified by two curly braces around them: {{Value}}. I'm supposed to combine all the documents into a single document and render this document using Django Template. Django would automatically read the keywords and replace them with the dictionary values. Simple as that, right? I suppose not, but i gotta ask. Is there any way of doing this? Is this even possible? Just to clarify, i already combined all documents into one, so it's only rendering it that is confusing me. Has anyone gone through a similar situation? -
Why does my image not show when i upload an image in django but when
Images dont show in the web browser when i try to upload an image But it show me the location of the image and it is valid any help please enter image description here -
Django Rest Framework - display child value on parent serializer without making too many extra queries
I have this two models: class Parent(models.Model): name = models.CharField(max_length=255) level = models.IntegerField() class Child(models.Model): parent = models.ForeignKey(Parent, related_name='children') therefore_name = models.CharField(max_length=255) level = models.IntegerField() active_from = models.DateTimeField(auto_now_add=True) active_to = models.DateTimeField(null=True, blank=True) Child model is used to be able to "overwrite" values on parent, and there is validation to prevent a parent with multiple overlapping children with the same active_from and active_to dates. My view: class FacilityViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = ParentSerializer def get_queryset(self): now = timezone.now() parents = Parent.objects.all().prefetch_related( Prefetch('children', queryset=Child.objects.exclude(valid_from__gt=now, valid_from__isnull=False).exclude(valid_to__lt=now, valid_to__isnull=False).distinct()) ) return parents My serializer: class ParentSerializer(serializers.ModelSerializer): class Meta: model = Parent fields = ['id'] def to_representation(self, instance): representation = super().to_representation(instance) if hasattr(instance, 'children') and instance.children.exists(): child = instance.children.first() else: child = Child(therefore_name=instance.name, level=instance.level) representation['name'] = child.therefore_name representation['level'] = child.level return representation This works, but the code makes alot of extra queries. Is there something I could do to cut the queries down? This is the code that is makes extra queries: if hasattr(instance, 'children') and instance.children.exists(): child = instance.children.first() -
How to load save image to Django models from csv file
I am having trouble saving image in ImageField from CSV file. I can save everything except image and I have no idea what to do. views.py def read_csv_file(request): if request.method == "POST": uploaded_file = request.FILES['csv_file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) file = open('C:/Fiverr projects/GrimBlog-main/media/' + uploaded_file.name) reader = csv.reader(file) for _ in range(1): next(file) for row in reader: title = row[0] author = request.user views = row[2] description = row[3] timestamp = strftime("%Y-%m-%d %H:%M:%S", gmtime()) slug = row[5] short_description = row[6] publish_on = strftime("%Y-%m-%d %H:%M:%S", gmtime()) path = row[8] image = Image.open(path) row_9 = str(row[9]) row_10 = (row[10]) if row_9 == "TRUE": featured = True if row_9 == "FALSE": featured = False if row_10 == "TRUE": case_study = True if row_10 == "FALSE": case_study = False create_blog = Post(title = title, author = author, views = views, description = description, timestamp = timestamp, slug = slug, short_description = short_description , publish_on = publish_on, heading_image = image, featured = featured, case_study = case_study).save() return render(request, 'blog/upload_blogs.html') models.py class Post(models.Model): title = models.CharField(max_length=30) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) views = models.IntegerField(default=0) description = RichTextUploadingField(blank=True, null=True) timestamp = models.DateTimeField(blank=True, auto_now_add=True) slug = models.CharField(max_length=33, unique=True) short_description = models.TextField(max_length=400) publish_on = models.DateTimeField() heading_image = … -
APIView - How to raise a 400 Bad Request and be caught by the exception handler
I am trying to raise a BadRequest error in my APIView and I wish it to be caught by the custom exception handler I have created. My current setup doesn't catch the exception. Could I please have some help as to why this may be happening settings.py REST_FRAMEWORK = { ...... 'EXCEPTION_HANDLER': 'src.exceptions.common_exception_handler', } views.py class LoginView(APIView): serializer_class = LoginSerializer permission_classes = (AllowAny,) def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=False) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) exceptions.py def common_exception_handler(exc: APIException, context: dict) -> Response: response = origin_exception_handler(exc, context) ............. ``` -
How to create a dictionary with two querysets from different models, using a common DateTimeField as the dictionary keys?
I would like to create a dictionary from two models with a field dt in common. This field should be the dictionary keys, and fields value and last the keys's value. What is the most efficient way to do that ? class Balance(models.Model): value = models.FloatField(default=0) dt = models.DateTimeField() class Price(models.Model): last = models.FloatField(default=0) dt = models.DateTimeField() The desired output would be something like this : { "2022-10-11T00:00:00Z": { "value": 151.05, "last": 1, }, "2022-10-10T00:00:00Z": { "value": 151.1, "last": 1.1, }, "2022-10-09T00:00:00Z": { "value": 152, "last": 1.1, }, "2022-10-08T00:00:00Z": { "value": 154, "last": 1.23, } } I could iterate through each dictionaries of the querysets with a nested loop and search the items with a common dt then populate key:value inside a new dictionary, but it's not elegant and I don't believe it's efficient. -
Object level permission at ORM level in Django
I have a Django application (mainly a rest API) with a completely custom User model (not inhered from Django). My authentication is based on JWT tokens. I would like to make sure a user cannot access to data of another user. I have checked the django-guardian and django-rules. It provides stuff to call a has_perm function. However, in the case the developer does not perform the check and makes a mistake (for example hardcoding the user id in a query), a user might be able to access someone else data Is there any way to enforce some kind of rule at the ORM level? -
Django vs Laravel — Which framework to choose? [closed]
Django vs Laravel — Which framework to choose for a level business ERP? who can guide me about this what I can learn for Django what I used for web design of Django so please guide me in right way. -
Paginate tabs element with Bootstrap - Jquery
I would like to paginate bootstrap tabs buttons. Let's say, after 50 buttons, I would like to display them paginated, so the list doesn't get too long. So far, I wasn't able to find help anywhere so I tried to figure it out by myself but I couldn't reach my goal. WHAT I WANT TO ACHIEVE I post a picture for better understanding: WHAT I ACHIEVED SO FAR let listElement = $(".paginator"); let perPage = 50; let numItems = document.getElementById("numOfQuestions").value; let numPages = Math.ceil(numItems / perPage); $(".pager").data("curr", 0); let curr = 0; while (numPages > curr) { $('<li><a href="#" class="page_link">' + (curr + 1) + "</a></li>").appendTo( ".pager" ); curr++; } $(".pager .page_link:first").addClass("active"); listElement.children().css("display", "none"); listElement.children().slice(0, perPage).css("display", "block"); $(".pager li a").click(function () { let clickedPage = $(this).html().valueOf() - 1; goTo(clickedPage, perPage); }); function previous() { let goToPage = parseInt($(".pager").data("curr")) - 1; if ($(".active").prev(".page_link").length == true) { goTo(goToPage); } } function next() { goToPage = parseInt($(".pager").data("curr")) + 1; if ($(".active_page").next(".page_link").length == true) { goTo(goToPage); } } function goTo(page) { let startAt = page * perPage, endOn = startAt + perPage; listElement .children() .css("display", "none") .slice(startAt, endOn) .css("display", "block"); $(".pager").attr("curr", page); } <div class="col-md-3"> <div class="nav nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical"> <input type="hidden" name="" … -
How mock stripe in Django unit test
We used stripe for the payment system and stripe testing docs is its test doc. I want to mock Stripe in order to test our payment system but the stripe invoice total cost is zero all the time. I mocked stripe.InvoiceItem.create and stripe.Invoice.finalize_invoice and stripe.Invoice.create like this: @patch("app_name.models.stripe.InvoiceItem.create") @patch("trips.models.stripe.Invoice.finalize_invoice") @patch("trips.models.stripe.Invoice.create") def test_method( self, mock_create, mock_finalize, mock_invoice_item, ): response = MagicMock() # api_key and stripe_account from this link https://stripe.com/docs/api/connected_accounts response.api_key = "sk_test_MSc53AbTknQXPy" response.stripe_account = "acct_1032D82eZvKYlo2C" # Stripe account ID response.stripe_version = "2022-08-01" # last version here https://stripe.com/docs/upgrades mock_invoice_item.return_value = response response = MagicMock() geofencing_zone = GeofencingZone.objects.get(properties__name="Zone A") response.total = geofencing_zone.properties.delivery_price.price response.invoice_pdf = "https://google.com" response.id = "sk_test_MSc53AbTknQXPy" mock_create.return_value = response mock_finalize.return_value = response.id now I think maybe I should use stripe-mock somehow to mock stripe, but I can not understand how? -
Why my form not sowing any validation errors after i click the submit button in django?
I've two forms rendering in a single function based view, it is diplaying validation errors of only one form when i click the signup button but when i click the login button it just reload my page and doesn't showing any validation error views.py def register(request): form = RegisterForm() form_b = LogInForm() if request.POST.get('submit') == 'sign_up': form = RegisterForm(request.POST) if form.is_valid(): form.save() elif request.POST.get('submit') == 'log_in': form1 = LogInForm(request=request, data=request.POST) if form1.is_valid(): uname = form1.cleaned_data['username'] upass = form1.cleaned_data['password'] user = authenticate(username=uname, password=upass) if user is not None: login(request, user) return redirect('/shop/') else: form = RegisterForm() form_b = LogInForm() return render(request, 'reg.html', {'form': form, 'form1': form_b}) forms.py from distutils.command.clean import clean from xml.dom import ValidationErr from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): password1 = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['username', 'email'] class LogInForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) reg.html <form class="loginForm" action="" method="POST" novalidate> {% csrf_token %} {% for field in form %} <p> {{field.label_tag}} {{field}} </p> <p> {{field.errors}} </p> {% endfor %} <button type="submit" class="btnLogin" name='submit' value='sign_up'>Sign Up</button> </form> <form class="loginForm" action="" method="post" novalidate> {% csrf_token %} {% for field in form1 %} <p> {{field.label_tag}} {{field}} </p> <p> … -
Django Paginator returns results of the last page despite page number being greater than the last feasible page
Lets say I have 92 objects and want them to paginate by 5 per page. That's 19 pages where the last page contains 2 objects. Why doesn't it raise EmptyPage or InvalidPage exception if page is greater than 19? page = int(request.GET.get('page')) paginator = Paginator(self.get_queryset(), self.paginate_by, allow_empty_first_page=False) try: page = paginator.get_page(page) reports = list(page.object_list) except (EmptyPage, InvalidPage) as _error: reports = [] -
Django - Updating value only for the last item of list
This is how my ToDoapp looks like The date change works only for the last item in the list but for other items it throws the error: ValidationError at / ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] I see that irrespective of "Update" button I press, it passes only the last item's id and date. Find my code below: Index.html {% extends 'base.html' %} {% block content %} <h3 style = "margin-bottom: 20px"><strong>To Do List App</strong></h3> <form method="POST"> {%csrf_token%} <ul class="list-group"> {% for task in tasklist %} <li class="list-group-item d-flex justify-content-between align-items-center"> <input type='hidden' name = 'task_id' value='{{task.id}}'>{{task.tasks}} <span class="badge bg-primary rounded-pill">{{task.duedate}} <input type="date" name="datepick" /> <input type='submit' value ='Update'> </span> </li> {% endfor %} </form> Views.py def index(request): if request.method == "POST": task_id = request.POST.get('task_id') task=Task.objects.get(id=task_id) datepick = request.POST.get('datepick') task.duedate = datepick task.save() tasklist = Task.objects.all() return render(request, 'index.html', {'tasklist':tasklist}) I feel that mistake is in the HTML file and I'm not familiar with HTML.