Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model.field validators don't execute for required Boolean fields
My use case: I have a Yes/No question the user must answer, but they may answer it yes or no. I don't want to supply a default because I need the user to actively select their answer. If they do not select an answer, I want a form validation error, like "This field is required". I know that could store this in the DB as a CharField, but I'd prefer to store it as a required BooleanField. The issue appears to be that the form validation logic does NOT enforce required=True for Boolean fields, nor does it call the model field's custom validators when a value of '' is returned in the POST data. My setup: boolean_choices = ( (True, 'Yes'), (False, 'No'), ) def boolean_validator(value): if value is not True and value is not False: raise ValidationError("This field is required.") class Item(models.Model): accept = models.BooleanField( choices=boolean_choices, validators=[boolean_validator] ) class ItemForm(ModelForm): class Meta: model = Item fields = ['accept'] A complete, working demo of the issue is here: https://repl.it/@powderflask/django-model-form-validators Reproducing the issue create or edit an item, and set the 'accept' value to None ("-------") --> save will crash - notice form.is_valid() passed, crash is in form.save() --> notice that … -
Swal.fire opens unclicable modal (behind html body)
I'm currently having the following issue with Sweet Alerts 2: The modal is loaded, but it doesn't seems to be clickable I've investigated over the console and found two important things: first, it happens even if I run Swal.fire({}) on chrome console this behaviour is kept. I've tried to replace some codes on the source code, with no luck. Z-index seems to have no effect on this, and the target object that loads the div is not trivial. I'm doing this work on django, but the problem is not there so i'll ommit the django code. My html code on _base.html is: {% block styles %} <link href="{% static 'system/css/bootstrap.min.css' %}" rel="stylesheet"/> <link href="{% static 'system/css/material-dashboard.css' %}" rel="stylesheet"/> <link href="{% static 'system/css/sweetalert2.css' %}" rel="stylesheet"/> <link href="{% static 'system/css/jquery.datetimepicker.min.css' %}" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link crossorigin="anonymous" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" rel="stylesheet"> {% endblock %} {% block html5shim %} <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script> {% endblock %} {% block extra_scripts %} {% endblock %} {% block extra_head_base %} <script defer src="https://use.fontawesome.com/releases/v5.0.4/js/all.js"></script> <script src="{% static 'charts/code/highcharts.js' %}"></script> <script src="{% static 'charts/code/modules/exporting.js' %}"></script> <script src="{% static 'charts/code/modules/export-data.js' %}"></script> <script src="{% static 'system/js/jquery-3.2.1.min.js' %}"></script> <script src="{% static 'system/js/sweetalert2.js' %}"></script> {% block extra_head %}{% … -
Django FilterSet with distinct AND order_by
I want to use django-filter to create a FilerSet with distinct results for field A, ordered by field B (in another model). Database is PostgreSQL. Commented lines in class MinutesListView are things I've tried (in various configurations). models.py class Case(models.Model): case_filed_date = models.DateField() case_number = models.CharField(max_length=25, unique=True) as_of_timestamp = models.DateTimeField() def __str__(self): return self.case_number class Minutes(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE) minute_entry_text = models.TextField(blank=True, null=True) minute_entry_date = models.DateField(blank=True, null=True) minute_entry_type_text = models.CharField(max_length=255, blank=True, null=True) filters.py class MinuteFilterSet(df.FilterSet): case__case_number = df.CharFilter(lookup_expr='icontains', label='Case Number', distinct=True) minute_entry_text = df.CharFilter(lookup_expr='icontains', label='Minutes Text') class Meta: model = Minutes fields = ['minute_entry_text'] order_by = ['-case__case_filed_date'] views.py: class FilteredListView(ListView): filterset_class = None def get_queryset(self): # Get the queryset however you usually would. For example: queryset = super().get_queryset() # Then use the query parameters and the queryset to # instantiate a filterset and save it as an attribute # on the view instance for later. self.filterset = self.filterset_class(self.request.GET, queryset=queryset) # Return the filtered queryset return self.filterset.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Pass the filterset to the template - it provides the form. context['filterset'] = self.filterset return context class MinutesListView(FilteredListView): filterset_class = filters.MinuteFilterSet paginate_by = 25 # ordering = '-case__case_filed_date' # queryset = Minutes.objects.all() queryset = Minutes.objects.distinct('case') The … -
Django Rest Framework: User Not Updating with UpdateModelMixin
Using django-rest-framework and django-rest-auth, I have the following test case to ensure that a custom user's profile can be partially updated: def test_update_user_profile_first_name(self): client = APIClient() client.login(email=self.test_email, password=self.test_password) data = {"first_name": self.first_name} response = self.client.put("/users/" + self.user_id, data, follow=True, ) self.assertEqual(response.status_code, 200) self.assertEqual(self.test_user.first_name, self.first_name) client.logout() However, this test fails with test_user's first name still not updating. What mistake am I making here? Relevant files: # serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') # views.py class UserViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = User.objects.all() serializer_class = UserSerializer With my URLs following this pattern: users: { list() read(id) update(id, username, email, [first_name], [last_name]) partial_update(id, [username], [email], [first_name], [last_name]) delete(id) } -
How to Dynamically Compute Value in View and Display in Template (Django)
I want to dynamically pull values from two user input fields, a textbox and a dropdown, and then send those values to my view to calculate a new value and display said value in my template. This seems like a fairly simple scenario, but I am new to Django/Python. Any help is greatly appreciated! views.py def presales(request): my_opportunities = cwObj.get_opportunities() context = {'my_opportunities': my_opportunities} return render(request, 'website/presales.html', context) def presales_total(request): hours = request.GET.get('hours') engineer_level = request.GET.get('selected_engineer_level') if engineer_level == 'PM': wage = 225 elif engineer_level == 'Solutions Technician': wage = 175 elif engineer_level == 'Solutions Engineer': wage = 225 elif engineer_level == 'Senior Solutions Engineer': wage = 275 elif engineer_level == 'Solutions Architect': wage = 275 total = wage * hours context = {'total': total} return render(request, 'website/presales_total.html', context) presales.html <div class="field"> <div class="control"> <input class="input" name="hours" id="hours" placeholder="Hours"> </div> </div> <label class="label">Engineer Level:</label> <div class="field"> <div class="select"> <select name="selected_engineer_level" id="selected_engineer_level"> <option value="">Engineer Level</option> <option value="PM">PM</option> <option value="Solutions Technician">Solutions Technician</option> <option value="Solutions Engineer">Solutions Engineer</option> <option value="Senior Solutions Engineer">Senior Solutions Engineer</option> <option value="Solutions Architect">Solutions Architect</option> </select> </div> </div> </div> <div class="field"> <div class="control"> <button class="button is-info" type="button">Add Task</button> </div> </div> <span class="label is-medium is-pulled-right">Total: {{ total }}</span> presales_total.html Total: <span>{{ total … -
Error when making a POST Request in C# to Django REST API
I would like to make a POST Request to a Django REST API. My data (a Json string) lives in a C# application. I am using this snippet: var httpWebRequest = (HttpWebRequest)WebRequest.Create(myurl); httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"a\":\"sun\", \"b\":\"moon\"}"; streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); } Unfortunately, I am getting this error at the 'var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();' line : System.Net.WebException: 'The remote server returned an error: (405) Method Not Allowed.' I have also checked the logs of the Django API, it is Django that is throwing the 'Method Not Allowed' error. After doing some research, it looks like it is caused by the fact that POST is not allowed in my Django REST application. I have been able to issue GET requests with no problem. For this, in my django REST framework application, I use a retrieve() function inside my views.py file. I also happen to have a create() function in the same views.py file. I thought this function would be able to handle the POST request. However, it does not look like I am even able to get to … -
Returning empty queryset when used __startswith(or similar kind) while querying mogodb through parsepy
I am accessing mongodb through parsepy in my django application. I have a name field in my db collection. I'm tying to get those name fields which match my query string. For example, if I have these values--> food, folk, form, fill, filled, dust If I query fo I should get food, folk, form. If I query fi I should get fill, filled I found that CollectionName.Query.filter(name__startswith=query) could do that. But unfortunately that is giving me empty queryset. I tried it with CollectionName.Query.filter(name=ExactNameInDB) like CollectionName.Query.filter(name='food') and it returned me the collection object with that name. I even tried name__contains as keyword argument but that didn't work. This one is bugging me since a long time. Please help me. If you think that this explanation isn't enough, I can elaborate the context more. Thanks in advance :) -
Add task from web interface without restarting celery - django
I am trying to create network scanner, so my goal is to allow user that he can schedule network scan, which is repeated every 30 or 60 minutes depends on what user choice. Currently I am using celery 4.3 and rabbitmq and I can schedule task if I hardcode the time period when the scan will be repeated and network ip address. I would like to add new task to CELERY_BEAT_SCHEDULE when user enter the network ip and the time period in the web browser. Is it possible to add the task and if it possible do I need restart the celery to add new task? Here is my code: setting.py: CELERY_BROKER_URL = 'amqp://localhost' CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'scan_network.tasks.scan_network_periodically', 'schedule': crontab(minute='*/30'), 'args': ("192.168.0.0/24") } } celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'network_scanner.settings') app = Celery('network_scanner') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py @task() def scan_network_periodically(ip_addres): ... some logic to scan the network I will appreciate any advice how can I achieve my goal. -
Django filtered queryset in foreignkey lookup
I have a standard model with a foreignkey, in this case from biology: Seed to Taxon. The taxon model includes both Animal and Plant Taxon, and has a category column which is either zoology or botany When I add a new Seed I get the expected dropdown list, but it supplies the zoology and botany options. How do I filter it so only the botany options are shown? I'm assuming this filter can be applied somewhere in the model? I've tried adding .filter() and .exclude() but they do nothing here. class Taxon(models.Model): taxon_id = models.AutoField(primary_key=True) taxon = models.CharField(max_length=50, blank=True, null=True) common_name = models.CharField(max_length=50, blank=True, null=True) taxon = models.CharField(max_length=50, blank=False, null=False) genus = models.CharField(max_length=50, blank=True, null=True) category = models.CharField(max_length=50, blank=True, null=True) # family_name = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return str(self.taxon) class Meta(): managed=False db_table = 'kap\".\"taxon_manager' ordering = ["genus","taxon"] verbose_name_plural = "taxon" class Seed(models.Model): seed_id = models.AutoField(primary_key=True) fraction_id = models.ForeignKey(Fraction, db_column='fraction_id', blank=True, null=True, on_delete = models.PROTECT) taxon_id = models.ForeignKey(Taxon, db_column='taxon_id', blank=True, null=True, on_delete = models.PROTECT, related_name='seed_taxon') weight_type = models.CharField(max_length=50) weight = models.DecimalField(max_digits=10, decimal_places=3) quantity_type = models.CharField(max_length=50) quantity = models.IntegerField() def __str__(self): return str(self.taxon_id) class Meta(): managed=False db_table = 'kap\".\"seed' ordering = ["taxon_id","fraction_id"] verbose_name_plural = "seeds" -
How to get the info parameter which is sent to resolver in tests
I want to test test a function that checks if a field is requested by the query: def field_in_query(field, info): fragments = {} node = ast_to_dict(info.field_asts[0]) for name, value in info.fragments.items(): fragments[name] = ast_to_dict(value) while node.get('selection_set'): for leaf in node['selection_set']['selections']: if leaf['name']['value'] == field: return True else: node = fragments[leaf['name']['value']] if leaf['kind'] == 'FragmentSpread' else leaf return False but i don't know how to get the info parameter. Is there any way to do it? -
How can I add displaying image in my home page
Am creating a site where I want to post some information with image, in my admin page I can add image and it works fine. But when I come to the homepage it doesn't appear Am using django and python. I know, the way I have used to call the image in the home template is not right, please help me how would I bring the image in my home page?? url from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static app_name = "main" urlpatterns = [ path("", views.homepage,name="homepage"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Home template {% extends 'main/base.html' %} {% block content %} <a class="waves-effect waves-light btn" href="">button</a> <div class="row"> <div class="col s12 m9" > {% for Doc in documents %} <div class="card"> <div class="card-image"> <p>{{Doc.docs_name}}</p> <p>{{Doc.police_station}}</p> <p>{{Doc.docs_details}}</p> <img src = "{{Documents.docs_pic.url}}" width = "240"> </div> </div> {% endfor %} </div> </div> {% endblock %} views from django.shortcuts import render from django.http import HttpResponse from . models import Documents from main.models import Documents # Create your views here. def homepage(request): return render(request=request, template_name="main/home.html", context={"documents":Documents.objects.all} ) -
overwrite function with mock
Is it possible to overwrite functions behavior in class with mock? This is for python 3.6.8, django 2.2.2 views.py: YEAR_PATTERN = r"\(\d{4}\)\s*$" LOCKED_FROM_EXTERNAL_API = False class FetchFromExternalApi(APIView): @staticmethod def fetch_from_url(source): return urlopen('http://files.grouplens.org/datasets/movielens/%s.zip' % source, timeout=1) def post(self, request): global LOCKED_FROM_EXTERNAL_API, YEAR_PATTERN if LOCKED_FROM_EXTERNAL_API is False: LOCKED_FROM_EXTERNAL_API = True try: source = request.data['source'] except KeyError: LOCKED_FROM_EXTERNAL_API = False return Response('no source data in body', status=status.HTTP_400_BAD_REQUEST) if source in settings.AVAILABLE_SOURCES: try: response = self.fetch_from_url(request.data['source']) except URLError: LOCKED_FROM_EXTERNAL_API = False return Response("External server respond time out", status=status.HTTP_504_GATEWAY_TIMEOUT) I would like to write test that will overwrite behaviour of 'fetch_from_url' method, and fully simulate it. -
Django/PostgreSQL Full Text Search - Different search vectors when using SearchVector and SearchVectorField on AWS RDS PostgreSQL
I'm trying to use the Django SearchVectorField to support full text search. However, I'm getting different search results when I use the SearchVectorField vs. SearchVector on my AWS RDS PostgreSQL instance. Both perform the same on my laptop. Let me try to explain it with some code: # models.py class Tweet(models.Model): def __str__(self): return self.tweet_id tweet_id = models.CharField(max_length=25, unique=True) text = models.CharField(max_length=1000) text_search_vector = SearchVectorField(null=True, editable=False) class Meta: indexes = [GinIndex(fields=['text_search_vector'])] I've populated all rows with a search vector and have established a trigger on the database to keep the field up to date. I can't figure out why, but the search vector from the database looks different than the search vector that's generated using the SearchVector class. More importantly, it returns different results. # views.py query = SearchQuery('chance') vector = SearchVector('text') on_the_fly = Tweet.objects.annotate( rank=SearchRank(vector, query) ).filter( rank__gte=0.001 ) from_field = Tweet.objects.annotate( rank=SearchRank(F('text_search_vector'), query) ).filter( rank__gte=0.001 ) # len(on_the_fly) == 32 # len(from_field) == 0 The empty result prompted me to drop into the shell to debug. Here's some output from the shell using python manage.py shell: for tweet in qs: print(f'Doc text: {tweet.text}') print(f'From db: {tweet.text_search_vector}') print(f'From qs: {tweet.vector}\n') # Doc text: @Espngreeny Run your 3rd and long … -
How can I mock a function called from a dictionary?
test.py: @pytest.mark.django_db def test_b_called(mocker): b = mocker.patch('app.service.b') service.a('b') assert b.called service.py: def a(type): _actions[type]() def b(): pass _actions = { 'b': b } My test will fail as my patch does not work as I expected. What am I doing wrong here? This definitely works if a calls b directly and not using that dictionary. I have tested for this. -
API Root doesn't have has_permissions with JWT_Authentication
Trying to implement djangorestframework_simplejwt in accordance with DRF. After implementing everything based on: https://simpleisbetterthancomplex.com/tutorial/2018/12/19/how-to-use-jwt-authentication-with-django-rest-framework.html and when I'm logged in on localhost:8000, the API Root view is unavailable and the error is an attribute error. 'JWTAuthentication' object has no attribute 'has_permission' When I view the ModelViewSets themselves, they appear perfectly fine. It's just the API Root itself. When I logout and try to access the API Root, the page loads perfectly fine returning HTTP 403. Am I not supposed to access the API root when logged in or is there a loophole that I can implement (or extend) in views.py? -
How best to use multiple fields across multiple models?
Let's say I have these models and fields: class User(AbstractBaseUser): name_title name_first name_middle_initial name_last address_1 address_2 address_city address_state address_post_code class Order(models.Model): name_title name_first name_middle_initial name_last address_1 address_2 address_city address_state address_post_code class Shipment(models.Model): address_1 address_2 address_city address_state address_post_code Let's say, too, that none of these models are necessarily related -- an Order doesn't have to belong to a User, a Shipment doesn't have to belong to an Order, etc. I want all of the repeat fields to be identical -- to have the same verbose_name, validations, max_length, etc. I've tried taking a mixin approach: class AddressFieldsMixin(models.Model): address_1 address_2 address_city address_state address_post_code class NameFieldsMixin(models.Model): name_title name_first name_middle_initial name_last class User(AbstractBaseUser, AddressFieldsMixin, NameFieldsMixin): pass class Order(models.Model, AddressFieldsMixin, NameFieldsMixin): pass class Shipment(models.Model, AddressFieldsMixin): pass ...but this leads to model/inheritance collisions if my Mixin classes inherit from models.Model, and "unknown field" errors if they don't. What would be the correct way to re-use the 'name' fields and the 'address' fields across multiple models? Thanks! -
How to send password reset email from django using django-rest-framework and React
I'm creating a website in the backend i'm using (django,django-rest-framework) and frontend (React.js). I'm not clearly understand how do i create restfull api for password reset email. -
How can I pytest mock a function called from a dictionary?
test_service.py: @pytest.mark.django_db def test_some_other_function_called(mocker): cancel_showing = mocker.patch('app.service.some_other_function') service.some_function('some_other') assert some_other_function.called service.py: def some_function(type): _actions[type]() def some_other_function(): pass _actions = { 'some_other': some_other_function } My test will fail as my patch does not work as I expected. What am I doing wrong here? This definitely works if some_function calls some_other_function directly and not using that dictionary. I have tested for this. -
Cannot change URL of Django admin page
I am adding a second Django app to an Ubuntu Intranet application server. I am using Gunicorn/Nginx and both apps are available. However, I am running into problems with the admin pages. I should have changed the admin url for the second app before running it but I forgot, so both apps had the same admin URL. I changed the admin URL of the original app and it is now responding at it's new URL. I did the same for the new app but it was looking in the original app's urls.py so I added a location for it in NGINX/sites-available file. I saw strange behavior in the standard, Django URLconf "can't find URL" error page so I rebooted the server. Now strange behavior is gone, just a NGINX 502 Bad Gateway error. My NGINX set up must be wrong. How can I have admin sites for separate apps on two different URLs? urls.py (second app): urlpatterns = [ path('it-site-admin/', admin.site.urls), path('assets/', include('assets.urls')), path('', RedirectView.as_view(url='/assets/', permanent=True)), ] nginx/sites-available: server { listen 80; server_name server;; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { root /var/www/.....path to staticfiles; } location / { include proxy_params; proxy_pass http://unix:/var/www/.......path to original … -
Django - Invalid Model Reference, but the model is not referenced
I can't find the source of this error: ValueError: Invalid model reference '......Tickets.models.SeatingGroup'. String model references must be of the form 'app_label.ModelName'. This is appearing after moving these models to a new app and subsequently attempting makemigrations. I've commented out the only Model reference to the SeatingGroup() model, but I'm still getting the same error. I don't see any of my files in the trace. from django.contrib.gis.db import models from django.db import models from Otherlane.UserAuth.models import OLUser TICKET_FEE = .99 TICKET_RESERVATION_LENGTH_IN_MINUTES = 15 class SeatingGroup(models.Model): user = models.ForeignKey(OLUser, on_delete=models.CASCADE) name = models.CharField(max_length=128) seat_index = models.CharField(max_length=1024) qty = models.IntegerField() class Ticket(models.Model): seat = models.CharField(max_length=12) # section = models.ForeignKey(SeatingGroup, on_delete=models.PROTECT) price = models.FloatField() event_instance = models.ForeignKey('Events.EventInstance', on_delete=models.PROTECT) sold = models.BooleanField(default=False) owner = models.ForeignKey(OLUser, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return str(self.id) class TicketLock(models.Model): ticket = models.OneToOneField(Ticket, related_name='lock', on_delete=models.CASCADE) user = models.ForeignKey(OLUser, null=True, on_delete=models.CASCADE) session = models.CharField(max_length=32, blank=True, null=True) moment = models.DateTimeField() in_cart = models.BooleanField(default=False) This is the stack trace: (otherlane) C:\Projects\Otherlane>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Adam\Envs\otherlane\lib\site-packages\django\db\models\utils.py", line 11, in make_model_tuple app_label, model_name = model.split(".") ValueError: too many values to unpack (expected 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line … -
How to set the default selection of radio-button group on page load ( Django forms, ChoiceField )
Im trying to do a seemingly simple thing but cannot get this to work. Collection of fields in a Form class assinged ChoiceField class objects. The widget assigned to these ChoiceField is RadioSelect. choices attribute of these objects are assigned one list of value-text pairs. The form displays correctly and is hooked to the database, but I cant get the first radiobutton to be selected by default on page load. on page load there are no buttons selected. There were many questions that seem to be about an issue like this that people have, but none of the suggestions I read worked for me. Tried setting default attribute when the choice field is declared in the Form class, In the view that triggers when form-page url is entered (and handles the form submit), there is a IF ELSE condition that checks if request is 'POST' (or else). Im assuming the issue is at the else part. In the else-condition I have set initial attribute of the form object declared (with dictionary> declared_choicefield_attribute:'Unspecified' - the first default choice I need) In the pair I tried changing the 'Unspecified' to "-6" (-6 is the value of the radio button) and also the … -
Updating page elements immediately on input changes with django and AJAX inside GET request
I want to update elements in the page to tell a user in real-time how many objects will be affected by their choice of criteria in a form. For an example to work with, the form asks for a number and the django logic will delete any model instance with a pk less than that value once the submit button is clicked - but before clicking the user wants to know how many they will be deleting: <span id="number-changed">NULL</span> objects will be deleted so the end result I want is that #number-changed will be populated by a value like MyModel.objects.filter(pk__lt=input_number).count(). I have set up an AJAX call on changes to the input via: $("input").change( function() { $.ajax({ type: "GET", url: "{% url 'myapp:bulkdelete' %}", data: { csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, success: function (data) { // code to update #number-changed } I am wondering how I implement in the view so that on successful GET the success function can use the value I retrieve. Some pseudo-code: # views.py class MyView(FormView): # ... def get(self, request, *args, **kwargs): input_number = ??? number_changed = MyModel.objects.filter(pk__lt=input_number).count() # presumably some super().get() call here return ??? Questions: Can I retrieve the current input_number via request or does … -
Django how i choice from template fields for my json
I want in my template to make a select multiple in which I select what fields I want to contain my JSON. How can I do that? I don`t have for the moment any source code. First step I must to think. Any advices? -
How to deploy Django asgi project to Heroku?
When I try to deploy to Heroku the build succeeds but it fails to work. In the Heroku logs --tail I get: Process exited with status 127 bash: daphne: command not found I tried finding the Daphne install directory but couldn't. My Procfile contains: web: daphne chatapp.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 chatworker: python manage.py runworker -v2 In my settings.py for the CHANNEL_LAYERS I have: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 6379)], }, }, } In my asgi.py file I have: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chatapp.settings") django.setup() application = get_default_application() channel_layer = get_channel_layer() -
Django inline model: can I apply a different css to the header?
Django 2.2 I have inline mode which works fine as described here. Both main model and inline model are susing default Django templates, nothing is custom yet. I also have defined verbose_name_plural for it which shows as the header to the inline model table. My question is: is there a way to apply a css class to the header text class SomeForeignKeyInline(admin.TabularInline): model = SomeForeignKey verbose_name_plural = "My Header Text" #works css = "<some_css_class_I_want_to_apply_to_header_text>" I did not find anything reading this: Django docs on inline models Thanks