Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can't able to save multichoice field (checkbox) data in database
Am trying to save data from multi choice field to database but it doesn't get saved in database instead it shows all many to many relationship data. Models.py class masterList(models.Model): mastername=models.CharField(max_length=150) unit=models.ForeignKey(unit, on_delete=models.CASCADE) status =models.IntegerField() def __str__(self): return self.mastername class subCategory(models.Model): sub_category_name=models.CharField(max_length=200) category=models.ForeignKey(category,on_delete=models.CASCADE) masters= models.ManyToManyField(masterList) status=models.IntegerField() def __str__(self): return str(self.sub_category_name) Forms.py class subCategoryForm(forms.ModelForm): the_choices = forms.ModelMultipleChoiceField(queryset=masterList.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model=subCategory fields=[ "category", "sub_category_name", "status", ] Views.py def add_sub_category(request): context={} form = subCategoryForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request,'add_sub_category.html',context) I think form.save_m2m() will do this job but i couldn't understand how it works. Thanks in advance :) -
Django 3.x - Custom Error Page is showing a 500 when it should be a 404
For a CS50 project I'm working on with a wiki page, I'm trying to send the right custom 404 error when a user types a page that doesn't exist in wiki/TITLE however when I type a missing page, Django throws a 500 instead of a 404. Is this a common error or did I make my error message wrong? Debug is set to False and Allowed Hosts is configured to ['*'] in settings: Here's my custom error handlers in views.py: def error_404(request, exception): context = {} response = render(request, 'encyclopedia/error_404.html', context=context) response.status_code = 404 return response def error_500(request): context = {} response = render(request, 'encyclopedia/error_500.html', context=context) response.status_code = 500 return response Here's how they are in wiki/urls.py: from django.contrib import admin from django.urls import include, path from django.conf.urls import handler404, handler500 urlpatterns = [ path('admin/', admin.site.urls), path('', include("encyclopedia.urls")), ] handler404 = "encyclopedia.views.error_404" handler500 = "encyclopedia.views.error_500" Here's what the terminal shows (my styles.css is throwing a 404 for some reason but I haven't changed anything there...that's a separate issue): -
How do I get Javascript Handler to recognize dynamically added forms via Formsets?
So after about 3 days of completely being demoralized over JQuery...come to figure out that there is an issue with Django formsets whereby if there are extra forms defined prior to the page load...all is right with the world. If the user clicks to add forms....or the add button essentially...the dynamically loaded forms are not captured by Javascript or Jquery. The data gets processed...but I am unable to manipulate the dynamically generated forms via Javascript or JQuery. I tried to add event listeners programmatically but that didn't seem to help. Essentially...I have a link that is generated by jquery.formset.js. It looks like... <a class="delete-row-budget" href="javascript:void(0)">Del</a> It gets generated fine...but the issue is that it's invisible to JQuery and Javascript. Has anyone else encountered this? I did come across this issue which sounds identical but have not been able to get this solution to work....https://stackoverflow.com/questions/61036000/how-to-handle-javascript-event-inside-a-inlineformset-factory-with-formset-media Thanks in advance for any thoughts or ideas. -
How to pass form data as instance in Django?
info: I am trying to make an app like monthly installment payment of items(property or etc). I want when I fill out the customer form and select the product, I have to submit the payment form along with it and that payment will be linked to that customer. So in order to do this work, I have created a CustomerPayment model. I don't know how the models should be designed to do this. Problem I am trying to submit the customer payment along with the customer form but my form is not submited it's redirect me to back on form. i don't know how can i pass the both form data as instances of CustomerPayment (customer=customer & payment=payment). Example: models.py class Customer(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=11, blank=True) class Payment(models.Model): collect_by = models.ForeignKey(User, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) amount = models.FloatField(default=0) class CustomerPayment(models.Model): customer = models.ForeignKey(Customer, related_name='Customer', on_delete=models.CASCADE) payment = models.ForeignKey(Payment, related_name='Payment', on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) views.py def order_form(request): customer_form = CustomerForm(request.POST) payment_form = PaymentForm(request.POST) customer_payment_form = CustomerPaymentForm(request.POST) if request.method == 'POST': if customer_form.is_valid() and payment_form.is_valid() and customer_payment_form: customer = customer_form.instance.sales_men = request.user customer.save(commit=False) payment = payment_form.instance.collect_by = request.user payment.save(commit=False) customer_payment_form.instance.customer = customer customer_payment_form.instance.payment = payment customer_payment_form.save() return redirect('/') context … -
Any idea on why my django LoginView form isn't being displayed?
I'm trying to display the LoginView form but it won't display. I've been looking at the documentation for almost an hour and I cannot seem to figure out why the form is not being displayed. It accepts my template so it's rendering the template properly but not creating the form within the HTML form tags. urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ] Login HTML {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <!-- fieldset used to group related elements into a form --> <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> <!-- Loads in the form_key's value within our view with P tags instead--> <!-- {{ form_key }} --> {{ form_key|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Don't have an account yet? <a class="ml-s" href="{% url 'register' %}">Sign up now</a> </small> </div> </div> {% endblock content %} BASE HTML {% load static %} <!-- Loads in our static folder … -
Getting cloudinary default image to work with Django object
I'm trying to get Cloudinary default image to show up in my Django template, but it's not working. Each image URL works separately, but when combined, neither works. It goes to the one error. <img src="https://res.cloudinary.com/.../d_{{ id }}/{{ system|lower|cut:' '}}.png" width="250px" onerror='this.onerror = null; this.src=""'/> -
login - 'AnonymousUser' object has no attribute '_meta'
If password is not correct I am getting this kind of error, I don't know why. I can usually register, log in, log out, but when password is incorrect something wrong is happening. I am using AbstractBaseUser registration form. I will appreciate any help and thank you in advance. views.py from django.http.request import HttpRequest from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.contrib import messages from .forms import RegistrationForm, LoginForm, UserChangeForm, ChangePasswordForm from .models import Account from django.conf import settings @csrf_exempt def sign_in(request): form = LoginForm() context = {'form':form} if request.method == "POST": form = LoginForm(request.POST or None) Account.objects.get(email=request.POST.get('email')) if form.is_valid(): data = form.cleaned_data user = authenticate(email=str(data['email']), password=str(data['password'])) login(request, user) return redirect('/') return render(request, 'login.html', context) -
How do I remove the "Installed x object(x) from y fixture(s)" report from django test?
I am using fixtures during my django tests as they are proving to be quite useful def some_test(self): ... call_command('loaddata', 'path/to/fixture.json') ... self.assertTrue(...) And when I run my tests, they all pass: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ..Installed 2 object(s) from 1 fixture(s) ...................................... ---------------------------------------------------------------------- Ran 40 tests in 0.104s OK Destroying test database for alias 'default'... However, the "Installed 2 object(s) from 1 fixture(s)" is starting to annoy me. Is there a way to reduce the verbosity of the command? So then it could look like: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ........................................ ---------------------------------------------------------------------- Ran 40 tests in 0.104s OK Destroying test database for alias 'default'... Which is what I want -
How does the Django template engine work?
In Django, I wonder when and when the code written in the django template language in the html file works. I looked for the official documentation, but couldn't find it. -
Changing admin site codes to another app in Django
I am learning django I would like to move admin to another app that I created but I couldn't do and don't know how to do it. How can I move all admin site codes to another app? Simply moving or creating admin codes in that app didn't work. -
Getting a "Django can only handle ASGI/HTTP connections, not websocket." error when hosting ASGI on heroku?
Been scrolling though every question on StackOverflow and Youtube to find an answer. I'm deploying both WSGI and ASGI/websockets via Django channels on Heroku. It works locally, but it's been giving me trouble during production. Setup Here's my procfile: web: daphne API.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker background -v2 Settings.py: # Redis Setup ASGI_APPLICATION = 'API.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(HEROKU_URL, 6379)], }, }, } asgi.py: import os import django from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'API.settings') django.setup() application = get_asgi_application() And finally, routing.py: application = ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^timer/$", TestConsumer.as_asgi()), ] ) ) ) ,'channel':ChannelNameRouter({ 'background':BackgroundConsumer.as_asgi() }) }) Problem/logs Heroku logs when connecting to the websocket: 2021-07-02T19:42:42.209398+00:00 app[web.1]: IP - - [02/Jul/2021:19:42:42] "GET /chat_switch/1/" 200 10480 2021-07-02T19:43:02.708851+00:00 app[web.1]: IP - - [02/Jul/2021:19:43:02] "WSCONNECTING /timer/" - - 2021-07-02T19:43:02.709658+00:00 app[web.1]: 2021-07-02 19:43:02,709 DEBUG Upgraded connection [IP, 32183] to WebSocket 2021-07-02T19:43:03.058159+00:00 app[web.1]: 2021-07-02 19:43:03,057 ERROR Exception inside application: Django can only handle ASGI/HTTP connections, not websocket. 2021-07-02T19:43:03.058167+00:00 app[web.1]: Traceback (most recent call last): 2021-07-02T19:43:03.058168+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/asgi.py", line 143, in __call__ 2021-07-02T19:43:03.058168+00:00 app[web.1]: raise ValueError( 2021-07-02T19:43:03.058169+00:00 app[web.1]: ValueError: Django can only handle ASGI/HTTP connections, not websocket. 2021-07-02T19:43:03.059813+00:00 app[web.1]: 2021-07-02 19:43:03,059 INFO … -
How to share validation and schemas between a DRF FilterBackend and a Serializer
I am implementing some APIs using Django Rest Framework, and using the generateschema command to generate the OpenApi 3.0 specs afterwards. While working on getting the schema to generate correctly, I realized that my code seemed to be duplicating a fair bit of logic between the FilterBackend and Serializer I was using. Both of them were accessing and validating the query parameters from the request. I like the way of specifying the fields in the Serializer (NotesViewSetGetRequestSerializer in my case), and I would like to use that in my FilterBackend (NoteFilterBackend in my case). It would be nice to have access to the validated_data within the filter, and also be able to use the serializer to implement the filtering schemas. Are there good solutions out there for only needing to specify your request query params once, and re-using with the filter and serializer? I've reproduced a simplified version of my code below. I'm happy to provide more info on ResourceURNRelatedField if it's needed (it extends RelatedField and uses URNs instead of primary keys), but I think this would apply to any kind of field. class NotesViewSet(generics.ListCreateAPIView, mixins.UpdateModelMixin): allowed_methods = ("GET") queryset = Note.objects.all() filter_backends = [NoteFilterBackend] serializer_class = NotesViewSetResponseSerializer def … -
Passing a callable to the default option of a model field fails
I have a model named Package. It has fields named, diagnosis, treatment, patient_type, mf and tp. The fields diagnosis, treatment and patient_type have foreign keys defined in separate individual classes, making diagnosis, treatment and patient_type choice fields. Now, what I intend to achieve is that whenever the user chooses the treatment and patient_type from the choices, I want certain figure to appear in mf as a default value. It should be dependant on both the above fields. I have defined a function that takes treatment and patient_type as its arguments, applies the suitable conditions and returns the relevant figure. But when I assign the function to the default option to the mf field, run the migrations and open the webpage and fill in the details in treatment and patient_type, the mf does not return the desired value. What is going on here, is there something that I am doing wrongly? The models: class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) def __str__(self): return self.diagnosis class Treatment(models.Model): treatment=models.CharField(max_length=15, blank=True) def __str__(self): return self.treatment class PatientType(models.Model): patient_type=models.CharField(max_length=15, blank=True) def __str__(self): return self.patient_type class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) max_fractions=models.IntegerField(default=max_fraction(treatment, patient_type)) total_package=models.DecimalField(max_digits=10, decimal_places=2) The function that is added to the default option in … -
Error while trying to connect Django to SQL Server using django-mssql-backend
Windows 10 SQL Server 2019 Python 3.9.1 Django 3.2.5 pip freeze: asgiref==3.4.1 Django==3.2.5 django-mssql-backend==2.8.1 djangorestframework==3.12.4 pyodbc==4.0.30 pytz==2021.1 sqlparse==0.4.1 DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dbForDjango', 'USER': 'sa', 'PASSWORD': 'sdf874sd21', 'HOST': 'DESKTOP-AR76KF2\SQL_SERVER', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } I can run the server without any problem also py manage.py shell is working but Django can't communicate with the database at all. The command "py manage.py dbshell" occurs this error: Please ignore the directory name "playingWithFastAPI", am using Django not FastAPI :) py manage.py migrate occurs that error: -
Django GET request result for data not in API
Context I am using django to take user input via a form. This data, city_name, is then used to call an API for weather data. The request works fine when an actual city name is given. Blocker/Obstacles However, these 2 specific cases result in the following error. Invalid city name Search button is clicked without entering anything into the form I have tried using some conditional logic to no avail. Any help will be greatly appreciated. Views.py from django.shortcuts import render import requests def index(request): if 'city' in request.GET: city = request.GET['city'] # Query API with user input payload = {'q': request.GET['city'], 'appid': 'API_KEY'} response = requests.get('http://api.openweathermap.org/data/2.5/weather', params=payload) # Parse json output for key value pairs e = response.json() context = { 'city_name': e['name'], 'weather':e['weather'][0]['main'], 'description' : e['weather'][0]['description'], 'temp' : e['main']['temp'], 'pressure':e['main']['pressure'], 'humidity':e['main']['humidity'], 'visibility':e['visibility'], 'wind_speed':e['wind']['speed'], 'wind_deg':e['wind']['deg'] } # successfull response code search_was_successful = (response.status_code == 200) # 200 = SUCCESS context['success'] = search_was_successful return render(request, 'index.html', {'context': context}) else: context = None return render(request, 'index.html', context) HTML(index.html) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WeatherApp</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"> </head> <body> <div align="center"> <h1>Weather in your city</h1> <form action="" method="get"> <input type="text" id="city" name="city" placeholder="Enter a city"> <input type="submit" name="send" value="Search"> … -
AttributeError: module 'django.db.models' has no attribute 'CharFiled'
class Profile(models.Model): File "C:\Users\Billal's PC\Desktop\Django-stuff\My_Ecom\App_Login\models.py", line 78, in Profile username = models.CharFiled(max_length=10, blank=True) AttributeError: module 'django.db.models' has no attribute 'CharFiled' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') username = models.CharFiled(max_length=10, blank=True) full_name = models.CharFiled(max_length=264, blank=True) address_1 = models.TextField(max_length=300, blank=True) city = models.CharFiled(max_length=40, blank=True) zipcode = models.CharFiled(max_length=30, blank=True) country = models.CharFiled(max_length=50, blank=True) phone = models.CharFiled(max_length=20, blank=True) date_joined = models.DateTimeField(auto_now_add=True) -
Dynamic carousel slider with django and bootstrap
I was trying to make image carousel slider of product in my product detail page but I cant make it work properly i tried for loop counter but that doesn't work either I think I have to do some changes in views.py for carousel slider please suggest me some solutions This is my code <div class="container-fluid px-0" style="background-image: url(/static/images/wallpaperflare.com_wallpaper.jpg);background-size: cover; background-repeat: no-repeat;" > {% for product in product%} <div class="row" style="margin-right:0px"> <div class="col-md-6 box "> <!-- Create slider --> <div class="carousel slide" data-ride="carousel" id="abcd"> <!-- Carousel Indicators --> <ul class="carousel-indicators"> <li class="active" data-target="#abcd" data-slide-to="0"></li> <li data-target="#abcd" data-slide-to="1"></li> <li data-target="#abcd" data-slide-to="2"></li> <li data-target="#abcd" data-slide-to="3"></li> </ul> <div class="carousel-inner"> <div class="carousel-item {% if forloop.counter0 == 0 %}active{% endif %}"> <img src="/media/{{product.images.0}}" class="" alt="" id="lol"> </div> <!-- Carousel COntrol --> <a href="#abcd" class="carousel-control-prev" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a href="#abcd" class="carousel-control-next" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> </div> </div> <div class="col-md-6 box2 pl-5"> <div class=" mt-4"> <p style="color: rgb(82, 81, 81);margin-top: 120px;" >{{product.brand|upper}}</p> <h1 class="mt-3 st" >{{product.name}}<i class="pl-2 product-favourite far fa-heart" id="dtheart{{product.id}}" onclick="add_to_favorite('{{product.id}}')", data-toggle="tooltip" data-placement="top" title="Add to wishlist"></i></h1> <h3 class="mt-3" style="color: rgb(255, 7, 123);"></h3> <p class="mt-3" style="color: rgb(82, 82, 82);font-size: large;">{{product.description}}</p> <p style="font-size: 20px; font-weight: bolder;">Size: {{product.size}}</p> <p style="font-size: 20px; font-weight: bolder;">Color: {{product.color}}</p> <h3>Price: {% if … -
Django - Page redirect showing as empty page after saving?
I'm working through a Wiki project for CS50's web course and I'm having an issue with my edit entry implementation. I'm able to edit an entry and it saves properly but for some reason, redirecting the user to the newly edited entry is only showing an empty entry page like this: here's my views. py: def edit(request, title): content = util.get_entry(title) if request.method == "GET": return render(request, "encyclopedia/edit.html", { "title": title, "content": content }) elif request.method == "POST": title = request.POST.get("title") content = request.POST.get("content") util.save_entry(title, content) html = md_converter(util.get_entry(title)) return render(request, "encyclopedia/entry.html", { "title": title, "content": html }) else: return render(request, "encyclopedia/edit.html", { "title": title, }) and my urls.py: from . import views app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry_page, name="entry"), path("wiki/edit/<str:title>", views.edit, name="edit"), path("search", views.search, name="search"), path("random", views.random_page, name="random"), path("create_landing",views.create_landing_page, name="create_landing"), path("create_entry",views.create_entry, name="create_entry") ] Is there something wrong with my redirect? When I revisit the entry page, the page shows the edits I made Thanks so much for reviewing. -
NoReverseMatch at / Reverse for 'foroshande' with arguments '('',)' not found. 1 pattern(s) tried: ['foroshande/(?P<prof_id>[^/]+)$']
idk what to do with this. looks like ineedto pass prof_id in home but i dont need an id in my url this is home views.py from django.shortcuts import render from .models import * from .forms import * def home(request): form = DatasetForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'main/home.html', {'form': form}) def foroshande(request, prof_id): prof = DatasetModel.objects.get(pk=prof_id) return render(request, 'main/foroshande.html', {'prof': prof}) home.html {% block content %} <form method="POST" action="{% url 'foroshande' form.id %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save" /> </form> {% endblock %} foroshande.htlm {% block content %} <form method="POST"> {% csrf_token %} {{ prof }} <input type="submit" value="save" /> </form> {% endblock %} models.py from django.db import models class DatasetModel(models.Model): open_or_close_CHOICES = ( ("baaz", "baaz"), ("basteh", "basteh") ) name = models.CharField(max_length=100) address = models.CharField(max_length=500) open_or_close = models.CharField( max_length=20, choices=open_or_close_CHOICES, default="baaz" ) forms.py class DatasetForm(forms.ModelForm): class Meta: model = DatasetModel fields = ['name', 'address', 'open_or_close'] idk what to do with this. looks like ineedto pass prof_id in home but i dont need an id in my url this is home -
how do i get crispy form to visibly show an error message?
i have django 3.2, latest crispy forms. with bs template: CRISPY_TEMPLATE_PACK = "bootstrap5" from here I am using a ModelView and Model form. class HspRegistrationForm(ModelForm): def __init__(self, *args, **kwargs): super(HspRegistrationForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'id-hspr' self.helper.layout.append(Submit('save', 'save')) class Meta: model = HomeServiceProvider fields = [...] class HspRegistrationView(CreateView, UserPassesTestMixin): form_class = HspRegistrationForm # sepcify name of template template_name = "mainss/hsp_registration.html" success_url = "/" def test_func(self): return self.request.user.is_active def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) the form is being generated correctly sample below: <form id="id-hspr" method="post" > <input type="hidden" name="csrfmiddlewaretoken" value="..."> <div id="div_id_bus_name" class="mb-3"> <label for="id_bus_name" class="form-label requiredField">Business Name<span class="asteriskField">*</span> </label> <input type="text" name="bus_name" maxlength="200" class="textinput textInput form-control" required id="id_bus_name"> <small id="hint_id_bus_name" class="form-text text-muted">Name of the HSP business</small> </div> .... </form> and when i try submit with something invalid like a required field it will auto take me to that field to indicate it needs filled out. however, there isn't any visible change like an error message or highlighting like i would expect given tutorials and documentation i read. -
Create a token with customer saved card
I want to charge users only when a product has been marked as ready to dispatch. Currently, I can't seem to find a way to create a token for payment server side. Is there a way to do this at all? This is what I've tried so far. All except for token creation works. def charge(request, subscription): stripe.api_key = STRIPE_SECRET_KEY subscription = Subscription.objects.get(id=subscription) user = subscription.customer customer = stripe.Customer.retrieve(user.stripe_id) card_id = user.card token = stripe.Token.create(card=card_id) charge = stripe.Charge.create( amount=500, currency='usd', description='description', source=card_id ) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Custom django admin change form
Hi guys I added a custom change form to one of my models in the admin portal, how can I get access to the current model in the template? I need to prefil fields and create a dropdown for a many to many Also on save how do I redirect to the list view? The form I have submits to a custom view -
pytest fixture to make an AIPClient that I have information for
I am trying to make a fixture that returns an APIClient object that is authenticated for a user that I can pass a parameter to if I need. I have a DjangoModelFactory object called CustomerFactory that can create a customer and a user, the user of which is created with a UserFactory factory. I want to be able to access the data in the customer that is created, but also have a fixture to make an authenticated API request. This api_customer_client is what I came up with, and it doesn't work. @pytest.fixture def api_client(): return APIClient() @pytest.fixture def api_customer_client(app_customer, api_client): def _api_customer_client(test_customer=app_customer): refresh = RefreshToken.for_user(test_customer) api_client.credentials(HTTP_AUTHORIZATION=f"JWT {refresh.access_token}") return api_client return _api_customer_client I am calling the fixture with this test: def test_client_cant_view_users_without_token(self, api_customer_client, app_customer): client = api_customer_client(test_customer=app_customer.user) result = client(reverse("api:user-list"), format="json") assert result.status_code == 401 I keep getting the error TypeError: 'APIClient' object is not callable, and I can't figure out why. I originally thought it might be having trouble going through the api_customer_client fixture and returning a different fixture, but I have tried to just use APIClient directly in the api_customer_client fixture, and that didn't work either. I have another fixture that is nearly identical, except for the sub-method thing, … -
Twilio Unable to send fax
Hope you are having a nice day. I am getting following error on twillion fax api HTTP Error Your request was: POST /Faxes Twilio returned the following information: Unable to create record: The requested resource /Faxes was not found Here is the code . def __init__(self): self.client = Client( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN, ) self.sender = settings.FAX_SENDER self.receiver = settings.FAX_RECEIVER self.callback_url = settings.TWILIO_CALLBACK_URL i am sending a fax in function with this code fax = self.client.fax.faxes.create( from_=self.sender, to=self.receiver, media_url=pdf_url, status_callback=self.callback_url, ) Is there something I am doing wrong ? -
django tmeplate view is loading slow
I have a template view temrinal management that hs 2 forms and 2 querysets, i am not doing any sorting stuff only a filtering method. I have no idea why the page goes slow, can it happen because of internet connection? I am using a mysql database that is on a separate server. class TerminalManagementView(LoginRequiredMixin, TemplateView): template_name = "app/terminal_management.html" def post(request): pass def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tb_terminal_categories'] = TbTerminalCategory.objects.all() context['tb_terminal_caregory_form'] = TbTerminalCategoryForm() context['tb_terminal_register_form'] = TbTerminalRegisterForm() filter = self.request.GET.get('category') if filter: terminals = TbTerminal.objects.all().filter(category__category_name=filter) else: terminals = TbTerminal.objects.all() page = self.request.GET.get('page', 1) paginator = Paginator(terminals, 9) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context['terminals'] = data return context from django import forms from .models import TbDepartment, TbTerminal, TbTerminalCategory class TbDepartmentForm(forms.ModelForm): department_name = forms.CharField( max_length=60, required=True) class Meta: model = TbDepartment fields = ['customer', 'department_name', 'parent'] class TbTerminalCategoryForm(forms.ModelForm): class Meta: model = TbTerminalCategory fields = ['category_name', 'category_desc'] class TbTerminalRegisterForm(forms.ModelForm): class Meta: model = TbTerminal fields = ['terminal_name', 'terminal_desc', 'room', 'device_model']