Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to customize the schema in APIView
I have two class, CustomAPIView and ContestMessageAPI, where the ContestMessageAPI inherits from CustomAPIView. The specific structure is as follows (the irrelevant method is omitted): class CustomAPIView(APIView): """ Custom APIView """ authentication_classes = (JSONWebTokenAuthentication,) class ContestMessageAPI(CustomAPIView): """ Pass in the contest_id to get the corresponding match information """ Now I am modifying a parameter in the ContestMessageAPI class so that I can implement a function. class ContestMessageAPI(CustomAPIView): """ Pass in the contest_id to get the corresponding match information """ parameter = {'contest_id': 'Field description'} schema = AutoSchema(manual_fields=[ coreapi.Field(name=k, required=True, location="form", schema=coreschema.String(description=v)) for k, v in parameter.items() ]) Since the fragments assigned to the schema code are fixed, I want to port this code to its parent class CustomAPIView, and CustomAPIView becomes class CustomAPIView(APIView): """ 自定义的APIView """ authentication_classes = (JSONWebTokenAuthentication,) parameter = {'contest_id':'字段描述'} schema = AutoSchema(manual_fields=[ coreapi.Field(name=k, required=True, location="form", schema=coreschema.String(description=v)) for k, v in parameter.items() ]) Then I want to configure the parameter variable in the ContestMessageAPI to implement the schema that modifies its parent class, but the discovery fails. After querying the data, the reason may be: the rule for loading the member variable is to load the member variable of the parent class first, and then load the member variable … -
How to use multiple functions on Jupyter Notebook as an api and call this api from Django?
I am making a movies prediction model in Jupyter Notebook and want to use this model in Django where I am making web application. But I don't know how to do it -
How to make the user pay for something online
I am making a bookstore website and I want the user to be able to pay for the books online with credit card or visa etc .. how to do this in django is there a library for this ?? -
Search everythings using django filter
I am trying to search everything related to Warnings table. I use django filter to search but no returned result. I also refer some code using django filter and follow them but nothing. How do I solve? Here are some code. filters.py import django_filters from .models import Warnings class WarningFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_expr='icontains') detail = django_filters.CharFilter(lookup_expr='icontains') type = django_filters.CharFilter(lookup_expr='icontains') website = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Warnings fields = ['title', 'detail', 'type', 'website'] views.py def search(request): if request.method == 'GET': query = request.GET.get('q') result = WarningFilter(query, queryset=Warnings.objects.all()) context = {'filters': result.qs} return render(request, 'pages/history_warning.html', context) models.py from django.db import models from django.contrib.auth.models import User import uuid class Website(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) uri = models.CharField(max_length=200) def __str__(self): return self.name class Warnings(models.Model): TYPE_WARNINGS = ( ('security', "Cảnh báo bảo mật"), ('service', "Cảnh báo dịch vụ") ) title = models.CharField(blank=True, null=True, max_length=255) detail = models.TextField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) type = models.CharField(choices=TYPE_WARNINGS, blank=True, null=True, max_length=255) website = models.ForeignKey(Website, on_delete=models.CASCADE) def __str__(self): return self.title -
How do I convert my Django app to use form validation correctly using Django forms?
I have an existing application that works as it exists. As of right now, I obtain data from a POST request, retrieve it one by one, and then perform some logic. Here is some of my existing code: last_name = request.POST.get('last_name') first_name = request.POST.get('first_name') mi = request.POST.get('mi') street_line1 = request.POST.get('street_line1') #sanitize if last_name == None: return HttpResponse("Invalid last name.", status=422) if first_name == None: return HttpResponse("Invalid first name.", status=422) if street_line1 == None: return HttpResponse("Invalid address line 1.", status=422) street_line2 = request.POST.get('street_line2') street_line3 = request.POST.get('street_line3') city = request.POST.get('city') # sanitize if city == None: return HttpResponse("Invalid city.", status=422) etc. For each field in my model, I pull it manually, then do some sanitization (which, for most of my fields, is simply making them required.) Once I pull all of my data, I grab some things from my JWT, and the primary key from my POST request, then I do some logic to determine if the primary key (surrogate_id) already exists. If it does, I update the data. If it does not, I create a new instance in the db. This happens like so: # Grab the pidm from the JWT user_pidm = Identity.objects.get(username=payload['username']).pidm # grab the surrogate_id sur_id = Contact.objects.filter(surrogate_id=surrogate_id) … -
Get lenght of searched output
I have a ListView in Django to return all users that match a keyword(username, first_name, last_name) from search bar on my page. Code looks like this class SearchView(ListView): model = User template_name = 'blog/list_of_users.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_name = self.request.GET.get('search', '') if len(user_name) < 1: context['all_search_results'] = False return context context['all_search_results'] = User.objects.filter(username__icontains=user_name ) or User.objects.filter(last_name__icontains=user_name ) or User.objects.filter(first_name__icontains=user_name ) return context And I'm showing in in template this way : {% if not all_search_results %} <div class="alert alert-danger"> No User </div> {% else %} {% for result in all_search_results %} {{ result.username }} etc..... And I would like to show length of matched result on my template. How should I change my code for that? -
How to authenticate a user in a unit test for the Django admin page?
I'm trying to adapt the answer from Testing custom admin actions in django, but I'm running into some unexpected behavior. I've created a simplified Django app, myapp, which has a Worker and Invoice model: class Worker(models.Model): name = models.CharField(max_length=255) class Invoice(models.Model): UNPAID = 0 PAID = 1 worker = models.ForeignKey( 'Worker', on_delete=models.CASCADE) amount = models.DecimalField( max_digits=10, decimal_places=2) amount_paid = models.DecimalField( max_digits=10, decimal_places=2, default=Decimal('0.00')) status = models.IntegerField( choices=[(UNPAID, 'Unpaid'), (PAID, 'Paid')], default=0) I've create a custom admin action called mark_as_paid which changes the status of the selected invoices to Invoice.PAID in admin.py: from django.contrib import admin from django.db.models import F from .models import Invoice @admin.register(Invoice) class InvoiceAdmin(admin.ModelAdmin): list_display = ('worker', 'status', 'amount', 'amount_paid') actions = ['mark_as_paid'] def mark_as_paid(self, request, queryset): queryset.update(amount_paid=F('amount')) I'm trying to test this like so: from decimal import Decimal from django.contrib import admin from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from myapp.models import Invoice, Worker class InvoiceAdminTests(TestCase): def setUp(self): self.user = User.objects.create_user( username='foobar', email='foo@bar.com', password='barbaz', is_superuser=True) self.client.force_login(user=self.user) def test_mark_as_paid(self): worker = Worker.objects.create(name="John Doe") invoice = Invoice.objects.create( worker=worker, amount=Decimal('100.00')) response = self.client.post( reverse('admin:myapp_invoice_changelist'), data={ 'action': 'mark_as_paid', admin.ACTION_CHECKBOX_NAME: [invoice.id]}) import ipdb; ipdb.set_trace() invoice.refresh_from_db() self.assertEqual(invoice.amount_paid, Decimal('100.00')) I've set a debugger trace in the test, but ultimately … -
Update model field based on edit form input django
I'm using tesseract to read in numbers in an image. I have a model with a boolean field that is dependent on the largest number found in the image. It's True if the largest number found is less than 90 and False otherwise. When the user submits the form, the boolean value is correctly updated (image_view). The problem is I created an edit form, and I'm trying to update the boolean value based on the new user input. I tried to define a function good_candidacy in the editPartView() that will update the boolean value if the user updates the dimension, but it currently does not work. views.py def image_view(request): if request.method == 'POST': form = partForm(request.POST, request.FILES) if form.is_valid(): image_file = request.FILES.get('image') text_content = pytesseract.image_to_string(Image.open(image_file)) Serial_number = request.POST.get('Serial_number') text_list = text_content.split() new_list = [] # ----- code for cleaning string and putting it into new_list... is_good_candidate = False if max(new_list) < 90: is_good_candidate = True x = Component(Serial_number = Serial_number, text=text_content, image=image_file, dimension1=max(new_list), Good_Candidate = is_good_candidate) x.save() return redirect('editPart', Serial_number) else: form = partForm() return render(request, 'home.html', {'form': form,}) class editPartView(UpdateView): model = Component form_class = editForm template_name = "edit_form.html" def good_candidacy(self, form): to_edit = get_object_or_404(Component,pk=self.kwargs['serial_number']) dimension1 = to_edit.dimension1 if … -
Why do I need to use asynchronous tools for sending Django email
While using Django, I had noticed when I send an email there is a delay and to overcome this I had to use Celery tool. So I wanted to know what is actually happening under the hood. Why does Django/Python need an async tool to accomplish this task. I have learned about MultiThreading, MultiProcessing in Python but if somebody could give me a brief idea about what exactly is happening when Django is trying to send an email without using Celery. -
How get a login token from Django after doing Google sign in on Android?
What I have: Django with Rest Framework (drfx), Allauth + socialaccount + Google provider setup on my local server. When I go to /accounts/google/login I can log in fine in my browser and I am returned to /accounts/google/login/callback like normal and I can use my account perfectly fine. On Android: My Google login is working fine. The app logs in with Google, creates an ID Token which I now have to send to my server. I have no idea how to connect to my server at all. What kind of request should I be making so I can get an authentication key? I know I'm supposed to be making a POST request with the ID Token but I have no idea how to send it. This is what Google suggests I do, I don't know what URL to send and what parameters/headers/etc. to POST. https://developers.google.com/identity/sign-in/android/backend-auth HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("https://yourbackend.example.com/tokensignin"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("idToken", idToken)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); final String responseBody = EntityUtils.toString(response.getEntity()); Log.i(TAG, "Signed in as: " + responseBody); } catch (ClientProtocolException e) { Log.e(TAG, "Error sending ID token to backend.", e); … -
Postgresql get updated by sql script, get notification in backend
I'm using django-rest-framework as backend and postgresql as the database. The database might be changed by raw SQL script and I want to get notified in the backend when those changes happen so that I can notify different users about the change. I've checked about posts like https://gist.github.com/pkese/2790749 for receiving notification in python and some SQL scripts for CREATE TRIGGER rec_notify_trig AFTER INSERT OR UPDATE OR DELETE ON rec FOR EACH ROW EXECUTE PROCEDURE rec_notify_func() My question is that I don't know how to hook them together in the django-rest-framework, like where should I put the SQL script, where to put the python settup so that I can connect them together. Any advice will be appreciated. -
How to remove the selection option from the admin panel
If an option has been selected once, how to remove the selection option from the admin panel admin.py class MyModelForm(forms.ModelForm): LOC = [('op1', 'op1'), ('op2', 'op2'),...] LI = [i.location for i in list(DataModel.objects.all())] X = [] for i, j in LOC: if i not in LI: X.append((i, j)) print(X) print(LI) location = forms.ChoiceField(choices=X) class DataModelAdmin(admin.ModelAdmin): form = MyModelForm list_display = ('location',) search_fields = ['location'] def get_ordering(self, request): return ['location'] admin.site.register(DataModel, DataModelAdmin) model.py class DataModel(models.Model): location = models.CharField(max_length=50, unique=True) def __str__(self): return self.location I try to do but it remove the option on restart the server -
Heroku Config Vars and Django
I want to make specific settings for each environment (local vs staging). I set up Config Vars in my heroku staging app and set DEBUG setting to false to try it out, but it didn't work. Am I missing something or making it wrong? My seetings.py file Config Vars in the staging app Result when I tried somthing wrong -
Using django-filter with class DetailView
I want to make a dynamic filtering form with Django and django-filter like stackoverflow filter and i want to use this filter on a template that render by DetailView , now the problem is i searched alot and i didn't found example of how to make this happen in my template i list all 'courses' that related to 'materials' class and i want to make a form on the same template so i can filter this list my template {% for course in material_detail.courses_set.all %} <div class="course"> <h5>{{ course.course_name }}</h5> <p>{{ course.course_description }} </p> </div> <hr/> {% endfor %} I have two models 'Materials' and 'Courses' my models.py class Materials(models.Model): materials_name = models.CharField(max_length=200) materials_description = models.CharField(max_length=200, null=True) slug_material = models.SlugField(blank=True, unique=True) class Courses(models.Model): course_name = models.CharField(max_length=200) course_description = models.CharField(max_length=300, null=True) material = models.ForeignKey(Materials, on_delete = models.CASCADE) and i have one Class DetailView my views.py class MaterialsDetailView(DetailView): model = Materials template_name = 'tuts/material.html' context_object_name = 'material_detail' I have made a filters.py file and make this code on it , but i don't know how to link this with my Class DetailView import django_filters from .models import Materials class CourseFilter(django_filters.FilterSet): class Meta: model = Materials fields = ['courses__course_name', 'courses__course_description'] Note: there are … -
How can I automatically test or check that the attributes used in __str__ exist in the class of my Django model?
In a Django 2.2 project, I renamed an attribute in a django.db.models.Model class. This attribute was used in __str__ but I forgot to rename it in the __str__ method of this class. I discovered this bug quite late, when testing something about this class in a Django shell. Is there a code testing app/framework/suite that could look for this kind of bug automatically? If not, how would a test checking that all attibutes used in __str__ actually exist in the class look like? -
Django sql query with None in field of WHERE clause not working
I am having issues when writing sql query for django. If the query is Books.objects.filter(id=1, name='ABC'), the sql query using django.db.connection would be: cur = connection.cursor() cur.execute('SELECT title FROM book WHERE id = %s AND name = %s',[id, name]) This works if there is a value in the name field but returns [] if name is None. So what should the equivalent be for Books.objects.filter(id=1, name=None)? What would be the query to accommodate both None and other values. cur = connection.cursor() for id, name in [(),(),()]: cur.execute('SELECT title FROM book WHERE id = %s AND name = %s',[id, name]) Expected result is the rows from the table but actual result is []. -
migrating problems when porting django project to python 3 and django 2
I've been porting a Django project to python 3 and Django 2. I have had to add on_delete to all my models with foreign keys as required in Django 2. Now I have tried to make migrations for those changes have been getting TypeError: __init__() missing 1 required positional argument: 'on_delete' the file it references is the 0002 migration file not the models file which has been updated. I am not sure how to go about fixing this. I have tried faking the migrations and I still get the same error. I am not sure why it thinks the database doesn't exist, I have checked and everything is intact and working in postgres. Any ideas? -
Django Forms - How to make a form inputs type equal to "date"
I am using a django form to create two inputs for date. When created in html the input types are set to type="text". How can I make theses be created with type="date". forms.py class searchForm(forms.Form): datestart = forms.DateField(label="Date Start") dateend = forms.DateField(label='Date end') views.py def search(request): if request.method == 'POST': form = searchForm(request.POST) if form.is_valid(): print(form) else: form = searchForm() return render(request, 'next_launch/search.html',{'form': form}) search.html <form action="search" method="post"> {% csrf_token %}} {{ form }} <input type="submit" value="Submit"> </form> -
Is there a way to integrate a Django application with a pre-existing Squarespace site?
I have a client who has a pre-made Squarespace site who has asked me to build polling and article pages as well as a user database. I did this using django, but am unsure if I can integrate the third party application with their site. I contacted squarespace, they told me they themselves do not provide support on third party applications. They pointed me towards forums to gather more information. Any information would help. -
URL rewriting with Django
The Problem I want to solve is the following: E.g. we have https://example.com/?id=e46Hd3cDe. But I want to make it look nicer so I want users to be able to go to this link: https://example.com/e46Hd3cDe and get the same HTML file returned. How could I achieve this in Django? If I would have to change something in the Apache config, how could I do that while testing Django locally? Currently, I test my Django website by calling python manage.py runserver and opening it at localhost:8000. -
custom reset page Django
I need some advice how to add posibility to reset password with phone number or username? my CustomUser: class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True) first_and_last_name = models.CharField(_('name'), max_length=50, blank=True) email = models.EmailField(_('email address'), unique=True, blank=True, null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(_('phone number'), validators=[phone_regex], max_length=17,unique=True, blank=True, null=True) my urls.py: urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), ] -
Running Django 2.2 with Tornado 6.0 as webserver with SSL
I am running Django 2.2 using Tornado 6.0 as a webserver. If I run the system in a port like 8080, everything works as intended. But when I try to run on port 443 (SSL/HTTPS) using the following code to start the server: import os import tornado.httpserver import tornado.ioloop import tornado.wsgi import tornado.web import sys import django.core.handlers.wsgi from django.core.wsgi import get_wsgi_application def main(): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'caf\\static\\') print(STATIC_ROOT) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "caf.settings") application = get_wsgi_application() container = tornado.wsgi.WSGIContainer(application) tornado_app = tornado.web.Application([ (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': STATIC_ROOT}), (r'.*', tornado.web.FallbackHandler, dict(fallback=container)),]) http_server = tornado.httpserver.HTTPServer(tornado_app) http_server.listen(443) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": main() and in Django's app settings.py the following line... SECURE_SSL_REDIRECT = True The server doesn't answer the request from the web browser. Any idea of why the server doesn't answer? -
How do I fix a 400 error when sending data that uses nested relationships?
I'm currently working on a Django app that uses Django REST Framework as the backend for API, and I keep getting 400 errors when I try and send JSON data to the server. I've ensured all the field names in the JSON file match up with the field names in my API, but beyond that I'm not sure what else to try other than the small edits I've been making to my code (such as setting die field on the DieMeasurement model to allow blank and null entries). Here's the script I'm using to send the data: def post_die_measurement(): with open('file.json') as obj: data = json.load(obj) requests.post(api_url_base + 'api-page/', data=data, headers={'Authorization': 'Token ' + api_token}) Here are the two relevant models associated with the data: class DieMeasurement(models.Model): # ... # fields # ... die = models.ForeignKey(Die, on_delete=models.CASCADE, blank=True, null=True) class Result(models.Model): # ... # fields # ... die_measurement = models.OneToOneField(DieMeasurement, on_delete=models.CASCADE, related_name='results') Here are my serializers for these models: class ResultSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = views.Result fields = ('set_v', 'dmm_value', 'actual_v', 'actual_a', 'time') class DieMeasurementSerializer(serializers.HyperlinkedModelSerializer): results = ResultSerializer(many=False) class Meta: model = views.DieMeasurement fields = ('notes', 'tap', 'dmm_mode', 'laser_power', 'timestamp', 'die', 'results') def create(self, validated_data): results_data = validated_data.pop('results') measurement = … -
NoReverseMatch at /cart/add-to-cart/1/ Reverse for 'single_product' with arguments not found. 1 pattern(s) tried: ['products/(?P<slug>.*)/$']
am having a function add_to_cart wanted to reverse redirect to product detail page rendered by single_product function which has slug for product id , cant get a way to solve it .getting this error Reverse for 'single_product' with arguments '('s', 'l', 'u', 'g')' not found. 1 pattern(s) tried: ['products/(?P.*)/$'] def add_to_cart(request,**kwargs): product = Product.objects.filter(id=kwargs.get('item_id', "")).first() # check if the user already owns this product ---------------- ------------- messages.info(request, "item added to cart") return redirect(reverse('products:single_product',args=('slug'))) url for product detail view url(r'^(?P<slug>.*)/$',single, name="single_product"), -
django.template.exceptions.TemplateDoesNotExist
I'm learning django, and I have a problem, I'm doing a virtual store and when I click on add a product to the shopping cart you should redirect me to another page, but can not find it, this is my code and my error: django.template.exceptions.TemplateDoesNotExist: productos/carritocompras_form.html detalle.html <div class="fixed-action-btn" style="bottom:90px;"> <form action="{% url 'aniadir_carrito' %}" method="post"> {% csrf_token %} <input type="hidden" name="usuario" value="{{request.user.pk}}"> <input type="hidden" name="produto" value="{{object.pk}}"> <input type="hidden" name="precio" value="{{object.precio}}"> <button class="btn-floating btn-large red pulse"> <i class="large material-icons">add_shopping_cart</i> </button> </form> </div> <div class="fixed-action-btn"> <a class="btn-floating btn-large red pulse"> <i class="large material-icons">add_shopping_cart</i> </a> <ul> </ul> </div>