Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make sure celery task exits after database commit
I have a Django application in which the app creates a celery task to process user input, check the progress of the task, and update the page as soon as the task is completed. I am well aware of the fact that the celery task should only be started after the record being processed is committed, using code such as transaction.on_commit(lambda: my_task.apply_async(args=(pk,))) However, when the task exits with something like @celery.task def my_task(pk): record = Record.objects.get(pk) # do something record.save() The django app still gets the old value of the record when it reads from the database (Record.objects.get(pk)), likely because the database has not been updated yet. How can I make sure that the celery task exits only after the transaction has been committed? I tried to add transaction.commit() after record.save() and it does not appear to help. -
Is Django REST Framework and Bootstrap enough to build a complete webapp?
I'm totally new backend developer and i want to create a website .I have an API which created in Django REST Framework. I want to use Bootstrap 5 as frontend. My question is that, whether these tools enough for building my site or i need more tools? Exactly my question is that are there any options in Bootstrap for sending request and getting responses from server or not? -
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'error')1
`const loadAllProducts = () => { 41 | Object(helper_coreapicalls__WEBPACK_IMPORTED_MODULE_1_["getProducts"])().then(data => { 42 | if (data.error) { | ^ 43 | setError(data.error); 44 | console.log(error); 45 | }` -
ManagementForm data is missing or has been tampered with. Missing fields: servicesprice_set-TOTAL_FORMS
When i am changing and saving from Inclusive To Exclusive Django admin give me following error: (Hidden field TOTAL_FORMS) This field is required. (Hidden field INITIAL_FORMS) This field is required. ManagementForm data is missing or has been tampered with. Missing fields: servicesprice_set-TOTAL_FORMS, servicesprice_set-INITIAL_FORMS. You may need to file a bug report if the issue persists. This is happening after i override inline field. What does this mean? @admin.register(Services) class ServicesAdmin(ImportExportModelAdmin, EmptyFieldListFilter): ... inlines = [ SubServiceInline, ServicePriceInline ] ExclusiveInlines = [ ExclusiveServicePriceInline ] InclusiveInlines = [] ... def get_inlines(self, request, obj): if not obj.parent_id: return self.inlines elif obj.type == 1: return self.InclusiveInlines else: return self.ExclusiveInlines -
Change pending status to submitted after uploading of file in django
I am creating an assignment management system where students are uploading their assignments and the status of assignments are pending before uploading. I want to change the status when the assignment is saved at backend and change the status to submitted. template code <tr> <td>{{assignment.assignment_date}}</td> <td>{{assignment.assignment_creator}}</td> <td>{{assignment.assignment_title}} </td> <td> <form enctype="multipart/form-data" action="{% url 'assignment' %}" method="POST"> {% csrf_token %} <input required type="file" name="inputFile" id="" placeholder="upload"> <button>Upload</button> {{s.assignment_status}} </form> </td> <td> <span class="bg-success text-white">Pending </span></td> </tr> views.py print('file uploaded') if request.method == "POST": print('file uploaded Post') uploaded_file = request.FILES['inputFile'] print(uploaded_file) student = Student.objects.get(student_username=request.user) std_instance = student document = Submissions.objects.create(submitted_by=std_instance, submission_file=uploaded_file) document.save() print('saved') -
Uploading image file from React Native to Django
So on the React Native side the console.log is printing this for the image file as in I'm doing console.log(image_file) and getting this {"fileName": "rn_image_picker_lib_temp_0d752f09-0fab-40f0-8c89-13dec3695de0.jpg", "fileSize": 374466, "height": 810, "type": "image/jpeg", "uri": "file:///data/user/0/com.cheersfe/c ache/rn_image_picker_lib_temp_0d752f09-0fab-40f0-8c89-13dec3695de0.jpg", "width": 1000} Here is my React Native Code const createFormData = (photos, body = {}) => { const data = new FormData(); if (photos.length > 1) { console.log(photos[1]) data.append("images", photos[1]); } Object.keys(body).forEach((key) => { data.append(key, body[key]); }); return data; }; const onAddButtonClick = () => { if (value === null) { Alert.alert("Hold On!", "Please select a goal"); } else if (descriptionText === "") { Alert.alert("Hold On!", "Update description required"); } setLoading(true); const body = createFormData(photos, { join_goal: value, body: descriptionText }); postGoalUpdatePost(body).then(response => { // navigation.navigate("PostsScreen"); setLoading(false); }).catch(error => { const errorMessage = `${error.name}: ${error.message}`; }); setLoading(false); }; export async function postGoalUpdatePost(body) { return constructConfig().then(config => { return axios.post(`${url}/posts/update`, body, config).then(response => { return response.data; }); }); } But on the Django side when I look at request.data['images'] I get this crazy hexstring: \x7f.x�������uJr|�����a=e��|�\x00��^�=J0�^������\x08\x1a\\\x02;�H�a�a�\x19=�u�K\x01�x䞧�\x0e�{{�\x07\x14���}H�2\x06?.)%�\x7f\x1f�\x0c�RvI������=H-���[��䌏ÿ^��\x00玵�$��<g�\x1d}�\x1d�\x00®7�\x1e���Yr\x7f�\x1f���+&��wт�I�?������$�Ӯz���N?Z�+�\x07�Oo\x7f�?����\x7f\x13���ܒ1����\r����V=J0M�\x7f5�I5�ϹVG���\x189��`�\x7fJ�$��u�1���{\x7f.�չ:7���kuO��\x15���m,����{\x18x�\x7f.]�\x7f�W��s�\x0e=��1�\x00֬�e^��0y$sӧ�\x0ez՛���\x7f3YS\x13��|��+�\x7f\x13��#���;>�k�o�\x7fñ\x1c�\x03�\x0f\x18�;s�\'��ߥ\x19$$�{���O���SI�\x1b�U\x1f�\x0f�O�\x15���}^����֥\x08���u���\x002��|����|���Y�$�\x003�^�A�9�>�j��\x1f����z\x1f��U��\x17�u=z\x10\\��O����b9�V\x18\x04p\x08������Vd�G\x1f��2O�V��\x1f�ک\\u?C��qԛJI[���zT"����_�W+�\x02\x06\x0f$u����\x00����\x15\x19�\x1f��4W\x0b��z$w���' so clearly it's coming in as a string rather than a file. How do I fix this? -
Microservices- how can I call the api in django template
How can I call the rest api in django template.I want to design the microservices and just got thinking about calling a api in the front end.How could I achieve this. Usually when I work in monolithic I directly call it from the database in the html but not case in microservices part. -
Recursive and nested serializer for CreateAPIView
I know there are a few other threads about this topic but none of the solutions seem to work for me. I have a simple django-treebeard model that allows me to bulk add nested children to a parent via a load_bulk model method. The POST payload is essentially: items = [ {"data": {"title": "1"}, children: []}, {"data": {"title": "2"}, children: [ {"data": {"title": "2_1"}, children: []}, {"data": {"title": "2_2"}, children: [ {"data": {"title": "2_2_1"}, children: []}, ]}, ]}, ] payload = { "parent_id": parent_id, "items": items } I have a view that takes the parent_id and the items list of objects from the payload and passes it to load_bulk to create all the nested objects: Model.load_bulk(items, parent=Model.objects.get(id=parent_id) It works fine for the top-level of items but seems to ignore the nested children. In fact, I can't even get the get_children method in my serializer (commented below) to run. # models.py class Item(MP_node): id = UUIDField() title = CharField() # views.py class BulkCreateView(generics.CreateAPIView): queryset = Item.objects.all() serializer_class = BulkCreateSerializer # serializers.py class BulkCreateSerializer__item(serializers.ModelSerializer): class Meta: model = Item fields = ["title"] class BulkCreateSerializer__wrapper(serializers.ModelSerializer): data = TextBulkCreateSerializer__chapter() children = serializers.SerializerMethodField() class Meta: model = Item fields = ["data", "children"] def get_children(self, obj): … -
Django Boostrap TimePicker/Forms not working
I am working on a project and have ran into an issue with my forms. In particular, I want the form to use Bootstrap4 (from CDN) elements, yet when I try to use the widgets feature of ModelForm, it isn't working quite right forms.py: class Meta(object): model = ScheduleItem fields = ( 'name', 'time_start', 'time_end', 'day', ) widgets = { 'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'test' } ), 'time_start': forms.TimeInput( attrs={ 'class': "form-control" } ) } def __init__(self, *args, **kwargs): super(ScheduleItemForm, self).__init__(*args, **kwargs) self.fields['name'].label = "" self.fields['time_start'].label = "" self.fields['time_end'].label = "" self.fields['day'].label = "" html page: (The first two are ones using the form and the latter are not using it) <form action="" method="POST"> {% csrf_token %} <div class="input-group mb-3"> <label class="input-group-text" for="inputGroupSelect01">Description</label> {{schedule_item_form.name|as_crispy_field}} </div> <div class="input-group mb-3"> <label class="input-group-text" for="inputGroupSelect01">Start Time</label> {{schedule_item_form.time_start|as_crispy_field}} {% comment %} <input type="time" class="form-control" aria-label="Username" name="start_time" required> {% endcomment %} </div> <div class="input-group mb-3"> <label class="input-group-text" for="inputGroupSelect01">End Time</label> <input type="time" class="form-control" aria-label="Username" name="end_time" required> </div> <div class="input-group mb-3"> <label class="input-group-text" for="inputGroupSelect01">Day of the Week</label> <select class="form-select" id="inputGroupSelect01"> <option selected>Choose...</option> <option value="0">Monday</option> <option value="1">Tuesday</option> <option value="2">Wednesday</option> <option value="3">Thursday</option> <option value="4">Friday</option> <option value="5">Saturday</option> <option value="6">Sunday</option> </select> </div> <button type="submit" class="btn btn-primary mb-2 mt-2">Add item to … -
Django no User with same username in database
I'm particularly new to django and still in the learning process. I have this code where it would have the user input any text into the field and once the user hits the submit button it would grab the text they inputted and look for it in the django database for that item. It's able to do what I want, except when there are no users with that username. I don't know where I would do an if statement, or a work around for that. views.py from .forms import RequestPasswordResetForm from django.contrib.auth.models import User def request_password(request): next = request.POST.get('next', '/') if request.method == "POST": user = request.POST['passUsername'] users = User.objects.get(username=user) form = RequestPasswordResetForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Request has been sent! Admin will be with you shortly.') return HttpResponseRedirect(next) -
Populate HTML table (dataTables) with AJAX+JS data in Django
I have an HTML page on Django which currently has two tables. The first table contains certain data related to a unique id key. Once the user clicks on an "Edit" button, Django populates a form using the available data using the id key. However, I also want to populate a second table ( different from the first one in the DB) by only showing the records related to the id under edition, passing it using a view. If no record is intended to edit, the table must appear empty to the user. I'm able to load the records from both tables using ajax: $(document).ready(function() { var 1Table= $('#FirstTable').DataTable( { "ajax": {"type":"GET", "url" :"/Deal/request_first/, "data":function( e ) { e.placeholder = "asdf"; } }, "columns": [ { "className": 'edit-control', "width": "12px", "defaultContent": '<button type="button" class="btn-primary"></button>' }, { "data": "id" }, { "data": "A" }, { "data": "B" }, ], } ); var 2Table = $('#Secodntable').DataTable( { "ajax": {"type":"GET", "url" :"/Deal/request_second/", "data":function( d ) { d.placeholder = "asdf"; } }, "columns": [ { "data": "id" }, { "data": "C" }, { "data": "D" }, ], } ); If the 'edit-control' is clicked, I'm calling a view that passes the data from the … -
Connect Google Cloud Platform SQL to Visual Studio
I am trying to connect VS to my GCP SQL Server but I'm running into a bunch of issues. I tried following a youtube tutorial (https://youtu.be/l4nPaSXE3QE) and it has an option for Google Cloud SQL in there Photo of Option, but when I download it, mine doesn't show that option. My Visual 2019 version is 16.11.2 Thanks in advance -
Move a data from one department to another using django
I have a webpage where it will show all the data, how do I move this data from this department to another department with just a click of a button. Lets say this data is currently at the customer service page and when I click on the view button the data will go to another department, for example logistic. So after clicking on the button view, it should appear here as shown from the picture below, how to do that Below are my codes for the customer service page and logistic page, they are both the same code. views.py (customer service) @login_required() def ViewMCO(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q( Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q(status__icontains=search_post) | Q(serialno__icontains=search_post)) if not allusername: allusername = Photo.objects.all().order_by("-Datetime") else: allusername = Photo.objects.all().order_by("-Datetime") # new important part part = request.GET.get('sortType') valid_sort = ["partno", "serialno", "Customername", "mcoNum"] if (part is not None) and part in valid_sort: allusername = allusername.order_by(part) page = request.GET.get('page') paginator = Paginator(allusername, 6) try: allusername = paginator.page(page) except PageNotAnInteger: allusername = paginator.page(1) except EmptyPage: allusername = paginator.page(paginator.num_pages) context = {'allusername': allusername, 'query': search_post, 'order_by': part} return render(request, 'ViewMCO.html', context) views.py (logistic) @login_required(login_url='login') def … -
updating user with same email address, gives email already exists error
I am trying to update user fields but it returns email already exists error when I try to update it with the same email address. @login_required def user_profile(request, id): if request.user.id == int(id): if request.method == "POST": user = Account.objects.get(pk=request.user.pk) form = UserProfileUpdateForm(request.POST, user=user) if form.is_valid(): form.save() messages.success(request, mark_safe("UPDATE: <br> your profile is updated")) context = { "form": form } return render(request, "accounts/user_profile.html", context) else: #... else: #... else: return redirect("not_found") and forms.py class UserProfileUpdateForm(forms.ModelForm): class Meta: model = Account fields = ["first_name", "last_name", "first_name_kana", "last_name_kana", "post_code", "city", "address", "building", "tel", "sex", "occupation", "year", "month", "day", "parent_name", "parent_name_kana", "year", "month", "day", "school_type", "school_name", "student_id", "email"] def __init__(self, *args, **kwargs): now = datetime.datetime.now() user = kwargs.pop("user") super(UserProfileUpdateForm, self).__init__(*args, **kwargs) # widget settings What is the right way to update user fields with the same email address. -
Dictionary output with Django
I need to create a dictionary with the ID's of my users, and also with the coordinates of geocoding API from Google! (The ID is not relevant for the API, but it is for me so i can connect each location with it's own data) This is a template of the dictionary i need to pass to my js script: var markersOnMap = [ { id: { id: 1 }, LatLng: [{ lat: 19.392856, lng: -99.162641 }] }, { id: { id: 2 }, LatLng: [{ lat: 19.393686, lng: -99.170752 }] }, ] This is the views.py script: I'm getting all the addresses and ID's from my users. The API processes the address and returns 2 coordinates: lat and lng, is there a way or a better way to return to the js script each block of data containing the id with it's coordinates and so on per user as i mentioned above? def test(request): # ADDRESSES AND ID'S FROM ALL USERS data = list(UserProfile.objects.values('address', 'id')) # GOOGLE API API_KEY = 'MyApiKey' params = { 'key': API_KEY, 'address': data } base_url = "https://maps.googleapis.com/maps/api/geocode/json?" response = requests.get(base_url, params=params).json() response.keys() if response['status'] == 'OK': geometry = response['results'][0]['geometry'] lat = geometry['location']['lat'] lng = … -
Django inner join with search terms for tables across many-to-many relationships
I have a dynamic hierarchical advanced search interface I created. Basically, it allows you to search terms, from about 6 or 7 tables that are all linked together, that can be and'ed or or'ed together in any combination. The search entries in the form are all compiled into a Q expression. I discovered a problem today. If I provide terms for sub-tables that are (somewhere along the line of foreign keys) in a many to many relationship, the output table will include results from that table that don't match the term. My problem can by reproduced in the shell with a simple query: qs = PeakGroup.objects.filter(msrun__sample__animal__studies__id__exact=3) sqs = qs[0].msrun.sample.animal.studies.all() sqs.count() #result: 2 The ids in sqs include 1 & 3 even though I only searched on 3. I'm hoping I won't have to completely rewrite my interface to do the type of join that only retrieves a record and links to study id 3. Is there a way to do such an inner join as the result of a single Q expression in a filter on the entire set of linked takes that whose fields are in the resulting html table in the template? I'm betting it's not possible without … -
How to update an user with JavaScript on Django
hope someone can help me with this as I´m starting to go crazy not finding anything. I need to make an update for a certain user using django and oracle, me and my team decided to use javascript for the update but we can´t figure it out. {% extends 'core/base.html' %} {% block titulo %} <title>Registro_coach</title> {% endblock %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'core/css/estilo_r_coach.css' %}"> {% endblock %} {% block contenido %} <div class="row"> <div class="col-md-6"> <h3>Coachs registrados</h3> <table id="tablaCoach" class="table table-bordered table-dark"> <thead> <tr> <th scope="col">Run</th> <th scope="col">Nombre</th> <th scope="col">Apellido Paterno</th> <th scope="col">Apellido Materno</th> <th scope="col">Correo</th> <th scope="col">Telefono</th> </tr> </thead> <tbody> {% for i in coachs%} <tr> <td>{{i.0}}</td> <td>{{i.1}}</td> <td>{{i.2}}</td> <td>{{i.3}}</td> <td>{{i.5}}</td> <td>{{i.4}}</td> <th><input type="button" class="btnModificar" value="Modificar"></th> </tr> {% endfor %} </tbody> </table> </div> <div class="col-md-5 ml-auto"> <h3>Registro Coach</h3> <form id="FormCoach" action="" method="POST"> {% csrf_token %} <input class="controls" type="text" name="run" id="run" placeholder="Run" oninput="checkRut(this)" maxlength="10" required> <input class="controls" type="text" name="nombre" id="nombre" placeholder="Ingrese su Nombre" required> <input class="controls" type="text" name="a_paterno" id="a_paterno" placeholder="Apellido paterno" required> <input class="controls" type="text" name="a_materno" id="a_materno" placeholder="Apellido materno" required> <input class="controls" type="email" name="correo" id="correo" placeholder="Ingrese su correo" required> <input class="controls" type="text" name="telefono" id="telefono" placeholder="telefono" required> <input class="botons" type="submit" value="Agregar" onclick="limpiarFormulario()" … -
django.db.utils.IntegrityError: null value in column "genre_id" of relation "shop_book" violates not-null constraint
I am building Microservice, I have 2 project / 1 DB in Warehouse and 1 DB in Shop. When I have a new book in Warehouse I have updated DB in Shop - celery takes this task and does Models in Warehouse and Shop it same. I'm getting a strange error that I can't find information for. Models: from django.db import models from django.urls import reverse class Author(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return f'{self.first_name} {self.last_name}' class Genre(models.Model): name = models.CharField(max_length=50, db_index=True) slug = models.SlugField(max_length=50, unique=True) class Meta: ordering = ('name',) verbose_name = 'genre' verbose_name_plural = 'genres' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:book_list_by_genre', args=[self.slug]) class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) genre = models.ForeignKey(Genre, related_name='books', on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField(blank=True) language = models.CharField("language", max_length=20) pages = models.IntegerField() image = models.ImageField(upload_to='products/%Y/%m/%d') slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) isbn = models.CharField('ISBN', max_length=13, unique=True) created = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) quantity = models.IntegerField() class Meta: ordering = ('title',) index_together = (('id', 'slug'),) def __str__(self): return self.title def get_absolute_url(self): return reverse('shop:book_detail', args=[self.id, self.slug]) Celery: from celery import shared_task from django.core.mail import send_mail import requests from .models import Author, Book, Genre @shared_task def send_mail_task(subject, message, email): send_mail(subject, message, … -
cart problem in django checkout, Problem sorting items in cart
i am using a brokerage to pay but i am having trouble sending the cart This is the draft the brokerage house wants from me. options = { 'api_key': 'api', 'secret_key': 'secretkey', 'base_url': 'sandbox-api.iyzipay.com' } payment_card = { 'cardHolderName': kartisim, 'cardNumber': kartno, 'expireMonth': kartskt, 'expireYear': '2030', 'cvc': karcvc, 'registerCard': '0' } buyer = { 'id': adres.id, 'name': adres.adres_uye.username, 'surname': 'Doe', 'gsmNumber': '+905350000000', 'email': adres.adres_uye.email, 'identityNumber': '74300864791', 'lastLoginDate': '2015-10-05 12:43:35', 'registrationDate': '2013-04-21 15:12:09', 'registrationAddress': adres.adres_detay, 'ip': '85.34.78.112', 'city': 'Istanbul', 'country': 'Turkey', 'zipCode': '34732' } address = { 'contactName': 'Jane Doe', 'city': 'Istanbul', 'country': 'Turkey', 'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'zipCode': '34732' } basket_items = [ { 'id': 'id', 'name': 'name', 'category1': 'category1', 'category2': 'category2', 'itemType': 'type', 'price': 'price' }, { 'id': 'id', 'name': 'name', 'category1': 'category1', 'category2': 'category2', 'itemType': 'type', 'price': 'price' }, { 'id': 'id', 'name': 'name', 'category1': 'category1', 'category2': 'category2', 'itemType': 'type', 'price': 'price' } ] request_payload = { 'locale': 'tr', 'conversationId': '123456789', 'price': '1', 'paidPrice': '1.2', 'currency': 'TRY', 'installment': '1', 'basketId': 'B67832', 'paymentChannel': 'WEB', 'paymentGroup': 'PRODUCT', 'paymentCard': payment_card, 'buyer': buyer, 'shippingAddress': address, 'billingAddress': address, 'basketItems': basket_items } payment = iyzipay.Payment().create(request_payload, options) this is my method: basket_items = [] for bas in uye: bas = { … -
I'm having some trouble setting default url for specific page in Django
Right now I have my urls.py set up like this: urlpatterns = [ ... path('dividends/<str:month>/', views.DividendView.as_view(), name='dividendview'), path('dividends/', views.DividendView.as_view(), name='dividendview'), ] What I would like is to have the 'month' parameter optional and default to today's month. Right now I have my views.py set up as class DividendView(ListView): model = Transaction template_name = 'por/dividends.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) divs = Dividends() month = self.kwargs['month'] context['month'] = get_month(month) return context def get_month(month): if month: return month else: return datetime.today().month and my dividends.html file as {% extends 'base.html' %} {% load static %} {% block title %}Dividends{% endblock %} {% block content %} {{ month }} {% endblock %} If I navigate to /dividends/Oct/ (or any other month) it works fine, but if I just go to /dividends/ it gives me KeyError: 'month' Can anyone help me figure out what I'm doing wrong and how I might go about fixing it? Thanks. -
How to display product details from django restframework to angular?
I am trying to navigate into my product details, however not getting any response from my api. May i have you assistance please? django views: class Product(generics.RetrieveAPIView): lookup_field = "slug" queryset = Product.objects.all() serializer_class = ProductSerializer django urls: path("product/<slug>", views.Product.as_view(), name="product_detail"), angular api.service: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { baseurl = "http://127.0.0.1:8000" httpHeaders = new HttpHeaders({'Content-Type': 'application/json'}) constructor(private http: HttpClient) { } getAllProducts(): Observable<any>{ return this.http.get(this.baseurl +'/product/', {headers: this.httpHeaders}) } getProductDetails(slug: string){ return this.http.get(this.baseurl +'/product/'+ slug, {headers: this.httpHeaders}) } } angular product detail components: ts - export class GroceriesDetailsComponent implements OnInit { ProductId:any; ProductData:any = []; constructor( private service:ApiService) { } ngOnInit(): void { this.ProductId = this.actRoute.snapshot.params['id']; this.getProductDetails(this.ProductId); } getProductDetails(ProductId: string){ this.service.getProductDetails(ProductId).subscribe(product=>{ this.ProductData=product; }); } } and the html - <div class="form-froup row"> <p>{{ ProductData.title }}</p> </div> -
Django Annotate Changes Query Values/Order
I am trying to pull the 8 most recent items from my model and attach their minimum price. When I annotate the 8 most recent items, the items change unless I use order_by(). Is this a bug, or does this make my query more efficient somehow? I'm trying to better understand my queries so that I can make them faster. class Item(ClusterableModel): name = models.CharField(max_length=100) class Meta: ordering = ('-pk',) class StoreInventory(ClusterableModel): item = ParentalKey('Item', on_delete=models.CASCADE) price = models.DecimalField(max_digits=4, decimal_places=2) Undesired newest_items = Item.objects.all()[:8] > Queryset [Item: Item object(100), ..., Item: Item object(93)] newest_items = newest_items.annotate(price = Min('storeinventory__price')) > Queryset [Item: Item object(1), ..., Item: Item object(8)] Desired newest_items = Item.objects.all().order_by('-pk')[:8] > Queryset [Item: Item object(100), ..., Item: Item object(93)] newest_items = newest_items.annotate(price = Min('storeinventory__price')) > Queryset [Item: Item object(100), ..., Item: Item object(93)] -
Create and get the id of a model's attribute in Django
Im working in a project where users can register their shops addresses in a Django model and i can display all those addresses in a google map. For that i need the addresses but also a way to access to that specific user's shop info, how can i create an id linked or pointing to the user's "address" attribute in my extended users models, and how do i call all those ids? models.py class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name='user_profile') address = models.CharField(null=True, blank=True, max_length=150) views.py def test(request): addresses = list(UserProfile.objects.values_list('address')) address_id = ???????? context = { 'address_id': address_id, 'addresses': addresses } return render(request, "test.html", context) -
Create a preview screen in Django
I have a Django form that receives a text (that I copy from Google Classroom: a bunch of student comments). I use these comments to make student's attendance. What I want to achieve is: Accessing /insertion/ url via GET user receive the page form as a response, to choose the class (class01, class02, etc) and to past the text When the user clicks on submit in this form (post method), it is redirect to the same /insertion/ url, but now the form is bound to the data submited, and the page shows a preview page (based on a boolean variable I'm passing through context), showing what students are present and what are absent based on the text informed. At that page, a new submit button will be shown below a text like "if everything's ok, hit the ok button". After click this ok button, a pdf will be generated and the user will be redirected to /files/ url, to see the generated pdf and previous generated pdf. views.py def insertion(request): context = {} if request.method == 'GET': form = AttendanceDataForm() context.update({"form": form}) if request.method == 'POST': form = AttendanceDataForm(request.POST) context.update({"form": form}) if form.is_valid(): lesson = form.cleaned_data['lesson'] raw_text = form.cleaned_data['raw_text'] # … -
Trouble creating unit tests for Django admin action
I am having a bit of trouble figuring out where to mock and patch things and it's not making sense to me. I'm creating an admin action that fetches a token from a third-party API, and then instantiates an instance of a local class (that connects to said API) and makes API calls based on the item id. For example, let's assume that I'm storing restaurant ratings in an external location, accessible via API calls, and I'm storing users locally. I want to create an admin action that goes through each selected user and deletes all restaurant ratings in my external location, which is authenticated via a fetched token. I know this is not an optimal way to do things, but this is obviously not a real example, just an analogue of something a bit more complicated. Here is the structure of my project. from external_class_location import ReviewClass # This is the class that hooks into the restaurant review location from external_function_location import get_token # This is the method that fetches the token from that external location class UserAdmin(admin.ModelAdmin) actions = ['delete_reviews', ] def delete_reviews(self, request, queryset): reviews = ReviewClass(get_token()) for user in queryset: reviews.delete_all_reviews(user) delete_reviews.short_description = "Delete all reviews …