Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete child model data in case of on_delete=models.PROTECT?
Let assume i have two models Meeting and Call_Type and there is ForeignKey relation between them like bellow. class Meeting(SoftDeleteModel): name = models.call_type(CallType, on_delete=models.PROTECT, null=True) And:- class CallType(models.Model): type = models.CharField(max_length=256, null=False, blank=False, unique=True) Now i have deleted data from meeting table using Meeting.objects.all().delete() by mistake, and when trying delete CallType model data i get following error:- ProtectedError: ("Cannot delete some instances of model 'CallType' because they are referenced through protected foreign keys: 'Meeting.call_type'.", {<Meeting: Meeting object (1)>, <Meeting: Meeting object (2)>, <Meeting: Meeting object (3)>, <Meeting: Meeting object (4)>, <Meeting: Meeting object (5)>, <Meeting: Meeting object (6)>, <Meeting: Meeting object (7)>, <Meeting: Meeting object (8)>, <Meeting: Meeting object (9)>, <Meeting: Meeting object (10)>, <Meeting: Meeting object (11)>, <Meeting: Meeting object (12)>}) Is there is any way to delete CallType model data. Thanks in advance. Hope in here from you soon. -
send fabricjs drawing over WebSocket with django channels
I'm making a whiteboard and running it on localhost with different browser windows open. I can send shapes and textbox, but I can't figure out how to make a freedrawing appear in the canvas in the other windows. Code: HTML <button id="pencilBtn">Pencil Off</button> <canvas id="canvas"></canvas> JAVASCRIPT SENDER CODE: Click button to activate freedrawing: var pencilBtn = document.querySelector('#pencilBtn'); pencilBtn.addEventListener('click', pencilDrawing); function pencilDrawing(e){ if (e.target.textContent == 'Pencil Off'){ e.target.textContent = 'Pencil On'; canvas.freeDrawingBrush = new fabric.PencilBrush(canvas); canvas.set('isDrawingMode', true); canvas.freeDrawingBrush.width = 10; canvas.freeDrawingBrush.color = 'blue'; // Add some attributes to freeDrawingBrush canvas.freeDrawingBrush.brushtype = 'pencil'; canvas.freeDrawingBrush.user_id = user_id; canvas.freeDrawingBrush.toJSON = (function(toJSON){ return function(){ return fabric.util.object.extend(toJSON.call(this), { brushtype: this.brushtype, user_id: this.user_id }); }; })(canvas.freeDrawingBrush.toJSON); } else { e.target.textContent = 'Pencil Off'; canvas.set('isDrawingMode', false); } } MOUSE DOWN EVENT - (I know I'll need a mouse move and mouse up event, but I figured I'd start with just trying to send a drawing of a dot before anything else) canvas.on('mouse:down', (ev)=>{ if (canvas.isDrawingMode == true){ // Add another attribute to freeDrawingBrush canvas.freeDrawingBrush.obj_id = Math.random(); canvas.freeDrawingBrush.toJSON = (function(toJSON){ return function(){ return fabric.util.object.extend(toJSON.call(this), { obj_id: this.obj_id }); }; })(canvas.freeDrawingBrush.toJSON); // send freeDrawingBrush over socket whiteboardSocket.send(JSON.stringify({ 'canvas_object': { 'type': 'drawing_mouse_down', 'color': canvas.freeDrawingBrush.color, 'width': canvas.freeDrawingBrush.width, 'mouse_down_pointer': canvas.getPointer(ev), 'brushtype': canvas.freeDrawingBrush.brushtype, 'user_id': … -
Ajax funtion is through ann error Uncaught TypeError: $.ajax is not a function
I'm working on a Django project and I,m using Ajax to remove an item on a button click. I'm getting the error "Uncaught TypeError: $.ajax is not a function" every time when the button is clicked. I'm not an expert with javascript/Jquery. The way this ajax method is written has worked for me on other pages of the same product for a different function. But it is throwing error for this task Django Template <div class="menu-container"> <div class="container-heading"> <div class="row"> <span>Main Menu Section</span> </div> </div> <div class="box"> <div class="form-group"> <label for="{{ form.name.id_for_label }}"> Menu Name:<span style="color: red; font-weight: bold;">*</span> </label> <input type="text" name="menu_name" class="textinput form-control" pattern='[a-zA-Z\s]{1,250}' title="Alphabets and Spaces only" value="{{menu.name}}" required="true"> </div> {% for item in items %} <div class="row form-row"> <div id="item-{{forloop.counter}}-box" class="form-group col-md-10"> <label for="item-{{forloop.counter}}"> Item {{forloop.counter}}: </label> <input id="item-{{forloop.counter}}" type="text" name="{% if item.dishes %}{{item.slug}}{% elif item.drinks %}{{item.slug}}{% endif %}" class="textinput form-control" pattern='[a-zA-Z\s]{1,250}' title="Alphabets, Integers and Spaces only" value="{% if item.dishes %}{{item.dishes}}{% elif item.drinks %}{{item.drinks}}{% endif %}" required="true" disabled=""> </div> <div id="item-{{forloop.counter}}-box" class="form-group col-md-2"> <label for="remove-item" style="color: #fff"> . </label> <button class="menu_btn btn btn-danger delete-btn" type="button" id="remove-item-{{forloop.counter}}" onclick="removeItem({{forloop.counter}})">Remove</button> </div> </div> {% endfor %} </div> </div><div class="menu-container"> <div class="container-heading"> <div class="row"> <span>Main Menu Section</span> </div> </div> <div class="box"> … -
Filtering Posts greater than certain number of likes
I have a question about filtering Posts by Like count greater than a given number. What I want to achieve is on DJANGO SHELL when I type post.likes is greater than 10 I want to see all posts with more than 10 likes. How can I do that? Thanks models.py class Post(models.Model,HitCountMixin): likes = models.ManyToManyField(User, related_name="likes", blank=True) -
My view isn't rendering any result in the template - django
I'm working on a Django project and i'm quite the beginner so i'm really sorry if this is a basic question, my view isn't showing any result in the template, here's my view: def all_products(request): products = Product.objects.all() context = {'products': products} return render(request, 'users/home.html', context) this is the model: class Product(models.Model): title = models.CharField(max_length=255) id = models.AutoField(primary_key=True) price = models.FloatField(null=True) picture = models.ImageField(null=True) category =models.ForeignKey(Category,related_name='products',on_delete=models.SET_NULL,null=True) developer = models.ForeignKey(Developer, on_delete=models.SET_NULL, null=True) and finally this is the part of html needed: <div class="row justify-content-center" > {% for product in products %} <div class="col-auto mb-3"> <div class="card mx-0" style="width: 12rem; height:21rem; background-color: black;"> <a href="#"><img class="card-img-top img-fluid" style="width: 12rem; height:16rem;" src="{{ product.picture.url}}" alt="Card image cap"></a> <div class="card-block"> <a href="#"><h5 class="card-title mt-1 mb-0" style="color:white; font-size: 18px; font-family: 'Segoe UI';"><b>{{product.title}}</b></h5><a href="#"></a> <p class="card-text text-muted mb-1" style="color:white;">{{product.developer.title}}</p> <p class="item-price card-text text-muted"><strike >$25.00</strike> <b style="color:white;"> {{product.price}} </b></p> </div> </div> </div> <span></span> {% endfor %} </div> I also do have some product objects in my database, so where could the problem be? -
What is a robust network visualization tool that can be linked to Django web framework with a MySQL backend server?
I am trying to create a web-based protein-protein interaction network visualization graphic user interface. The web framework I am currently using is Django and my database is in MySQL. I would like the network visualization to be dynamic. That is to display the corresponding pathogen nodes based on what is selected in the drop-down list (i.e. "Select pathogen"). The drop-down list is populated by data in the MySQL database. What would be a recommended network visualization tool (preferably in Python) that can be linked to Django web framework with a MySQL backend server to display network graphs dynamically? I have previously used Networkx but I am not sure if it is able to link up with Django. -
Django Celery Periodic Task How to call Task method That is inside class
I want to send periodic mail to certain user After the user has been registered to certain platform I tried to send email using celery which works fine and Now I want django celery to send periodic mail as of now I have set the email time period to be 15 seconds. Further code is here celery.py app.conf.beat_schedule = { 'send_mail-every-day-at-4': { 'task': 'apps.users.usecases.BaseUserUseCase().email_send_task()', 'schedule': 15 } } I have my Class in this way ->apps.users.usecases.BaseUserUseCase.email_send_task here is my usecases to send email class BaseUserUseCase: def _send_email(self, user, request): self.user_instance = user self._request = request token = RefreshToken.for_user(user=self.user_instance).access_token # get current site current_site = get_current_site(self._request).domain # we are calling verify by email view here whose name path is activate-by-email relative_link = reverse('activate-by-email') # make whole url absolute_url = 'http://' + current_site + relative_link + "?token=" + str(token) # absolute_url = 'http://localhost:3000' + relative_link + "?token=" + str(token) self.context = { 'user': self.user_instance.fullname, 'token': absolute_url } self.receipent = self.user_instance.email @shared_task def email_send_task(self): print("done") return ConfirmationEmail(context=self.context).send(to=[self.receipent]) How do I call this email_send_task method am I doing right any help regarding this It is not working. -
How to create to select from year to year in html forms?
I want to user to input from this year to that and then I need to forward the list of years to django? But before this how to create that kind of input, I have found something like this, but it is not working what I need. Any ideas? <select name="yearpicker" id="yearpicker"></select> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script type="text/javascript"> let startYear = 1800; let endYear = new Date().getFullYear(); for (i = endYear; i > startYear; i--) { $('#yearpicker').append($('<option />').val(i).html(i)); } </script> -
heroku server error 505 in django work fine locally
i am trying to deploy my web app on heroku server but even on sucessfull deployment it throw server error 500 my settings.py import django_heroku from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = BASE_DIR / 'templates' STATIC_DIR = BASE_DIR / 'static' MEDIA_DIR = BASE_DIR / 'media' STATIC_CDN = BASE_DIR / 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] STATIC_ROOT = STATIC_CDN # MEDIA MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' # crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' django_heroku.settings(locals()) my main projects urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import RedirectView from django.conf.urls import url from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), url(r'^favicon\.ico$',RedirectView.as_view(url='/static/image/favicon.ico')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) everything works fine locally an idea what causing wrong here -
Django: prefix language slug in i18n_urls
I have a django-cms site, that uses i18n_patterns in urls.py. This works, urls are built like /lang/here-starts-the-normal/etc/. Now, I would like to have urls like this: /prefix-lang/here-starts.... As there will be a couple of country specific domains, this wille be like /ch-de/here-... for Switzerland/.ch domain, /us-en/here-starts.... for the states, and some more. So, when the url would be /ch-de/..., the LANGUAGE would still be de. Hope this is clear? As the content is filled with existing LANGUAGES=(('de', 'DE'), ('en', 'EN'), ...), I cannot change LANGUAGES for every domain - no content would be found in the cms, modeltranslation, only to mention those two. How can I prefix the language slug in i18n_patterns? Is it possible at all? -
filter on new updated queryset return empty queryset using ORM Django
when looping the queryset and update field in the model using save() function, then try to filter on the updated queryset , the filter result returns empty even the there are still elements in the queryset that achieve the condition. please check the code below. qs = queryset.filter(status=models.BankTransfer.STATUS_NEW) for bank_transfer in qs: bank_transfer.status = models.BankTransfer.STATUS_APPROVED bank_transfer.save() Btw when I print qs, it returns with results, but I try to get the first object by using first(), it returns None for bank_transfer in qs.filter(purpose__status='pending_completed'): bank_transfer.purpose.status = 'completed' bank_transfer.purpose.save() -
Django, less than or equal method problem, Django documentation tutorial
I am following Django documentation tutorial (part 5) and in the .../polls/ page instead of getting the questions I made, I get: No polls are available. Files look like this: The problem should be in views.py, line 15, after the line def get_queryset, but I'm not professional! views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Question, Choice # Create your views here. class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice." }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results',args=(question.id,))) index.html: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> <title>The index page</title> </head> <body> {% if lastest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are … -
Django Customized Forgot Password error (custom user model)
looking for help! I am not that experienced writing Python/Back-end code even though I am improving. In development/localserver I am trying to create a customized password reset form... but I got the following error after I submitted the email when testing the form and never received and email with the link: save() got an unexpected keyword argument 'use_https' My custom Forgot Password Form class PrivateForgotPasswordForm(forms.ModelForm): helper = FormHelper() helper.add_input(Submit('page_userForgotPassword_content_form_button_submit', static_textLanguage['global_button_submit'], css_class='global_component_button')) class Meta: model = PrivateUser fields = ['email'] widgets = { 'email': forms.EmailInput(attrs={ 'id': 'page_userForgotPassword_content_form_input_email', 'maxlength': '254', 'class': 'global_component_input_box'} ) } def __init__(self, *args, **kwargs): super(PrivateForgotPasswordForm, self).__init__(*args, **kwargs) self.helper.form_id = 'page_userForgotPassword_content_form' self.helper.form_method = 'post' self.helper.form_action = '' self.helper.form_class = 'page_userForgotPassword_content_form' My custom Forgot Password View class UserForgotPasswordView(auth_views.PasswordResetView): with open(str(settings.BASE_DIR) + "/frontend/static/frontend/languages/emails/EN/email_footer__main.json", "r") as temp_file_email_footer_main: email_footer_main_data = json.load(temp_file_email_footer_main) with open(str(settings.BASE_DIR) + "/frontend/static/frontend/languages/emails/EN/email_user_forgotPassword.json", "r") as temp_file_email_forgot_password: email_forgot_password_data = json.load(temp_file_email_forgot_password) extra_email_context = { 'email_footer_static_json_text': email_footer_main_data, 'email_static_json_text': email_forgot_password_data, 'static_json_text': static_textLanguage, 'static_json_textGlobal': static_textGlobal} html_email_template_name = '../frontend/templates/frontend/templates.emails/template.email_user_forgotPassword.html' from_email = 'support@xyz.com' subject_template_name = 'Reset password' template_name = '../frontend/templates/frontend/templates.user/template.page_forgotPassword.html' form_class = PrivateForgotPasswordForm success_url = reverse_lazy('password_reset_done') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'forgot_password_form': PrivateForgotPasswordForm(), 'email_subject': self.email_forgot_password_data['emailSubject'], 'static_json_text': static_textLanguage, 'static_json_textGlobal': static_textGlobal} return context -
Django - Migrating data inside tables for smooth release
I am using Django Rest Framework for backend development, where I have set up 2 environments. I have split settings files as required and both the environments have different DBs which are working fine, I am using Zappa(AWS lambda) for deploys, I was wondering is there an elegant way of migrating data(not models but data inside models say a few config changes) than preparing PostgreSQL DB rollouts, Could not find much on the internet, so asking here. Please let me know if there are any questions. -
What is the purpose of parameter_name in django SimpleListFilter?
What is the purpose of parameter_name in django SimpleListFilter ? It still works if parameter_name is set to empty string. class EmailFilter(SimpleListFilter): title="Email Filter" parameter_name="user_name" def lookups(self,request,model_admin): return ( ('has_email','Has Email'), ('no_email','No Email') ) def queryset(self, request,queryset): if not self.value(): return queryset if self.value() =='has_email': return queryset.exclude(user__email='') if self.value() =='no_email': return queryset.filter(user__email='') -
How to implement edit-form with Django formset?
I implemented a django-form with a formset. When I create a new object it works. But I faced to a problem with editing form when I don't change formset data (only data outside formset). Formset raises errors: id requeired. If I mark formset fields to delete and then add new fields it works too. Please, explain me what's going wrong and how to solve this problem. Thanks! My formset: IngredientsFormSet = forms.inlineformset_factory( Recipe, RecipeIngredientsDetails, fields="__all__", can_delete=True, min_num=2, max_num=50, extra=0, ) And my view-function: def recipe_edit(request, recipe_id=None): if recipe_id: recipe = get_object_or_404(Recipe, id=recipe_id) else: recipe = Recipe() if request.method == "POST": form = RecipeCreateForm(data=request.POST, files=request.FILES) formset = IngredientsFormSet(data=request.POST, prefix=INGREDIENT_FORMSET_PREFIX) if form.is_valid() and formset.is_valid(): recipe = form.save(commit=False) recipe.author_id = request.user.id recipe.save() form.save_m2m() formset.instance = recipe formset.save() return redirect(reverse_lazy("index")) context = {"form": form, "formset": formset} return render(request, template_name="recipe-create.html", context=context) form = RecipeCreateForm(instance=recipe) formset = IngredientsFormSet( instance=recipe, prefix=INGREDIENT_FORMSET_PREFIX, ) context = { "form": form, "formset": formset, } return render(request, context=context, template_name="recipe-create.html") -
Why does stripe card element not load up when using django stripe?
Hi I've been trying to learn how to build an ecommerce site and am getting stuck with the Django Stripe integration for a custom pay flow. I can get the pre built checkout to work but can't for custom pay flow. Stripe seems to have updated the code on their docs a few months ago so when I try to look up tutorials, they all don't seem to have the same code and I can't seem to figure out how to get it to work. I'm self taught and just a beginner/intermediate maybe so might be missing something obvious. I'm using the code from this page https://stripe.com/docs/payments/integration-builder and trying to convert it into Django. This is my views.py from django.shortcuts import render import stripe from django.http import JsonResponse import json # Create your views here. from django.views import View stripe.api_key = "xxxxxxxxx" class StripeIntentView(View): def post(self, request, *args, **kwargs): try: intent = stripe.PaymentIntent.create( amount=2000, currency='usd' ) return JsonResponse({ 'clientSecret': intent['client_secret'] }) except Exception as e: return JsonResponse({'error':str(e)}) def payment_method_view(request): return render(request, 'custom-landing.html') This is my urls.py from django.contrib import admin from django.urls import path from products.views import payment_method_view,StripeIntentView urlpatterns = [ path('admin/', admin.site.urls), path('custom-landing/', payment_method_view, name='custom-landing-page'), path('create-payment-intent/', StripeIntentView.as_view(), name='create-payment-intent'), ] … -
Very confusing question regarding WEB dev
I have gotten the following questions which is so ambiguous, does anybody knows the answer? You create a static web site that simply consists of several HTML files on a web server. What possible difficulty might you run into with this setup as you continue to maintain your site? a. Updating URL design would require many edits throughout the site b. All of these c. Hyperlinks between pages of the site could become inconsistent d. Changes to the site’s look and feel would need to be made in many files -
Crontab Django Management command seems to start but nothing happens
I have defined a django management command that imports some data into my application database. I run it using a crontab. Sidenote: everything is inside a docker container. This command works perfectly when I use it manually in my container's shell. However, when crontab tries to run it, nothing happens. My crontab line is the following : * * * * * nice -n 19 /usr/local/bin/python3 /code/manage.py my_command "a string argument for my command" # a comment to find the cron easily (I put my code into /code because it seemed a good idea at the time.) I know that crontab calls my command, because /var/log/syslog displays when it is executed. I cannot fathom the reason why nothing happens. As a test in the "handle" method of my command, I wrote print("handling command") as the first line then added >> /code/cron.log at the end of my crontab line. The text didn't appear in the file. Any idea ? -
How to fetch users that i follow?
I want to make a viewset to allow request.user (Authenticated user) to receive the users in a view that they follow. But i do not know how to make an appropriate queryset filter for it. Models (Note: Author is the one following,profile is the one followed) class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=40,unique=True,default='undefinedusername') class UserFollow(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') View class FetchUserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [FollowedUserFilterBackend] Filter class FollowedUserFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( ??? ) I tried following__author = request.user but it returns the user that made the request,not the user that user follows. How can i do it? -
Trying to join a query for salesforce on python
I want to make a query from salesforce using an id opportunity_id="0061g00000BRG00AAH" query = "SELECT+FIELDS(ALL)+FROM+Opportunity+WHERE+ID+=+'"+opportunity_id+"'" print(json.dumps(sf_api_call('/data/v51.0/query/', {"q": query}))) But I get this error: b'[{"message":"\\nSELECT+FIELDS(ALL)+FROM+Opportunity+WHERE+ID+=+\'0061g00000BRG00AAH\'\\n ^\\nERROR at Row:1:Column:6\\nunexpected token: \'+\'","errorCode":"MALFORMED_QUERY"}]' -
How to get multiple fields of a django form in one row
Hej! I want to have multiple fields of a django form next to each other. (Input fields to search in a table) For now I can get them under each other with this template: <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Search"> </form> or two next to each other with: <div class="container"> <div class="row"> {% for field in form %} <div class="col-sm-6"> {{ field.label_tag }} {{ field }} </div> {% endfor %} </div> </div> but then I loose the 'form' of the forms. How can I get multiple (let's say 5) fields in one row? All ideas welcome! Thanks for the help :) -
Definition of the structure of a REST API with django from a data format
I was asked to write an API interface which should retrieve data from a connected object. The format of this data is as follows: { "devEUI": "8cf9572000023509", "appID": 1, "type": "uplink", "time": 1629378939869, "data": { "gwid": "b827ebfffebce2d3", "rssi": -77, "snr": 10, "freq": 868.1, "dr": 5, "adr": true, "class": "C", "fCnt": 852, "fPort": 8, "confirmed": false, "data": "AgUCIzYBAIERAAAAAAAAAAAAAAAAAAAAAAAAAADHDgA=", "gws": [ { "id": "b827ebfffebce2d3", "rssi": -77, "snr": 10 } ] } } I develop with django. I want to write a REST api with django.Should the data and gws fields be classes? How can I define the classes? -
Passing a token in the header of a ListAPIView endpoint from one api to another Django REST
I have 2 APIs in Django REST. One API generates a JWT token. I want to send that token to another API. In the first API (API 1), I am posting the token to the ListItems class (/someendpoint/) in the header of the POST request. import requests token = "someToken" requests.post("/posting/token", {token}) In another API (API 2), I want to receive that JWT token in the request header : in views.py: class ListItems(generics.ListAPIView): permission_classes = [ItemsPermissions] queryset = SomeModel.objects.all() serializer_class = SomeSerializer in urls.py: url_patterns = [ path("/someendpoint/list/", ListItems.as_view(), ] What is the best way to achieve that ? -
https with nginx and docker compose not working
Please I need some assistance. Your contributions will be greatly appreciated I am trying to add ssl to my nginx and docker compose configuration. Currently, everything works fine with http, but it won't work with https. Here is my docker-compose.yml file version: '3.8' services: web_gunicorn: image: ACCT_ID.dkr.ecr.us-east-2.amazonaws.com/web_gunicorn:latest volumes: - static:/static - media:/media # env_file: # - .env pull_policy: always restart: always ports: - "8000:8000" environment: - PYTHONUNBUFFERED=1 - PYTHONDONTWRITEBYTECODE=1 nginx: image: ACCT_ID.dkr.ecr.us-east-2.amazonaws.com/nginx:latest pull_policy: always restart: always volumes: - static:/static - media:/media - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot ports: - "80:80" - "443:443" depends_on: - web_gunicorn certbot: image: certbot/certbot restart: unless-stopped volumes: - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot depends_on: - nginx entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'" volumes: static: media: Here is my nginx.conf configuration that works (http) upstream web { server web_gunicorn:8000; } server { listen 80; server_name domain.com; location / { resolver 127.0.0.11; proxy_pass http://web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /static/; } location /media/ { alias /media/; } } Here is my nginx.conf configuration that does not work (http and https) upstream web { server web_gunicorn:8000; } server { location / { resolver 127.0.0.11; …