Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SuspisciousFileOperation
I'm trying to install saleor using wsgi on webfaction. When I try to reach my page I receive a 500 error, and the logs show: SuspiciousFileOperation at /en/ The joined path (/images/placeholder255x255.png) is located outside of the base path component (/home/<user>/lib/python3.6/versatileimagefield/static) Now this is of course the wrong base path component, but how can I fix that? -
Django Annotate Sum
I'm trying to get a simple sum for a column with several rows in a queryset. My direct question is (a) how do I set get_queryset() to include a sum of a column and (b) how do I access that element in a template? Following this question: #models.py class ItemPrice( models.Model ): price = models.DecimalField ( max_digits = 8, decimal_places=2 ) .... There are two answers provided - one using the .aggregate() method which I don't believe returns a queryset and .annotate() method which I believe appends an item to the queryset. So, I would have expected that the following would add another item to the object list in this view: #views.py def get_queryset(self): # generate table and filter down to a subquery. queryset = ItemPrice.objects.filter(<some_filter>) # sum the price for each row in the subquery. queryset = queryset.annotate(totals=Sum('price')) return queryset Then in the the Template, I would be able to iterate through the object list like this: #template.html {% for item in object_list %} {{ item }} {% endfor %} With the expectation that one of the items (the last item?) would be price_sum and that the balance could be accessed as price_sum.price. However, when i add the following … -
Django paypalrestsdk error - OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]
I am programming on Django and using paypalrestsdk https://github.com/paypal/PayPal-Python-SDK I am getting this error: OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')] Basically I have created BillingPlan(code snippet https://gist.github.com/axilaris/2f9cf8f5c27a8a2095c5c9abf0dc4121), and this appears: Payment created successfully 2018-05-08 22:44:45,358 INFO Request[POST]: https://api.sandbox.paypal.com/v1/oauth2/token 2018-05-08 22:44:45,358 DEBUG Level: sandbox 2018-05-08 22:44:45,358 DEBUG Request: Headers: {'Authorization': 'Basic QVZ2cEhjMExScXFkcEFQZy1QZm1DU19jVlFNYTV1V3lsaXpBMXRpMDRjcm4tZF9jbWdyVFF5N0ZQOVZOcnlfdXRZN0IwZk91cEJSQlluVzM6RUpIcV9GLWwxbmNJLTY3YmFLYmREcWRJMVMtcGNOWkxwWjdvX29mcG10eGQ4ZlVRM2drQTFQR1J5ZzBOZER6VDY1dE5URlY2Y29lWDVVdHM=', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'User-Agent': 'PayPalSDK/PayPal-Python-SDK 1.13.1 (requests 2.12.1; python 3.6.3; OpenSSL 1.0.2k 26 Jan 2017)', 'PayPal-Request-Id': 'b337cb66-b036-4a0a-9f70-aaa7011e73bb'} Body: grant_type=client_credentials 2018-05-08 22:44:45,362 DEBUG Starting new HTTPS connection (1): api.sandbox.paypal.com From cffi callback <function _verify_callback at 0x12972a268>: Traceback (most recent call last): File "/Users/some/Documents/project/somedotcom/somedotcomenv/lib/python3.6/site-packages/OpenSSL/SSL.py", line 313, in wrapper _lib.X509_up_ref(x509) ... File "/Users/some/Documents/project/somedotcom/somedotcomenv/lib/python3.6/site-packages/OpenSSL/_util.py", line 54, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')] more complete detail of the traces can be found here: https://gist.github.com/axilaris/c181aaaa8261add4240fb2d042bd1ffc How do I resolve this error ? Thanks. -
django extensions hide pre and post imports
When I run python manage.py shell_plus there are many pre and post imports there. How can I hide them(I want to use it but not to see it). I use python 3.4.3 and ipython 6.2.1 -
Change BooleanField value when now within time interval
I have a model: class Track(models.Model): act_time_start = models.DateField(null=True) act_time_finish = models.DateField(null=True) active = models.BooleanField(default=False) What is the best practice of making active = True when now is between act_time_start and act_time_finish? Thanks! -
City select on home page value to be passed on to view in Django
On Homepage , visitor need to select the City and based on City selection content on page need to be displayed like Rooms in Paris , PG in Paris and Cab Service in Paris . City select methos is implemented in Angular using onchange select . Need to pass this value to Django views, so in views i can write queryset to fetch data related to that city . -
Display (in Template) choice from Model - Django
I need to call to choice field in Models from Template. models.py: ... CAT = ( ("1", "1"), ("2", "2"), ) cat = models.CharField(max_length=2, choices=TYPE, default="") ... views.py: def cat(request): my_model = Model.objects.all() return render(...{'post': post}) template.html: {% for i in my_model%} {{ i.cat }} # This shows DUPLICATES if I have couple posts with same cat. I want to display uniques in choices (I am not interested in posts at all) {% endfor %} So how can I call to choices in model from template, without showing duplicates? P.S: Please, do not send me to: https://docs.djangoproject.com/en/2.0/ref/models/fields/#choices, there is nothing about what I ask :( Thank you in advance for help. -
how can i pass argument to celery task?
this is my celery task def task_a(arg1, arg2, arg3, arg4) and i call the task like following arg1 is list and arg2,3,4 is integer task_a.apply_async(arg1, arg2, arg3, arg4) and i got an error message File "/opt/envDjango/lib/python3.5/site-packages/celery/app/task.py", line 518, in apply_async check_arguments(*(args or ()), **(kwargs or {})) TypeError: functools.partial object argument after ** must be a mapping, not int how can i solve the problem?? i tried to make a dictionary and change argument position, they are all failed... -
UNABLE to load uWSGI plugin: dlopen(./python_plugin.so, 10): image not found
When I use uwsgi to connect the $ uwsgi --http :8000 --plugin python --module myProject.wsgi I get the bellow error: !!! UNABLE to load uWSGI plugin: dlopen(./python_plugin.so, 10): image not found !!! There are whole traceback: (venv) MacBook-Pro:myProject ldl$ uwsgi --http :8000 --plugin python --module myProject.wsgi !!! UNABLE to load uWSGI plugin: dlopen(./python_plugin.so, 10): image not found !!! *** Starting uWSGI 2.0.17 (64bit) on [Wed May 9 11:24:54 2018] *** compiled with version: 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2) on 09 May 2018 02:32:54 os: Darwin-16.7.0 Darwin Kernel Version 16.7.0: Mon Nov 13 21:56:25 PST 2017; root:xnu-3789.72.11~1/RELEASE_X86_64 nodename: MacBook-Pro.local machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 4 current working directory: /Users/sss/Desktop/QIYUN/Project/myProject detected binary path: /Users/sss/Desktop/myProject/Project/myProject/venv/bin/uwsgi *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 709 your memory page size is 4096 bytes detected max file descriptor number: 10240 lock engine: OSX spinlocks thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8000 fd 4 spawned uWSGI http 1 (pid: 5266) uwsgi socket 0 bound to TCP address 127.0.0.1:54904 (port auto-assigned) fd 3 Python version: 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) [GCC 4.2.1 … -
Django template not being passed form context
In my site, i am trying to create a template that automatically displays the form fields in my model, i am passing an instance of the form through in my view using a render, but the template isnt recognising the form, and not displaying any of the input fields views.py: def create_booking(request): if request.method == 'POST': form = BookingsForm(request.POST) form2 = BookingsFormRecurring(request.POST) if form.is_valid() and form2.is_valid(): booking = form.save() bookingRecurring = form2.save() return redirect("confirm") else: form = BookingsForm() form2 = BookingsFormRecurring() return render(request, 'makebooking.html', { 'form': form, 'form2': form2}) forms.py class BookingsForm(forms.ModelForm): studentUsername = 'test' startingDate = forms.DateInput() teacherID = forms.CharField(label = 'Select teacher', widget=forms.Select(choices=TeacherCHOICES)) startingTime = forms.CharField(label = 'Available starting times', widget=forms.Select(choices=TimeCHOICES)) lessonDuration = forms.CharField(label = 'For how long?', widget=forms.Select(choices=DURATION_CHOICES)) instrumentFocus = forms.CharField(label = 'Which instrument?', widget=forms.Select(choices=INSTRUMENTS_CHOICES)) class Meta: model = bookingsModel fields = ('teacherID', 'startingDate', 'startingTime', 'lessonDuration', 'instrumentFocus') widgets = { 'startingDate': DateInput() } class BookingsFormRecurring(forms.ModelForm): lessonRepeat = forms.CharField(label = "How often?", widget=forms.Select(choices=REPEATS_CHOICES), required=False) secondaryLessonDay = forms.CharField(label = "Secondary lesson day", widget=forms.Select(choices=LESSON_DAY_CHOICES), required=False) secondaryLessonTime = forms.CharField(label = "Secondary lesson time", widget=forms.Select(choices=TimeCHOICES), required=False) tertiaryLessonDay = forms.CharField(label = "Third lesson day", widget=forms.Select(choices=LESSON_DAY_CHOICES), required=False) tertiaryLessonTime = forms.CharField(label = "Third lesson time", widget=forms.Select(choices=TimeCHOICES), required=False) class Meta: model = bookingsModelRecurring fields = ('lessonRepeat', … -
Django enable the environment global
I am working in the environment when activate the ll_env me at me in ~/desktop/django/learning_log $ source ll_env/bin/activate (ll_env) me at me in ~/desktop/django/learning_log $ When change to the parent directory, it still is in the scope of the virtual environment: (ll_env) me at me in ~/desktop/django $ I assumed that ll_env might disappear when jump out of the directory where environment files lives How Django enable the environment global? -
Django Jquery: $image.cropper is not a function
I'm trying to add a crop section to an image upload. I'm working on converting this tutorial. I added materialie.js a one point and that is throwing things off. javascript this part works, more or less. when I click the button a box appears with an image. I can't click anything else though. $('.modal').modal({ dismissible: true }); $(function () { /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#id_file").change(function () { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#image").attr("src", e.target.result); $("#modalCrop").modal('open'); } reader.readAsDataURL(this.files[0]); } }); Now I get a picture that looks like this When I click the blue crop and upload button I get this console error. $image.cropper is not a function and this sources error var cropData = $image.cropper("getData"); Does anyone know why this is happening? Thanks in advance. Below is the rest of my code. This part doesn't work. {% block javascript %} /* SCRIPTS TO HANDLE THE CROPPER BOX */ var $image = $("#image"); var cropBoxData; var canvasData; $("#modalCrop").on("shown.bs.modal", function () { $image.cropper({ viewMode: 1, aspectRatio: 1/1, minCropBoxWidth: 300, minCropBoxHeight: 300, ready: function () { $image.cropper("setCanvasData", canvasData); $image.cropper("setCropBoxData", cropBoxData); } }); }).on("hidden.bs.modal", function () { cropBoxData … -
Bin a queryset using Django?
Let's say we have the following simplistic models: class Category(models.Model): name = models.CharField(max_length=264) def __str__(self): return self.name class Meta: verbose_name_plural = "categories" class Status(models.Model): name = models.CharField(max_length=264) def __str__(self): return self.name class Meta: verbose_name_plural = "status" class Product(models.Model): title = models.CharField(max_length=264) description = models.CharField(max_length=264) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10) status = models.ForeignKey(Status, on_delete=models.CASCADE) My aim is to get some statistics, like total products, total sales, average sales etc, based on which price bin each product belongs to. So, the price bins could be something like 0-100, 100-500, 500-1000, etc. I know how to use pandas to do something like that: Binning column with python pandas I am searching for a way to do this with the Django ORM. One of my thoughts is to convert the queryset into a list and apply a function to get the apropriate price bin and then do the statistics. Another thought which I am not sure how to impliment, is the same as the one above but just apply the bin function to the field in the queryset I am interested in. -
Whats of this line `eventlet.wsgi.server(eventlet.listen(('', 8000)), application)`'s function?
I set the bellow code in the wsgi.py,: eventlet.wsgi.server(eventlet.listen(('', 8000)), application) if I use the: python3 manage.py runserver 0.0.0.0:8001 it will ignore the 8001 port of python3 manage.py runserver 0.0.0.0:8001? because the logs are: $ python manage.py runserver 0.0.0.0:8001 Performing system checks... System check identified no issues (0 silenced). May 09, 2018 - 10:48:35 Django version 1.11.5, using settings 'Qiyun02.settings' Starting development server at http://0.0.0.0:8001/ Quit the server with CONTROL-C. (4516) wsgi starting up on http://0.0.0.0:8000 # you see this is using 8000 If this line settings: eventlet.wsgi.server(eventlet.listen(('', 8000)), application) ('', 8000) means : 0.0.0.0:8000? -
Django - How to setup dynamic templating within django
So I am having this major issue regarding the templating setup. I have a model that is created and attaches html, JS, and CSS files on upload to a corresponding folder with the model name. The user is able to upload these files (HTML,CSS,JS), and I need to be able to access the HTML file within this weird location. /template/app/app.html (the location where the view leads, which idc about) /media/uploads/modelName1/base.html ( I want to dynamically link each view with their corresponding model folder ) /media/uploads/modelName1/style.css /media/uploads/modelName1/base.js for the view I made it so the HTML file of the model is passed within the template and then I can use {% include %} but obv that can't work b.c the HTML included isn't even part of the template. If you have any suggestions on how to approach this problem, it would be much appreciated. -
How to take HTML user input and query it via Python & SQL?
Is there a way to take user input from HTML, and use python to run the input through to a SQL database? Does the input need to be parsed? I want the the user to be able to type in a store name, and for it to return relevant rows def search(): store_search = request.form.get("store") if request.method == "POST": if not store_search: return "please type in a store!" else: c = conn.cursor() c.execute("SELECT * FROM stores WHERE store_name= 'store_search'") rows = c.fetchall() for eachRow in rows: return row else: return render_template("search.html") HTML: {% extends "main_page.html" %} {% block title %} Search {% endblock %} {% block main %} <form action="{{ url_for('search') }}" method="post"> <fieldset> <div class="form-group"> <input autocomplete="off" autofocus class="form-control" name="store" placeholder="store" type="text"/> </div> <div class="form-group"> <button class="btn btn-default" type="submit">search</button> </div> <div class="page-header"> <h1>{{ store }}</h1> </div> </fieldset> </form> {% endblock %} -
Facebook Login / Graph API - getting started on localhost and http (not https)
I've been researching and going in circles for the past few hours. Help would be much appreciated. My setup: Mac OS Django 2.0.2 (I use python manage.py runserver to work on localhost) My app URL: http://localhost:8000/ Attempting to use Facebook Login / Facebook API to manage a page I am just trying to log in to set up an access token - following the Javascript SDK which seems a straightforward path to logging in. However, on the console I get this error: Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https:// This seems to be well documented but the answers I am reading seem old. As of now, the product "Facebook Login" has a setting called "Enforce HTTPS" which cannot be changed (it is a "Yes") for the app I just created and want to test. So obviously it makes sense that I cannot do this without a HTTPS domain, although some posts say otherwise. This brings me to researching on how to get a secure https://localhost setting but this seems complex, and I'm hoping there is something I missed so I can focus … -
Display URL in Lower Case in Django
My model has a category for a retailer--example - "Walmart" All of the retailers in my database have been entered with the first letter capitalized. I am trying to show a list of products by retailer on my site. My url looks like so: path('retailer-deals/<str:retailer>', deals_by_retailer, name='retailer'), and my view looks like this: def deals_by_retailer(request,retailer): retailer_deals = Deal.objects.filter(retailer__company=retailer).order_by('expired','-date_added') retailer = retailer return render(request, 'deals/deal_by_retailer.html', {'retailer_deals': retailer_deals, 'retailer': retailer}) So if i go to retailer-deals/walmart nothing shows up... but of course retailer-deals/Walmart works fine i might be being nitpicky--but i think it looks more professional with the lower case walmart and just in case someone goes to enter the uppercase version, i want to make sure it populates correctly I did see someone mention a (?i) for a similar problem, and i tried changing my path to this: path('(?i)retailer-deals/<str:retailer>', deals_by_retailer, name='retailer'), but that doesn't seem to work....and also, if i go to list the retailers with associated links--the generated url will still have the uppercase url.. -
Django NameError: name 'password_reset_done' is not defined
found some topics like this but they are older or not solved. Well, I'm following a youtube tutorial and I'm stuck in this part of it, I already know it's due the difference of version, I've gone to the docs and got some answers but still can't solve it by myself. I'll post what I think it's relevant but if you guys want another part of my code ask and I'll get it. the error as I said (on Traceback) is: NameError: name 'password_reset_done' is not defined On the tutorial he didn't done anything on views.py about this, he just added some imports on url.py that was deprecated so I fix that but the errors keeps the same... My accounts/urls.py: from django.urls import path from . import views from django.contrib.auth.views import ( login, logout, password_reset, PasswordResetDoneView, PasswordResetConfirmView, ) urlpatterns = [ path('', views.home), path('login/', login, {'template_name': 'contas/login.html'}), path('logout/', logout, {'template_name': 'contas/logout.html'}), path('register/', views.register, name='register'), path('perfil/', views.view_perfil, name='view_perfil'), path('perfil/edit/', views.edit_perfil, name='edit_perfil'), path('trocar-password/', views.trocar_password, name='trocar_password'), path('reset-password/', password_reset, name='reset_password'), path('reset-password/done/', password_reset_done, name='password_reset_done'), path('reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/', password_reset_confirm, name='password_reset_confirm'), ] just to add some more code. My views.py: from django.shortcuts import render, redirect, HttpResponse from contas.forms import ( RegistrationForm, EditPerfilForm, ) from django.contrib.auth.models import User from django.contrib.auth.forms … -
How to add cropper.js to a django project
I'm trying to follow the guide https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html I'm getting lost when he says "The jQuery utility to crop images in the Web browser can be downloaded here." I can see that you can get to the github from his link. I can then download it from github. Do I put 'jquery-cropper' in the same folder that my manage.py is in and add it to my settings.py's 'INSTALLED_APPS'? If that isn't the case I'm lost. I can't pip install it because it isn't a python package. Thoughts? -
Django Rest Framework update don't save changes
I have two models related through a one to one field, and I want to create a REST services that manages them both as they where one. The post works perfectly so far, and new instances are created in both models as they where one, but the put method just does nothing. It raises no error or anything, it just leaves the data unchanged. These are my models: class Company(models.Model): name = models.CharField(max_length=40) legal_name = models.CharField(max_length=100) url = models.URLField() address = models.TextField(max_length=400) def __str__(self): return "[{}]{}".format(self.id, self.name) class Hotel(models.Model): company = models.OneToOneField('Company', on_delete=models.CASCADE, primary_key=True) code = models.CharField(max_length=10) city = models.ForeignKey('City', on_delete=models.PROTECT, related_name='city_hotels') category = models.ForeignKey('HotelCategory', on_delete=models.PROTECT, related_name='category_hotels') capacity = models.IntegerField() position = models.DecimalField(max_digits=11, decimal_places=2, default=0.00) in_pickup = models.BooleanField(default=False) def __str__(self): return self.company.name This is my ViewSet: class HotelViewSet(viewsets.ModelViewSet): queryset = models.Hotel.objects.all() serializer_class = serializers.HotelSerializer These are my serializers: class CompanySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Company fields = ('id', 'name', 'legal_name', 'url', 'address') class HotelSerializer(serializers.HyperlinkedModelSerializer): company = CompanySerializer() class Meta: model = models.Hotel fields = ('company', 'code', 'city', 'category', 'capacity', 'position', 'in_pickup') def create(self, validated_data): company_data = validated_data.pop('company') new_company=models.Company.objects.create(**company_data) hotel = models.Hotel.objects.create(company=new_company, **validated_data) return hotel def update(self, instance, validated_data): company = models.Company( id=instance.company.id, name=instance.company.name, legal_name=instance.company.legal_name, url=instance.company.url, address=instance.company.address ) company.save() instance.save() return … -
Sticky footer not working with extended html in django?
Im working with django and im trying to put the a sticky footer but its not working. Im inserting the footer on the basic.html and it always gets on top of the content of the extended page like login.html. If I try to insert the footer on the extended files it starts working again but I dont want to replicate the footer code through all the pages. I presume that its because django loads the window size on basic.html first making the absolute positioning of the footer stay on top of the finished page (after rendering on login.html content). But if I try a normal paragraph after the code its works without a problem. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script> <script defer src="https://use.fontawesome.com/releases/v5.0.12/js/all.js" integrity="sha384-Voup2lBiiyZYkRto2XWqbzxHXwzcm4A5RfdfG6466bu5LqjwwrjXCMBQBLMWh7qR" crossorigin="anonymous"></script> <link rel = "stylesheet" type = "text/css" href = "{% static 'css/basic.css' %}" /> <link rel = "stylesheet" type = "text/css" href = "{% static 'css/register.css' %}" /> <link rel = "stylesheet" type = "text/css" href = "{% static 'css/main.css' %}" /> <link rel="stylesheet" href="{% static 'css/Projects-Clean.css' … -
How to get "data" rather than "results" with Django Rest Framework ReadOnlyModelViewSet?
I have read this question How to generate JSON-API data attribute vs results attribute in Django Rest Framework JSON API? but the accepted answer does not work for me plus I have a situation not covered there. I am using Django Rest Framework (3.5.3) to provide an API end point. That end point is based on class FruitTestReadOnlyViewSet(viewsets.ReadOnlyModelViewSet): queryset = Fruit.objects.all() serializer_class = FruitSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) The data returned from there is fine except that it has a "results" attribute rather than a "data" attribute. The question I mentioned above suggests you do this class FruitTestReadOnlyViewSet(viewsets.ReadOnlyModelViewSet): queryset = Fruit.objects.all() serializer_class = FruitSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) renderer_classes = (JSONRenderer,) parser_classes = (JSONParser,) but that makes no difference for me and in fact I already have global setting which I believe cover the render and parser aspects like this REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'PAGE_SIZE': 10, 'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler', 'DEFAULT_PAGINATION_CLASS': 'rest_framework_json_api.pagination.PageNumberPagination', 'DEFAULT_PARSER_CLASSES': ( 'rest_framework_json_api.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser' ), 'DEFAULT_RENDERER_CLASSES': ( 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', 'rest_framework_json_api.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata', } So I'm interested to know if someone out there has done this recently and how they did it ? BTW I have other API endpoints based on … -
What's the label for in `ModelForm`
I am building a web following the instruction. I didn't understand the labels attributes: class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text':''} The Topic in models.py does not specify labels attributes: class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) What's the labels for? -
Django Test related model is correct for relational fields
I’m trying to test that my onetoonefield is going to the right model. How exactly do you do that? I assume that it is the same for all the relational model fields? Model.py class PersonnelFile(models.Model): employee = models.OneToOneField( 'CustomerEmployeeName', on_delete=models.CASCADE, verbose_name='Employee Name', related_name='employee', ) CustomerEmployeeName is the linked model. I’m trying to test that I got the name correct. I wasn’t sure where you can access it. I have successfully tested the related_name.