Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I make sure the subscription is paid for now and every another invoice?
I am working on an intelligent cloud platform able to analyse data of the users. I am going to use Stripe payments and subscription plan. Everything seems to be working properly however I have some uncertainty. To wit, I wonder how can I check whether the subscription has been paid for the next month? I have to be 100% sure because if the user will be able to use the service without paying in advance he can spend almost unlimited funds for which I will have to pay out of pocket. So this is super important for me to be sure that I had already received his money in Stripe and only then I give him access to my services and he uses what he paid for. I need to verify his payment when I create a subscription for him when he is creating an account. At this moment I create subscription in my Django backend in this way: customer = stripe.Customer.create( email=user.email, source=request.data['token'] ) subscription = stripe.Subscription.create( customer=customer.id, items=[ { 'plan': ‘myexampleplan’, 'quantity': request.data['amount'], }, ], expand=['latest_invoice.payment_intent'], ) # So here I want to have information if I already have his money for the next month. I guess that … -
SignUp without validation afrer press button
I try to add recaptcha in django 2.2 on the sign up form. The problem is with validation, when I press the SignUp button, the form validation does not appear, only the recaptcha form remains on the page, and the form to create the account disappears. The form is built using: django-widget-tweaks code in view.py class SignupView(CreateView): template_name = 'registration/signup.html' form_class = forms.SignUpForm success_url = '/' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': 'my_key_to_recaptacha', 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: return redirect('/') else: print('someting is going on with recaptcha') else: form = self.form_class() return render(request, self.template_name, {'form': form}) -
With pytest and factory-boy, how do I create a factory for a non-traditional type of object?
I'm using Django 2, Python 3.7 and factory-boy. Trying to create a factory for the django-address' AddressField -- https://pypi.org/project/django-address/ , which I guess is a non-traditional model, in that it doesn't inherit from "models.Model". I created this factory, using "objects = models.Manager()" ... class AddressFactory(factory.DjangoModelFactory): """ Define Address Factory """ objects = models.Manager() class Meta: model = AddressField street_number = "123" route = "Rd" raw = "123 Fake Rd" formatted = "123 Fake Rd." latitude = 87.1234 longitude = -100.12342 locality = factory.SubFactory(LocalityFactory) Then I have this test ... @pytest.mark.django_db def test_address_create(self): """ Test address model """ # create customer model instance address = AddressFactory() assert address is not None but running the test results in the below error ... davea$ python manage.py test --settings=maps.test_settings Creating test database for alias 'default'... System check identified no issues (0 silenced). setUpTestData: Run once to set up non-modified data for all class methods. setUp: Run once for every test method to setup clean data. EsetUp: Run once for every test method to setup clean data. . ====================================================================== ERROR: test_address_create (tests.test_models.ModelTests) Test address model ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 126, in _get_manager manager = model_class.objects AttributeError: type object 'AddressField' has … -
Django relation to two colums from another table
I would like to have a relation with the ToDoLists using the foreign key and have the date from the ToDoLists in my ToDoItems. Explaining it more specifically: I want a realtion of One to Many from my ToDoLists table to te ToDoItems table so I need the foreign key to be the id of the ToDoLists but I need the date from the ToDoLists on the ToDoItems table I have: class ToDoLists(models.Model): todo_id = models.AutoField(primary_key=True) date = models.DateField(null=False) class ToDoItems(models.Model): item_id = models.AutoField(primary_key=True) to_do_list = models.ForeignKey(ToDoLists,related_name='to_do_items', on_delete=models.CASCADE) date = models.ForeignKey(ToDoLists, to_field='date', on_delete=models.CASCADE) I would like to have a relation with the ToDoLists using the foreign key and have the date from the ToDoLists in my ToDoItems, but I get this error: ERRORS: api.ToDoItems.date: (fields.E311) 'ToDoLists.date' must set unique=True because it is referenced by a foreign key. As a date I don't want it to be unique as I can have multiple To do lists with the same date -
How to use Httprequest object in FormView?
i was converting the below function view in class based view : but the problem was the below login code uses request object . so how to use this request in a form view . Functional view i wanted to change to class based view : def login(request): if request.method == 'GET': form = UserLoginForm() elif request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('name') password = form.cleaned_data.get('password') user = User.objects.filter(name=username, password=password).first() if user is not None: request.session['user'] = username return redirect('index') else: messages.error(request, 'Username or password no matched') return render(request, 'products_app/login.html', {'form': form}) FormView/class based view of the above code i changed to that gives error : class Login(FormView): template_name = 'products_app/login.html' form_class = UserLoginForm success_url = reverse_lazy('index') def form_valid(self, form): username = form.cleaned_data.get('name') password = form.cleaned_data.get('password') user = User.objects.filter(name=username, password=password).first() if user is not None: request.session['user'] = username else: messages.error(request, 'Username or password no matched') super().form_valid(form) here the problem is ,request is not being received unlike in the functional view of above def login(request). so gives error: module 'django.http.request' has no attribute 'session' -
Django. Why would my foreign key does not match the same data from parent primary key
I have 2 models: class Director(models.Model): director_name = models.TextField(primary_key=True) director_firstname = models.CharField(max_length=32) def __str__(self): return f'{self.director_name}' def get_absolute_url(self): return reverse('director-detail', args=[str(self.director_name)]) class Meta: managed = False db_table = 'director' ordering = ['director_name'] class Connection(models.Model): director_connect = models.ForeignKey('Director', models.DO_NOTHING, db_column='director_connect') worker_connect = models.ForeignKey('Worker', models.DO_NOTHING, db_column='worker_connect') class Meta: managed = False db_table = 'connection' unique_together = (('director_connect', 'worker_connect'),) ordering = ['director_connect'] def __str__(self): return f'{self.director_connect}' def get_absolute_url(self): return reverse('director-detail', args=[str(self.director_connect)]) This is my view.py file: class DirectorDetailView(generic.DetailView): model=Director template_name = 'company/director_detail.html' def get_context_data(self, **qwargs): a = super(DirectorDetailView, self).get_context_data(**qwargs) a['cons'] = Connection.objects.all() return a When I am trying to match 2 columns in html with for loop and if statement, they do not match, although they are similar one to one copies of each other: {% extends "index.html" %} {% block content %} <h1>{{ director.director_name }}</h1> <p>{{ director.firstname }}</p> {% for con in cons %} {% if object.director_name == con.director_connect %} <li>{{con.id}}, {{con.director_connect}}, {{con.worker_connect}}</li> {% endif %} {% endfor %} {% endblock %} How could I fix it? I would like to bring the list of workers under director's name. -
Django - deployment with DigitalOcean issue - python collectstatic
I'm trying to deploy my django project, I've done all the process with gunicorn and nginx, I've arrived to the last line and I had to finally collect with "python manage.py collectstatic" when I get this error: File "manage.py", line 16 ) from exc here my manage.py file #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'piattaforma.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Do you have any idea on how to solve it? thank you -
Django: loop all the records in a table and then get field from another table
I got two class models called Buy and Sell: class Buy(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.FileField() date = models.DateField() buy_price = models.DecimalField(max_digits=6, decimal_places=2) sell_price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return str(self.id) class Sell(models.Model): item = models.OneToOneField(Buy, on_delete=models.CASCADE) date = models.DateField() discount = models.DecimalField(max_digits=6, decimal_places=2) total_paid = models.DecimalField(max_digits=6, decimal_places=2) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE) def __str__(self): return str(self.item) In a template, I'd like to display all the records from the Sell table and also the image class-attribute from Buy table. Below, my view.py: def sell(request): buys = [] sells = Sell.objects.order_by('-id') for sell in sells: buys.append(Buy.objects.filter(id=str(sell.item))) context = {'sells': sells, 'buys': buys} return render(request, 'sell.html', context) Template: {% for sell in sells %} <tr> <td>{{ sell.item }}</td> <td>{{ sell.date|date:'d-m-Y' }}</td> <td>{{ buys[0].image}}</td> <td>R$ {{ sell.discount }}</td> <td>R$ {{ sell.total_paid }}</td> <td>{{ sell.buyer }}</td> </tr> {% endfor %} I'm wondering if there is a simple way to do that. I need some help in my view.py! -
Django: How to display database results based on form input selection?
I am trying to query the database to display results from the form. Once I select the form drop-down fields for my wanted query e.g. Ford C-Max 2019 1.2 Petrol 1500 , from which I coded for now to display results (regardless of Make & Model as I only have one atm) , then instead of showing me the table with matched results I get the full table with all results instead of the query I want. Portion of what I get after submitting the form (includes results I want filtered out): year liter fuel mileage average entered 2019 1.2 Petrol 1500 12075 April 8, 2020, 11:11 p.m. 0 None 13780 April 14, 2020, 5:25 p.m. 2018 1.6 Diesel 5000 15000 April 15, 2020, 2:23 p.m. What I want to get based on selecting 2019 1.2 Petrol etc. in the form: 2019 1.2 Petrol 1500 12075 April 8, 2020, 11:11 p.m. My code: views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import FormView from django.db.models import Q from .models import Average, Query from .forms import QueryForm class QueryMakeModel(FormView): template_name = 'QueryMakeModel.html' success_url = '/data/' form_class = QueryForm def form_valid(self, form): return HttpResponse("Sweet.") def index(request): if request.method == … -
how to change data in model1 while saving data to model2 on django
models.py class EquipmentWorker(models.Model): date = models.DateField() count = models.IntegerField() class Admission(models.Model): name = models.CharField(max_length=100,db_index=True) date = models.DateField() in_stock = models.IntegerField(null=True, blank=True) out_of_stock = models.IntegerField(null=True, blank=True) forms.py class AdmissionForm(forms.ModelForm): class Meta: model = Admission fields = ['date', 'name', 'admission', 'id_type', 'in_stock', 'out_of_stock'] class EquipmentWorkersForm(forms.ModelForm): class Meta: model = EquipmentWorkers fields = ['date', 'equipment', 'type', 'id_workers', 'id_room'] views.py class AssignToWorker(View): def get(self, request, admission_id): admission = Admission.objects.get(id=admission_id) form = EquipmentWorkersForm(instance=admission) return render(request, 'inventory/assignToWorker.html', context={'form': form, 'admission': admission}) def post(self, request, admission_id): admission = Admission.objects.get(id=admission_id) admission_form = AdmissionForm() form = EquipmentWorkersForm(request.POST) if form.is_valid(): form.save() return redirect(equipments_list) class AdmissionCreate(View): def get (self, request): form = AdmissionForm() return render(request, 'inventory/addAdmissions.html', context={'form': form}) def post(self, request): form = AdmissionForm(request.POST) if form.is_valid(): form.save() return redirect(admission_list) it is necessary that the value of the out_of_stock field of the Admission model is updated when the value is saved in the count field of the EquipmentWorker model, for example, out_of_stock = 0 after the value is saved in the count = 2 field, the out_of_stock field is updated (out_of_stock = 2) view AssignToWorker accepts admission_id to identify the value in Admission.objects.get() that needs to be updated -
NGINX ISSUE - reload?
I am still stuck at this point. I'd like to show this error as to where I have been stuck after reloading the nginx. Does this (pls see photo)look familiar to you all? It shows reloading is failed when I tried to reload it. I used the systemctl status nginx command line to check the status and this message says the same reload errors. Thank you in advance for your help! -
Django, dynamically change model output on index page based on dropdown list selection
I am new to Django framework and currently trying to create a web page that has an input form for Product bids and outputs the entire model on the same page, calculating mean values in a separate div. The list of Products is predefined and can be selected by the user in a dropdown menu. I am looking for a way to filter the model output based on the Product selected before the user makes his input into the remaining form fields. models.py class ProductModel(models.Model): product = models.CharField(max_length=20,blank='False') minval = models.DecimalField(max_digits=5,decimal_places=2,name='minval') maxval = models.DecimalField(max_digits=5,decimal_places=2,name='maxval') date = models.DateField(auto_now_add=True) def __str__(self): return str(self.product) forms.py prod_choices = [('Prod1','Prod1'), ('Prod2','Prod2'), ('Prod3','Prod3')] class InputPred(forms.ModelForm): #custom validation go here do for min-max-close product = forms.ChoiceField(choices=prod_choices,label='Product') minval = forms.DecimalField(min_value=0,label='Minimum Price') maxval = forms.DecimalField(min_value=0,label='Maximum Price') def clean(self): clean_data = super().clean() min_val = clean_data['minval'] max_val = clean_data['maxval'] if (min_val > max_val): raise forms.ValidationError('Minimum Price higher than Maximum Price') class Meta: model = ProductModel fields = ['product','minval','maxval'] views.py def index(request): data_list = models.ProductModel.objects.order_by('product').filter(product='Prod1') #MAKE THIS DYNAMIC min_avg = round(models.ProductModel.objects.all().filter(product='Prod1').aggregate(Avg('minval')).get('minval__avg'),2) #MAKE THIS DYNAMIC max_avg = round(models.ProductModel.objects.all().filter(product='Prod1').aggregate(Avg('maxval')).get('maxval__avg'),2) #MAKE THIS DYNAMIC form = InputPred() if request.method == "POST": form = InputPred(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect('/') else: form = InputPred() return_data = {'data_list':data_list,'min_avg':min_avg,'max_avg':max_avg,'form':form} … -
Where am I going wrong
So I am very new to Django and I am confused where am I going wrong. I am trying to create a simple calculator to calculate profit estimates. Here is what it shows in my HTML so far. Kind of confused where am I going wrong. Any help appreciated. This the HTML file code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <body> {% block content %} <form action = "something" method = "post"> {% csrf_token %} {{ form }} <input type="submit" value=Submit> </form> {% endblock %} </body> </html> This is forms.py from django import forms from .models import Calc class Calculator(forms.ModelForm): class Meta: model = Calc fields = ['gross_receivable', 'TDS', 'bank_charges', 'vendor_payable'] This is the models.py from django.db import models # Create your models here. class Calc(models.Model): gross_receivable = models.IntegerField() TDS = models.BooleanField(default=False) bank_charges = models.BooleanField(default=False) vendor_payable = models.IntegerField() This is the views.py from django.shortcuts import render from django.http import HttpResponse from .forms import Calc def something(request): form = Calc() context = {'form': form} return render(request, "calculator1.html", context) -
How to make db query in background task function on PythonAnyWhere?
I have a django project and i'm using django-background-tasks library for heavy processes. I have to make a db query in this @background() function and update an object. I have written the background task function and it works in my localhost but when I deploy it to PythonAnyWhere, i cannot reach that object which will be updated. The following part of the Background task function does not work. @background() def model_create(customer_name): task = TaskState.objects.filter(verbose = customer_name).last() accrual = int(round(100/13)) task.progress += accrual task.save() How can i fix this? -
Django prefetch_related is taking to much runtime
I need to list all my devices. To do this I use a prefetch related to reduce the amount of queries. But one of them is consuming to much time.. I wonder if it can't go better. I will start with the model construction: I want a list of devices. This is the device model: class Device(models.Model): name = models.CharField(max_length=250, null=True, blank=True) def get_active_gateway(self): from backend.gateways.models import Gateway all_gatewaydevices = self.gatewaydevices.all() for gd in all_gatewaydevices: if not gd.end_date: return gd.gateway return None In the real code the model is larger, but that code is irrelevant. As you can see, a device has some gatewaydevices (which is a model between gateway and device) The gatewaydevice model looks like: class GatewayDevice(models.Model): gateway = models.ForeignKey( Gateway, on_delete=models.CASCADE, related_name="devices" ) device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="gatewaydevices" ) So in my list of devices, I want for every device, the linked gateway. This is my view: class AdminDeviceView(GenericAPIView): def get_permissions(self): return IsAuthenticated() # noinspection PyMethodMayBeStatic def get_serializer_class(self): return AdminDeviceInfoSerializer @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully fetched all data from devices."), AdminDeviceInfoSerializer, ) } ) def get(self, request): devices = ( Device.objects.prefetch_related( "gatewaydevices__gateway", ) .all() ) serializer_class = self.get_serializer_class() serializer = serializer_class(devices, many=True) devices_data = serializer.data return … -
How to change query parameters in djnago filter?
I've created a multi field filter API using django filter My custom class based filter code is as below from django_filters import rest_framework as filters class EnquiryLogFilter(filters.FilterSet): start_date = filters.DateFilter(field_name='actual_mail_date',lookup_expr='gte') end_date = filters.DateFilter(field_name='actual_mail_date',lookup_expr='lte') broker_name = filters.CharFilter(field_name='broker_name') insured_name = filters.CharFilter(field_name='insured_name') class Meta: model = EnquiryLog fields =['start_date','end_date','broker_name','insured_name'] and my filter view is class ENQUIRYFILTERVIEWSET(viewsets.ModelViewSet): # comment this when using inbuilt get_queryset queryset = EnquiryLog.objects.all() serializer_class = EnquirySerializer filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter,) filterset_class= EnquiryLogFilter ordering = ('-unique_id_for_mail') search_fields = ('country_name') now when i call my api in browser with various query parameters i am getting the result also /di_enquirylog_filter_query/?start_date=2020-08-10&end_date=2020-08-30&broker_name=Broker-BPL+5&insured_name= and my response HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "unique_id_for_mail": "DISOMPO031", "actual_mail_date": "2020-08-30", "subject_name": "RE: Macquarie - Vedanta Prepay", "broker_name": "Broker-BPL 5", "is_today_mail": -2, "insured_name": "Mac Steel", "obligor_name": "ING Prosafe Nautipa", "country_name": "UK", "limit": "USD 45M", "is_enabled": "True" } ] Until now everything is working fine,the above API works well for single query parameter or multi query parameter by keeping query parameter to blank i mean like below .../di_enquirylog_filter_query/?start_date=2020-08-10&end_date=2020-08-30&broker_name=&insured_name= Here you can see broker_name and insured_name are blank (i am using django rest framework) But when my developer hit the same api he syas that for … -
Django on Mac showing Page not found (404) with every new project
I just switch my project from windows to Mac at first I create everything correctly and tried to create a test project to make sure my environment working fine and the home page of new Django Project lunch correctly. after that I tried to zip my project from windows and move it to the Mac and issue start showing. I tried to install all the missing packages and still not working. now even if I try to create a new project I'm receiving the below error Page not found (404) Using the URLconf defined in newproject.urls, Django tried these URL patterns, in this order: admin/ The current path, Login/, didn't match any of these. even with the new project. any idea what could be the issue ? -
How to send waysiprint pdf by mail
I'm trying to generate a pdf file from an HTML template using Weasyprint python package and I need to send it via email using. Here's what i have tried: views.py : user_info = { "name": 'nadjib', } html_string = render_to_string('Proformas/command.html') html = HTML(string=html_string,base_url=request.build_absolute_uri()) # html.write_pdf(target='/tmp/mypdf.pdf'); fs = FileSystemStorage('/tmp') with fs.open('mypdf.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'filename="Commande.pdf"' pdf = weasyprint.HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf( stylesheets=[weasyprint.CSS(string='body { font-family: serif}')]) to_emails = ['nadjzdz@gmail.com'] subject = "SH INFOR FACTURE" email = EmailMessage(subject, body=pdf, from_email='attaazd@gmail.com', to=to_emails) email.attach("Commande".format(user_info['name']) + '.pdf', pdf, "application/pdf") email.content_subtype = "pdf" # Main content is now text/html email.encoding = 'us-ascii' email.send() return response the pdf is rendered successfully but not sent by mail ? -
Celery workers in two projects with local tasks and mutual queue
I have two projects, A and B (A and B projects have a celery worker each). Project A handles user registration, login, password reset etc. Project B uses project A for user related things. Project B needs to keep some local data about users. So when a user in Project A gets updated, Project B needs to be notified (event on a message-queue). Both projects use celery and I have a message broker that both projects connect to and they can read and write events to it. This has been working fine. Now I need to create a task in Project B that should be handled by the worker in Project B (AKA NOT the worker in project A). The problem is that when I start a task in Project B it gets sent to worker A which says that the Task is unregistered (it's registered in project B!). I want to be able to start tasks in Project B that get handled by it's worker, and does not get sent to the worker in Project A. -
Foreign Key Query
I have the following models: class status(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #data class next(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') target = models.ForeignKey(User, on_delete=models.CASCADE, related_name='target') #data class settings(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #data and want to Query next and status with the following output: next,nextdata,status(target) => Attach the status of the target to the (next) queryset Is this possible via Django Query? Or should I just write raw SQL cheers, keslol -
Why is the error' ValueError at /add_to_cart/printed-shirt/ Field 'id' expected a number but got 'Red'.' being thrown?
I got this error and have no idea why this is coming ValueError at /add_to_cart/printed-shirt/ Field 'id' expected a number but got 'Green'. I'm trying to add variations to my product. So when I'm submitting, I'm printing the values the users are selecting by writing print(request.POST.getlist('variations', [])) and those are coming back as ['Red', 'Medium']. Now I was trying to see if the product matching these variations already exists in the cart. If it exists, then I would increase the quantity, and if it does not exist, then I would add a new item. But my code doesn't seem to work. Can anyone please help me with this? Thanks in advance! My views.py: @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) variations = request.POST.getlist('variations', []) print(variations) minimum_variation_count = Variation.objects.filter(item=item).count() if len(variations) < minimum_variation_count: messages.info(request, "Please specify the required variations.") order_item_qs = OrderItem.objects.filter( item=item, user= request.user, ordered=False, ) for v in variations: order_item_qs = order_item_qs.filter( item_variations__exact=v ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += 1 order_item.save() else: order_item = OrderItem.objects.create( item=item, user= request.user, ordered=False, ) order_item.item_variations.add(*variations) order_item.save() order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if not order.items.filter(item__id=order_item.id).exists(): order.items.add(order_item) messages.success(request, "Product added to cart.") return redirect("order-summary") else: ordered_date = timezone.now() … -
Django cannot find url pattern request from Angular
Angular 8, Django 3. I have done the same routing and urls, views, services a hundred times but this one route will not work for some reason and i dont know why.. Angular: html (with link) <h2>My Restaurants</h2> <ul *ngFor = "let restaurant of restaurants"> <a [routerLink]="['/ordersummary', restaurant.id]">Orders</a> </ul> app.routing.module const routes: Routes = [ {path: 'ordersummary/:id', component:OrderSummaryComponent} ]; OrderSummaryComponent export class OrderSummaryComponent implements OnInit { constructor( private orderservice:OrderService, private router: ActivatedRoute) { } id; orders; ngOnInit() { this.id = this.router.snapshot.paramMap.get('id') this.getrestaurantorders(this.id)} getrestaurantorders(id){ this.orderservice.restaurantorders(id).subscribe( x => this.orders = x )}} OrderService export class OrderService { private baseUrl2 : string ='http://127.0.0.1:8000/users/' private restaurantordersUrl : string = this.baseUrl2+'restaurantorders/' constructor( private http: HttpClient) { } restaurantorders(id):Observable<any>{ return this.http.get<any>(this.restaurantordersUrl+id) } Django urls.py #base urls urlpatterns = [ path('users/', include('users.urls')), #users urls urlpatterns = [ path(r'restaurantorders/<int:pk>', RestaurantOrders.as_view(), name='restaurantorders'), ] views.py class RestaurantOrders(generics.RetrieveAPIView): serializer_class = RestaurantOrderSerializer queryset = Orders.objects.all() serializers.py class RestaurantOrderSerializer(serializers.ModelSerializer): recipe = RecipeSerializerName customer = CustomerSerializerShort class Meta: model = Orders fields = '__all__' I know that Angular is asking for the correct url because the error i get is "Http failure response for http://127.0.0.1:8000/users/restaurantorders/2: 404 Not Found". But the http://127.0.0.1:8000/users/restaurantorders/2 url is right there... i dont understand, all of my other requests work. … -
How to handle celery tasks on multiple nodes pointing to the same database on Django?
I have a question with a problem that I'm having, my system run on multiple servers (let's call them nodes) pointing to the same database (postgres), each node has celery tasks that monitor around 1000 sensors each, all that data is collected on a central database (postgress) on a 30 secconds interval. My problem is that I don't know why celery keeps all my connections to the database "open" and one node alone takes almost 40 connections to postgress. Postgress has a limit around 100 connections by default, so adding more than couple nodes hits the connection limit. I tried using pgbouncer but had. a really bad peformance impact on the system, I'm thining that i will try pgpool II with database replication on multiple servers and test that. Instead of trying to remedy the problem, I wanted to know if there is anything that I can do on celery to mitigate the amount of connections open to the database. As a quick test after each task I added a line db.connections['default'].close() to try forcing close the database, but I can still see multiple connections from celery to the database. Any ideas on what is causing this? I'm using django … -
How to insert the blog pagination on Django Blog
I trying to implement pagination on my blog using the Bootstrap. I did comment because in this way is working but shows only one number. I did try some different way but not working yet, I feel that is close. or not. :-) Following my "blog.html" file. Thank you. <nav aria-label="Page navigation example"> <ul class="pagination pagination-lg justify-content-center"> {% if queryset.has_previous %} <li class="page-item"> <a class="page-link" href="?{{ page_request_var }}={{ queryset.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% endif%} {% comment %} <li class="page-item"><a class="page-link" href="?{{ page_request_var }}">{{ queryset.previous_page_number}}</a></li> {% endcomment %} <li class="page-item"><a class="page-link" href="?{{ page_request_var }}">{{ queryset.number }}</a></li> {% comment %} <li class="page-item"><a class="page-link" href="?{{ page_request_var }}">{{ queryset.next_page_number}}</a></li> {% endcomment %} {% if queryset.has_next %} <li class="page-item"> <a class="page-link" href="?{{ page_request_var }}={{ queryset.next_page_number }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> {% endif%} </ul> </nav> -
Adding Social Authentication to Django
I am using Django 3.0.5 and python 3.6. I want to add social authentication for my blog. Related files Settings.py, urls.py and login.html are: Settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR=os.path.join(BASE_DIR,'templates') DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'social_django', ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.github.GithubOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import url,include from blog import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index, name='index'), path('datetime/',views.current_datetime,name='datetime'), path('',views.post_list,name='post_list'), url(r'^blog/(?P<id>\d+)/(?P<slug>[\w-]+)/$',views.post_detail,name="post_detail"), …