Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Module Object is Not Callable Problem
I'm struggling to fix an error that doesn't allow me to access my /api/lead/ URL, as I keep getting an error "module object is not callable. Within my DjangoApp project, I have one other folder named api, and one other folder with the standard name of the project, which in my case is "DjangoApp". api/models.py : from django.db import models # Create your models here. class Lead(models.Model): name = models.CharField(max_length=100) email = models.EmailField() message = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) api/LeadListCreate.py : from .models import Lead from api import LeadSerializer from rest_framework import generics class LeadListCreate(generics.ListCreateAPIView): queryset = Lead.objects.all() serializer_class = LeadSerializer api/LeadSerializer.py : from rest_framework import serializers from .models import Lead class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = ('id', 'name', 'email', 'message') api/urls.py : from django.urls import path from . import views urlpatterns = [ path('api/lead/', views.LeadListCreate.as_view() ), ] DjangoApp/urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('api.urls')), ] -
Secure Websocket and https with Django [closed]
I am working with a Django development server in version 4.0.1 which uses an SSL certificate (https). The application uses websockets and there is the problem: it doesn’t work. Please note that the use of websockets works without SSL certificates. I’ve read that all you have to do is change “ws://” to “wss://” but that doesn’t seem to be enough. Do you have an idea? Thanks, MLP. -
How do I Filter a viewlist based on a selection made on a createview form? Django
I am learning how to use Python & Django. I don't have much experience, and this has been a huge learning process for me. Please forgive any ignorance in my question. I am designing a Django app and have a few relational tables created. My question involves only my first 2 models/forms/views. Here are my models ` class CustomerName(models.Model): #Fields company = models.CharField(max_length = 60, help_text = "Enter Customer Name",unique=True) def __str__(self): return self.company class ProgramName(models.Model): #Fields customer = models.ForeignKey("CustomerName",on_delete=models.CASCADE) program = models.CharField(max_length = 60, help_text = "Enter Program Name") def __str__(self): return self.program ` Here are my Views (Ive left out the customer add view since that works and I don't think its relevant) ` class ProgramAddView(CreateView, ListView): template_name = 'app/ProgramAdd.html' form_class = Programform model = ProgramName success_url = reverse_lazy('Part Number Add') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(ProgramName.objects.values())) return context ` Here is the form ` class Programform(forms.ModelForm): class Meta: model = ProgramName fields = "all" class Customerform(forms.ModelForm): class Meta: model = CustomerName fields = ('company',) ` Here is the HTML app/ProgramAdd.html ` {% extends 'base.html' %} {% block content %} <h2>Program</h2> <form method="post" class = 'formarea'> <div id = 'formarea' class = 'formdiv'> {{ form.media.js … -
BooleanField Model not showing the default False value
I have a model class where the variable completed_application should default to False when creating a new user (to show that the user hasn't completed an application yet). However, by default when a new user is created it doesn't show as False in Django admin but '-' instead. models.py: class Completed(models.Model): class Meta: verbose_name_plural = 'Completed Application' user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) completed_application = models.BooleanField(default=False) admin.py: class Company(admin.StackedInline): model = Completed can_delete: False verbose_name_plural = 'Completed Application' class UserAdmin(UserAdmin): list_display = ('username', 'first_name', 'last_name', 'email', 'company', 'completed') search_fields = ('username', 'email',) inlines = [Company] list_filter = ('is_active',) fieldsets = ( (None, {'fields': ('username', 'password')}), (('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (('Permissions'), { 'fields': ('is_active', 'is_staff', 'groups',), }), (('Important dates'), {'fields': ('last_login', 'date_joined')}), ) The red arrow in the first image above points to the Users admin panel for a newly created user. The second image shows the individual user in Django admin with the custom model added to that user. Other point to note: Checking the box and saving the user it shows True (as to be expected), but then unchecking the box and saving the user it eventually shows False and not '-'. Could someone explain what this '-' means … -
Partial update to extended user profile
I have a extension to user model in Django, adding multiple fields to the regular user profile. In order for the user to be able to change them, I have created a form that should be able to modify those fields but with no success... models.py class UserProfileModel(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) agency_name = models.CharField(max_length=255, null=True) license_number = models.CharField(max_length=10, null=True) phone = models.CharField(max_length=10, null=True) phone2 = models.CharField(max_length=10, null=True) fax = models.CharField(max_length=10, null=True) address = models.CharField(max_length=255, null=True) city = models.CharField(max_length=255, null=True) zip_code = models.CharField(max_length=10, null=True) about = models.CharField(max_length=255, null=True) # חפ pi_id = models.CharField(max_length=10, null=True) reason_pension = models.CharField(max_length=255, null=True) reason_policy = models.CharField(max_length=255, null=True) reason_gemel = models.CharField(max_length=255, null=True) reason_hishtalmot = models.CharField(max_length=255, null=True) def __str__(self): return str(self.user) class Meta: ordering = ('user',) forms.py class UserProfileChangeForm(forms.ModelForm): customer_name = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "שם לקוח", "class": "form-control" } )) labelwhite = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "", "class": "form-control" } )) smoker = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "מעשן", "class": "form-control" } )) ensurence_amount = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "ביטוח חיים", "class": "form-control" } )) ensurence_amount1 = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "00000", "class": "form-control" } )) disability_amount = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "נכות מתאונה", "class": "form-control" } )) class Meta: model = LifeEnsurenceModel fields = ('customer_name', … -
How to set a default time in Django ModelForm
I created a Django ModelForm. Here is the models.py file class Room(models. Model): available_from = models.TimeField() available_till = models.TimeField() Here is the forms.py file class RoomForm(forms.ModelForm): class TimeInput(forms.TimeInput): input_type = 'time' available_from = forms.TimeField( widget=TimeInput(), ) available_till = forms.TimeField( widget=TimeInput(), ) class Meta: model = Room fields = ['available_from','available_till'] I want to know how to set a default time to the form. -
asyncio loop blocking django http and websocket requests
i've been trying to build application where i need to listen to the postgres notify listen constantly and send those messages via websocket and also need the usual django apis, i'm able to run both separately, but as initiate the db listener it starts blocking http or websocket requests connection = get_db_conn() connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cur = connection.cursor() cur.execute("LISTEN new_item_added;") async def db_listen(): print('Started Listening to DB notify ...') while True: await asyncio.sleep(1) data = await queue.get() await NotificationConsumer.send_data(data.payload) # class method to send over websocket print("message received: ", data.payload) def listen_callback(): connection.poll() queue.put_nowait(connection.notifies.pop(0)) # calling this function from django app's __init__.py file def initiate_db_listener(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.add_reader(connection, listen_callback) loop.run_until_complete(db_listen()) if __name__ == '__main__': initiate_db_listener() i tried many variations of it, all are blocking the main thread -
How does token based authentication work?
I implement a web application (with Python+Django - to the extent that matters). Users can log in normally with username and password, but in addition I want to provide an API which users use to script the interaction with my site. For the API authentication my plan was to do something like this: In the database I create table with 'tokens' - i.e. random strings which point to the user database. The user gets a token string. For every API call the user passes the token string along with their request In the API implementation the code: Verify the token. Log the correct user in and execute the API function as the user matching the token. Log the user out again. Return the result Does this make sense? On the one hand it seems very simple - on the other hand it feels quite homemade, something I have heard is not recommended when it comes to security related topics? -
Django 'x' object has no attribute 'get_form'
I have a generic DetailView and I'm trying to do a form for the comment of an user after I display the details of the model but I keep getting the error 'ProductFeedbackView' object has no attribute 'get_form'. I don't know if the templates have any problem because the error is in the view when I try to get the form into a variable. Here is comment's model: class Comment(models.Model): service = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=False, blank=True) ... def get_absolute_url(self): return reverse('product-feedback', kwargs={'pk': self.pk}) Comment's form: class CommentForm(forms.ModelForm): content = forms.CharField() class Meta: model = Comment fields = ['content'] View: class ProductFeedbackView(DetailView): model = Product template_name = 'services/product-feedback.html' form_class = CommentForm def get_success_url(self): return reverse('product-feedback', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CommentForm(initial={'content': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) urls's: ... path('feedback/<int:pk>/', ProductFeedbackView.as_view(), name='product-feedback'), Template: <a href="{% url 'product-detail' product.id %}">Details</a> <a href="{% url 'product-feedback' product.id %}">Feedback</a> <p>{{ product.author }}</p> <h1>{{ product.title }}</h1> <p>{{ product.description }}</p> {% if user.is_authenticated %} <form method="POST"> … -
DRF filter/search return everything?
I'm currently doing self project inventory app and trying to implement filter and search. what I've done #views.py from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters class ListInventories(generics.ListAPIView): serializer_class = Inventory filter_backends = [filters.SearchFilter] search_fields = ['name'] filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'stock'] def get(self, request): inventories = Inventory.objects.all() serializer = InventorySerializers(inventories, many=True) return Response({'inventories': serializer.data}) class InventoryDetails(APIView): def get(self, request, pk): inventories = Inventory.objects.get(id=pk) serializer = InventorySerializers(inventories) return Response({'inventory': serializer.data}) in settings.py INSTALLED_APPS = [ ... 'django_filters', ... ] in url: http://127.0.0.1:8000/api/inventory?name=para I tried ?search=para and ?search=anynonsense . and the DRF would always return everything. just for the sake of clarification here is the screenshot(the total of item is just 3 for now, but even then filter/search should work): I expect the filter/search to function at least on a minimal level. What do I do to make this right? -
Django validation error from nested serializer
Inside a run_validation method I am calling another serializer's is_valid(raise_exception=True). If the input is not valid to the other serializer, then the program fails with the following error. super().__init__(*args, **kwargs) ValueError: need more than 0 values to unpack Here goes the code: def run_validation(self, data): modules = data.getlist("modules", []) if "modules" in data else [] if len(modules) > 0: sm_ser = SMSerializer(data=modules, many=True) sm_ser.is_valid(raise_exception=True) return super(CSSerializer, self).run_validation(data) Question 1. Is it ok to call validation for another object like this in this method? Question 2. How to make the run_validation raise the errors that are coming from the other serializer. sm_ser.errors is a list of errors which is not coming through. [ { "coordinates":{ "26":{ "1":[ "ErrorDetail(string=""Ensure that there are no more than 25 digits in total.", "code=""max_digits"")" ] }, "27":{ "1":[ "ErrorDetail(string=""Ensure that there are no more than 14 decimal places.", "code=""max_decimal_places"")" ] }, }, "c_coordinates":{ "50":{ "1":[ "ErrorDetail(string=""Ensure that there are no more than 14 decimal places.", "code=""max_decimal_places"")" ] } } }, ] -
How to exclude html from js export to xlsx with ExcellentExports.js?
Thanks in advance! In case it helps I am using Django3 and Python3 for the backend and javascript, html, and css for the front end. I am also using ExcellentExport.js to export html tables to excell. It works great with one caveat. It is exporting the entire html page instead of the two ids I specified. the html code snip of the tables to be exported: <div id="table1" class="position-absolute text-nowrap" style="max-width: 300px; max-height: 50px; right: 1600px; top: 145px;"> {% render_table tableP18 %} </div> <div id="table2" class="position-absolute" style="max-width: 100px; max-height: 10px; right: 1300px; top: 365px;"> {% render_table tableP17 %} </div> My js: function export() { return ExcellentExport.convert({ anchor:this, filename:'data_123.array',format: 'xlsx'}, [ {name: 'filename1', from: {table: 'table'}}, {name: 'filename2', from: {table: 'table2'}} ]); } What I'm trying to figure out is how to exclude certain html elements from the export in either the html or in js. Please let me know if you need any more information or code! -
Suitescript 2.x: Create a Customer Deposit upon Approval of Sales Order
Can you please check my code. I want to create a Customer Deposit upon approval of Sales Order. However, the Customer Deposit is both being created in Pending Approval and Pending Fulfillment. Can you please help fix my code. Thank you! /** *@NApiVersion 2.x *@NScriptType UserEventScript */ define(["N/record"], function (record) { try { function afterSubmit(scriptContext) { if (scriptContext.type == scriptContext.UserEventType.CREATE || scriptContext.type == scriptContext.UserEventType.EDIT) { var objSoRecord = scriptContext.newRecord; log.debug("Load the Sales Order", objSoRecord); var intsoId = objSoRecord.id; log.debug("Get the Sales Order Id: " , intsoId) var stCustomer = objSoRecord.getValue({ fieldId: 'entity' }); log.debug("Customer ", stCustomer) //Get Values var checkStatus = objSoRecord.getValue('status'); log.debug("SO status: " , checkStatus); if (checkStatus !== "Pending Approval"|| checkStatus == "Pending Fulfillment") { var objcustDeposit = record.create({ type: record.Type.CUSTOMER_DEPOSIT, isDynamic: true, defaultValues: { 'entity': stCustomer, 'salesorder': intsoId } }); //Insert Code here var saveCustDep = objcustDeposit.save(); } } } } catch (error) { log.debug("Capture Error:", error); } return { afterSubmit: afterSubmit } }); N/AN/AN/AN/AN/AN/AN/AN/AN/AN/A -
models in django. is many to many the best option?
I am trying to make my first website with django. Basically I'm making a website to check the bus schedule in my rural area. I think that the best thing is to make two models, one where all the bus stations are defined and the other where the route is established, for each route two stations are needed (origin and destination). I was wondering what was the best way to relate the two models. class BusStations(models.Model): bus_stations = models.CharField(max_length=80) bus_stations_identifier = models.IntegerField() def __str__(self): return self.bus_stations class Routes(models.Model): origin_station = models.ManyToManyField( BusStations, related_name='origin_station') destination_station = models.ManyToManyField( BusStations, related_name='destination_station') data = models.JSONField() slug = models.SlugField(unique=True, null=True) def __str__(self): return f'{self.origin_station} - {self.estacion_destino}' For now I was doing it with ManytoMany relationships, but this is giving me problems. For example, I am not able to return the origin and destination stations as str in the route model. I would also like it to be the slug. Thanks for advance. -
COMO PROTEGER URL DE FICHEROS ESTATICOS EN DJANGO
HOLAAAA BUENAS TARDES HE ESTADO TRABAJANDO EN UNA APP PARA REGISTRO DE DOCUMENTOS EN FORMATOS PDF, HASTA EL MOMENTO TODO MUY BIEN , PERO ME ENCUENTRO LA PROBLEMATICA DE QUE CUANDO GENERE MI TABLA DE CONSULTA Y CONFIGURO MI VISTA DE LOS ARCHIVOS DICHA VISTA NO ESTA PROTEGIDA, YA QUE CUANDO DESCONECTO EL SERVIDOR DE DJANGO Y COPIO LA URL ME DA ACCESO CON LOGUEO Y SIN LOGUEO COMO PUEDO PROTEGER ESA RUTA.. ALGUNA AYUDA POR FAVOR EL PROYECTO FUE HECHO EN DJANGO -
Multiple django databases and queries
good work. I have a database connection structure as follows. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DATA', 'USER': 'postgres', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '5432', }, "big_data": { "ENGINE": "mssql", "NAME": "DATABASE_NAME", "USER": "USER_NAME", "PASSWORD": "PASSWORD", "HOST": "HOST_ADDRESS", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, } I need to fetch and display data via mssql. And this, `from django.db import connections with connections['big_data'].cursor() as cursor: cursor.execute("SELECT * FROM [aab].[CENTER]")` but the page load is delayed. To get this with django orm python manage.py inspectdb --database=big_data > models.py i run it gives a blank output. It says on the internet that it doesn't receive it because of the database schema. How can I get around this how can I get it on django orm just to write a query. Page load speed is very good in queries performed with Django orm. Also, when I create the model file manually, it adds the application name to the beginning of the table and I can't ask what I did. This is a problem for me. The database I connect belongs to a different system, so I can't interfere too much because I only have the … -
Django create or update model only if field not equal to certain value
We have a potential race condition where multiple users can try to create or update a record. Wondering if there's a way to create a column, than when set (to say true), then an exception will be thrown, preventing the update. The underlying database is postgres, but since we're using django to wrap it, we would like to limit ourselves to something django offers, and not mess with very specific database settings. Thanks! -
Django filer - PolymorphicTypeInvalid ContentType 37 does not point to a subclass
I am using django-filer to handle uploading images in my Django app. I am currently trying to load data from MySQL to PostgreSQL database. I have used the following commands to get data from MySQL and move it t PostgreSQL: python manage.py dumpdata myapp> myapp.json set DJANGO_SETTINGS_MODULE=myproject.settings.production python manage.py loaddata "myapp.json" All content works fine and I can see in pgAdmin4 that it's been successfully exported however when I am trying to open a website that contains images I get Internal Server Error like this: PolymorphicTypeInvalid at /myapp/homepage ContentType 37 for <class 'django_comments_xtd.models.BlackListedDomain'> #205 does not point to a subclass! Or error like this: PolymorphicTypeInvalid at /admin/myapp/articles/30/change/ ContentType 37 for <class 'django_comments_xtd.models.BlackListedDomain'> #232 does not point to a subclass! How can I get rid of this error and how can I move all image paths from MySQL to PostgreSQL? -
Creating a model instance
I have two Models, (Doctor & Patient), the Doctor Model is the parent Model, How can I make (Service_doctor) field be an instance of the Doctor's Model so that I can get the Doctor's name into the Patient's Model using for loop in the HTML Template. This is what am trying to mean; Models.py class Doctor(models.Model): Doctor_Name = models.CharField(max_length=200) def __str__(self): return self.Doctor_Name class Patient(models.Model): Name = models.CharField(max_length=200) Telephone = models.CharField(max_length=100, unique=True) Service_doctor = models.ForeignKey(Doctor, on_delete=CASCADE) def __str__(self): return self.Doctor_Name Views.py def Newpatient(request): if request.method == 'POST': Name = request.POST.get('Name') Telephone = request.POST.get('Telephone') Service_doctor = request.POST.get('Service_doctor') formdata = Patient(Name=Name, Telephone=Telephone, Service_doctor=Service_doctor) formdata.save() return render(request, 'Adm.html') ``` Any help please? -
Django signal user_login_failed not working for Custom User model , Custom Backend
I am a beginner in Django and due to my project requirements, I came to conclusion that I have to implement Custom User model, and also due to this I also implemented Custom Backend. But, now I am unable to use user_login_failed Django Signal, as I am thinking to use it for restrict the user login attempt to 3. and also, I have both encrypted and non-encrypted password and I want to authenticate both for now, but in future only encrypted password will remain in my DB ex: - "pbkdf2_sha256$390----------------------------" Any help will be a great deal to me Thanks settings.py AUTH_USER_MODEL = 'accounts.Usermanagement' AUTHENTICATION_BACKENDS = [ 'accounts.backends.EmailAuthBackend', 'django.contrib.auth.backends.ModelBackend', ] modely.py class Usermanagement(AbstractBaseUser): emailid = models.CharField(db_column='EmailID', unique=True, max_length=45,default=1) ------------ --------- ----------- objects = UsermanagementCustomUserManager() USERNAME_FIELD = "emailid" EMAIL_FIELD = "emailid" managers.py class UsermanagementCustomUserManager(BaseUserManager): def create_user(self,emailid,firstname, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not emailid: raise ValueError('Users must have an email address') user = self.model( emailid=self.normalize_email(emailid), password=password, ) user.set_password(password) user.save(using=self._db) return user backends.py from django.contrib.auth.backends import BaseBackend from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import get_user_model Usermanagement = get_user_model() class EmailAuthBackend(BaseBackend): def authenticate(self,request,username=None,password=None): # print("Custom authenticate rqst: ",request) try: print("Trying the … -
Image upload leads to Server Error (500) Django app deployed on railway.app
I have deployed a django app on railway.app. In development I can upload images but when I go to deployed app and click on upload it leads me to Server Error (500). following is my settings.py code STATIC_URL = 'static/' # STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if 'XXX' in os.environ: # Bucket config AWS_STORAGE_BUCKET_NAME = 'xxx' AWS_S3_REGION_NAME = 'xxx' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' # Static and media files STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATICFILES_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' MEDIAFILES_LOCATION = 'media' # Override static and media URLs in production STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATICFILES_LOCATION}/' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}/' html code <div> <img src="{{user_profile.profile_img.url}}" alt="Profile Image"> </div> <a href="{% url 'profile-image' user_profile.user user_profile.profile_uuid %}"</a> -
TypeError: the 'package' argument is required to perform a relative import for './myapp/manage.py.test_settings'
Trying to run script inside AWS Linux: ./runtests.sh ./myapp/manage.py and get the below error. Does anyone know what this means and what I should do? manage.py and test_settings.py are both in the main directory ./deploy-scripts/runtests.sh ./myapp/manage.py Traceback (most recent call last): File "manage.py", line 18, in <module> execute_from_command_line(sys.argv) File "/usr/local/python37/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/python37/lib/python3.7/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/usr/local/python37/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/python37/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/local/python37/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/python37/lib/python3.7/importlib/__init__.py", line 122, in import_module raise TypeError(msg.format(name)) TypeError: the 'package' argument is required to perform a relative import for './myapp/manage.py.test_settings' ./deploy-scripts/runtests.sh: line 57: flake8: command not found ------------------------ There were failed tests! Scroll up for details -
Transform python requests's exceptions to django-rest-framework's API exceptions
I'm developing a REST API using django-rest-framework that needs to interact with a 3rd party API. I use requests for comunication with this 3rd party API. Some recurrent pattern I get in my code is making a request from an APIView handler def calculate_order(order): url = f"https://api.anotherservice.com/orders/calculate/" try: response = requests.post(url, json=order.data) response.raise_for_status() # TODO: handle errors, just printing and re-raising for now except requests.exceptions.HTTPError as errh: raise errh except requests.exceptions.ConnectionError as errc: print(errc) raise errc except requests.exceptions.Timeout as errt: print(errt) raise errt except requests.exceptions.RequestException as err: print(err) raise err return response.json() # ... In my view def post(self, request, *args, **kwargs): # ... Some preprocessing code here order_calculated = calculate_order(order) return Response(order_calculated, status=HTTP_200_OK) DRF implements a mechanism that hanldes Subclasses of APIException raised inside REST framework. Django's Http404 exception. Django's PermissionDenied exception. I was wondering if there's a package for transforming requests's exceptions to exceptions objects that DRF can handle. Also I'll be glad to know any recomendation on how this should be implemented (best practices). I was googling it but terms with "Django" and "requests" drop results mostly of Django itself. -
Using an API to generate virtual numbers
I will build a website of virtual numbers, where the user can buy a number for a certain period of time and, after registering on a platform that requires a number to send a code, my website will receive the code through a webhook and return to the user. The central question is: which service fits my need? I thank. -
How to refresh token after expiry in django knox authentication?
I am running django application with django knox token authentication. I was able to do login with the package. But after the token expired, url response are throwing " Invalid Token". I don't understand how to refresh the token after expiry? whether i need to login again? if it is, the user will get irritated. How to do it in proper way? Which is the best token authentication for django rest framework?