Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django union of two querysets does not work with annotated value
I'm trying to do a union of two querysets with shared fields. This works: fields = ['id', 'date_trans', 'total', 'allocated', 'balance'] qs1 = Order.objects.values_list(*fields) qs2 = OnAccount.objects.values_list(*fields) return qs1.union(qs2) The Order model has a CharField called num_invoice which I'd like to include as a field in the union. This field doesn't exist in the OnAccount model so in order to include it in the values_list() I'm using an annotation. The annotation works fine but the union causes an error: django.db.utils.ProgrammingError: UNION types character varying and date cannot be matched Here's my annotation: from django.db.models import CharField, Values as V from django.db.models.functions import Concat fields = ['id', 'num_invoice', 'date_trans', 'total', 'allocated', 'balance'] qs1 = Order.objects.values_list(*fields) qs2 = ( OnAccount.objects .annotate(num_invoice=Concat(V('OA-'), 'id', output_field=CharField())) .values_list(*fields) ) return qs1.union(qs2) -
Adding extra fields to django InlineFormSet
Suppose I have 3 models: Chess Player Tournament Participation "Participation" is a junction table of two others. I use the following InlineFormSet in admin panel in order to show some fields from Participation model. from .models import Participation class ParticipationInline(admin.TabularInline): model = Participation formset = ParticipationAdminFormset class BaseParticipationAdminFormset(BaseInlineFormSet): def clean(self): # Some code # ... def _construct_form(self, i, **kwargs): # Some code # ... ParticipationAdminFormset = inlineformset_factory( Tournament, Participation, formset=BaseParticipationAdminFormset, fields="__all__" ) The Question: How can I include any fields from "Chess_Player" model, e.g. "first_name", into the FormSet above? -
Triggering POST request from django template
I am listing transfers from json response and viewing it in template: views.py def transfers_cft(request, host_id): hostname = Host.objects.get(pk=(host_id)) abc = "List idf or idt:" leave_empty = "(leave empty to list all | use * as string filler)" if request.method == 'POST': form = TransferForm(request.POST) if form.is_valid(): response = requests.get( 'https://{}:9999/api/transfers?fields=PART%2CIDF%2CIDT%2CIDTU%2C&limit=100'.format(hostname), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxx'}, ).json() arr = [] for key in response['transfers']: arr.append(key) context = {'response': response, 'hostname': hostname, 'host_id': host_id, 'arr': arr} return render(request, 'app/json_nest_transfer.html', context) else: form = TransferForm() context = {'form': form, 'abc': abc, 'leave_empty': leave_empty, 'hostname': hostname,'host_id': host_id} return render(request, 'app/message.html', context) json_nest_transfer.html [...] <div class="row m-2"> <div style="width: 100px;"><b>idf:</b></div> <div style="width: 100px;"><b>idtu:</b></div> {% if response %} {% for key in arr %} <div class="border w-100"></div> <div style="width: 100px;">{{ key.idf }}</div> <div style="width: 100px;">{{ key.idtu }}</div> {% endfor %} </div> <hr> {% else %} <p>No IDs are available.</p> {% endif %} [...] now, i would like to place near every <div style="width: 100px;">{{ key.idtu }}</div> "restart" button which would take key.idtu and execute following POST request: 'https://{}:9999/api/transfers/**key.idtu**/start'.format(hostname), verify='/cert/cacerts.pem', headers={'accept': 'application/json', 'authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxx'}, ) probably the best way would be to run new view somehow? but after click to end up with refreshed … -
css files are loading properly in django but no styling is visible on webpage
I have checked all the settings for django. CSS is loaded properly but no styling is visible on web page. I stopped the server and made changes and start it again, but it didn,t work.enter image description here -
'42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name django
I am trying to make access a table in my database but this error always occurs although a tried to access another table in the same schema and it worked PS: When I inspected the database a model of the table that I want was not created so I manually inspected it using python manage.py tableName --databse=DataAdmin > model.py it worked but the problem was not solved class Rfde2003Syd0827(models.Model): pe = models.CharField(db_column='PE', max_length=30, blank=True, null=True) # Field name made lowercase. pe_physical_interface = models.CharField(db_column='PE_PHYSICAL_INTERFACE', max_length=30, blank=True, null=True) # Field name made lowercase. pe_channel_interface = models.IntegerField(db_column='PE_CHANNEL_INTERFACE', blank=True, null=True) # Field name made lowercase. ts_usid = models.CharField(db_column='TS_USID', max_length=30, blank=True, null=True) # Field name made lowercase. ts_dna = models.IntegerField(db_column='TS_DNA', blank=True, null=True) # Field name made lowercase. new_pe = models.CharField(db_column='NEW_PE', max_length=30, blank=True, null=True) # Field name made lowercase. new_pe_physical_interface = models.CharField(db_column='NEW_PE_PHYSICAL_INTERFACE', max_length=30, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'RFDE2003SYD0827' -
Display image in dropdown list in django
I am bigenner to django ,I work on project that let user to rate countries in dropdown list, How I can display flag of each country in dropdown list of countries in django ? -
Dynamic linear interpolation between multiple HTML input field values with JavaScript
I'm trying to make a dynamically generated array of input fields where only the first and the last are editable. When either of the border fields are modified, the remaining should update their values by linearly interpolating between the two border values. Example below. I have written a (Django/Bootstrap) HTML template which generates the input fields themselves, and leaves only the border fields editable and assigns "-first" and "-last" id extensions. I have also written a basic JavaScript which takes two input values to interpolate between and output array size. This is how the input fields are instantiated. I started writing a JS function "change_values()" which would be activated on onchange event, but got nowhere. <div class="custom-control custom-linspace-field"> <div class="row" id="linspace-field"> {% for field in fields %} <div class="col p-1"> {% if forloop.first %} <input type="text" class="form-control" onchange="change_values()" id="linspace-field-first" value="{{ field | floatformat:3 }}" placeholder="min"> {% elif forloop.last %} <input type="text" class="form-control" onchange="change_values()" id="linspace-field-last" value="{{ field | floatformat:3 }}" placeholder="max"> {% else %} <input type="text" class="form-control" onchange="change_values()" id="linspace-field" value="{{ field | floatformat:3 }}" readonly> {% endif %} </div> {% endfor %} </div> </div> This is my linear interpolation JS script: function lerp(value1, value2, amount) { step = (value2 - value1) … -
DRF filter self foreign key
I have model as follows: class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) and I have to filter according to parent my view looks like this class CategoryView(generics.ListCreateAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer lookup_field = 'slug' name = 'category-list' filter_fields = ('name', 'parent_id') search_fields = ('^name',) ordering_fields = ('name',) as it can be seen from the view in filter_fields there is parent_id but it does not work if I select parent it returns nothing except [ ]. If I write get_queryset() def get_queryset(self): return Category.objects.filter( Q(parent_id=1) ) it returns objects whose id is 1. But I do not need to write id in numbers because in front end id can be in any number like 1, 2, 3, ... etc it should detect automatically that's why it should filter by id. Now I have no idea how to do it. Any idea please? Thanks in advance! -
TemplateDoesNotExist at / error, even though index.html exists in the stated folder
Following up on [https://realpython.com/location-based-app-with-geodjango-tutorial/] and implementing the nearby shops app. However getting a TemplateDoesNotExist at/, even though the file exists in the stated folder. Tried out solutions: Created subdirectory(templates) in the 'shops' app Changed DIRS in settings.py settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [''], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Also, Template postmortem states: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/username/sampleShops/nearbyshops/nearbyshops/shops (Source does not exist) django.template.loaders.app_directories.Loader: /home/username/.local/lib/python3.6/site-packages/django/contrib/admin/templates/nearbyshops/shops (Source does not exist) django.template.loaders.app_directories.Loader: /home/username/.local/lib/python3.6/site-packages/django/contrib/auth/templates/nearbyshops/shops (Source does not exist) django.template.loaders.app_directories.Loader: /home/username/.local/lib/python3.6/site-packages/django/contrib/gis/templates/nearbyshops/shops (Source does not exist) ` Moreso, I am not working in a virtual env(if that makes a difference, although it shouldn't) -
Accessing database table in Django view template
I expect this is a simple fix, but I've been unable to read objects from a SQLite database in my Django app in a particular instance. In /blog/views.py there are two functions defined, one to get all the instances of Article (index), and one to show some details of a particular Article (detail). detail is working as expected; i.e., I can navigate to localhost/xxxx/blog/1, and it will display the Article's title and description as expected. However, on the index page (which is routed to just localhost/xxxx/blog/), the object latest_article_list is not loaded, as "No articles are available" is displayed. The latter means that the routing is working, but it's just not reading Article.objects.all(). views.py from django.shortcuts import render, get_object_or_404 from .models import Article, Tags, Author def index(request): """ Will render templates/blog/index.html when called. This should show all articles. """ latest_article_list = Article.objects.all() return render(request, 'blog/index.html', {'latest_article_list': latest_article_list}) def detail(request, article_id): article = get_object_or_404(Article, pk=article_id) return render(request, 'blog/detail.html', {'article': article}) detail.html (working as expected, returns Article.title and Article.description for a given primary key) {% block content %} <br /> <h1> {{ article.title }} </h1> <p> {{ article.description }} </p> {% endblock %} index.html (not working as expected, if latest_article_list is evaluating … -
Work with selected data from a Select2 Remote Data dropdown
I have a select2 dropdown which loads remote data from a model in django. It loads correctly and now I want to work with the selected data. I want to add the selected query object to another db model. What's the best approach in this case? I did a lot of googling, but can't find any examples.. maybe I'm missing something? This is the current code: select2 box: <select class="js-data-ajax form-control"></select> jquery: $(document).ready(function(){ $(".js-data-ajax").select2({ tags: false, multiple: false, placeholder: "Select a product", // tokenSeparators: [',', ' '], minimumInputLength: 2, minimumResultsForSearch: 10, ajax: { url: '{% url 'inventory_json_data' %}', dataType: "json", type: "GET", params: { csrfmiddlewaretoken:'{{csrf_token}}', contentType: "application/json; charset=utf-8", }, data: function (params) { var queryParameters = { q: params.term } return queryParameters; }, processResults: function (data) { return { results: $.map(data, function (item) { return { text: item.product_name, id: item.pk } }) }; } } }); }); </script>``` -
Accessings fields directly in Django adminform template?
I have a ton of fields that I need to layout (reorder) in a specific way the form (with some other extra html stuff). I created change_form.html file for my model, which itself works. The problem is all examples are looping over the fields, I just want to refer to each field by name. # this works {% for fieldset in adminform %} {% for line in fieldset %} {% for field in line %} <p>{{ field.field }}</p> {% endfor %} {% endfor %} {% endfor %} I know you can customise the admin.ModelAdmin with fieldsets, etc.. But that's not what I want. I was trying different ways like below, but it doesn't work: # assuming the admin model has the fields: first_name & last_name {% block content %} <!-- doesn't work !!! -> {{ adminform.fieldsets.0.1.fields.first_name.field }} {{ adminform.fieldsets.0.1.fields.last_name.field }} <!-- neither does this --> {{ adminform.fields.first_name.field }} {{ adminform.fields.last_name.field }} {% endblock %} Now this doesn't work, is there any efficient way to directly access the fields I need? -
django url is loading in the console ,but the function in the view is not working
[26/Aug/2019 09:51:08] "GET /update HTTP/1.1" 200 32972 my basic url on the above and after ajax call below. [26/Aug/2019 09:51:11] "GET /updateline?client_response=true%20 HTTP/1.1" 200 32972 views.py def update_line(request): if request.method == 'GET': print("okey") #username = request.POST.get('username', None) label = ["INDIA", "PAK", "Europe", "Latin America", "North America"] data = json.dumps(label) return JsonResponse({"label":data}) jscript $("button").click(function(){ $.get( { url: '{% url "update_line" %}', //dataType: 'json', //method: "GET", data : { client_response : "true ", }, error: function(e){ alert('fail');}, success: function(data){ var dt =data.label alert(dt); addData(); }}); }); url.py urlpatterns = [ url(r'^$', views.HomePageView.as_view()),# views -Homepageview() url(r'chart', views.charts1,name='chart'), url(r'blank', views.blank_page,name='blank'), url(r'update', views.update_page,name='update'), url(r'updateline',views.update_line,name='update_line') #url(r'^$', views.HomePageView.as_view()), ] # -
How to update database in django using javascript
I want to update my django database using javascript. I searched a lot but i didn't get the relevant answer. Anyone help me to solve this problem class FriendList(models.Model): Friend = models.ForeignKey(SignUp,on_delete=models.CASCADE,default=None) Friend_name = models.CharField(max_length=30,default=None,blank=True) Status = models.CharField(max_length=20,default=None,blank=True,null=True) This is my model and I want to update Status field as either accepted or rejected when button is clicked. -
How to use next_page in Django URL path
I have two URL class views from django.contrib.auth: path('login/', auth_views.LoginView.as_view( template_name='accounts/login/login.html'), name='my_login'), path('logout/', auth_views.LogoutView.as_view( template_name='accounts/logout/logout.html', next_page=XXXX), name='my_logout'), What's the correct syntax to pass to next_page in the LogoutView? E.g.: next_page='accounts/login/' next_page='accounts/login/login.html' next_page=my_login next_page='my_login' next_page=reverse_lazy('my_login') -
update jsonfields in django model formsets with mongdb
I'm trying to create an editable bootstrap table where each cell represents a json value. I've defined a Django Model with this JSONField (not the Postgres's one) This is my Model: class Extracted_Tables(models.Model): ... content = JSONField(blank=True, null=True) My Template <tbody> {% for form in formset.forms %} <tr> {% for field in form %} {% if field.is_hidden %} <input type="hidden" >{{ field }}</input> {% else %} {% for k,v in field.value.items %} <td>{{v}}</td> {% endfor %} {% endif %} {% endfor %} </tr> {% endfor %} </tbody> This template renders the following HTML <tr> <td>Jamaica</td> <td>Kingston</td> <td>North America</td> <td>11424</td> <td>2500000</td> <input type="hidden"><input type="hidden" name="formset_1-0-id" value="353" id="id_formset_1-0-id"> </tr> To have a better idea on why it's not working: I've used a Django Model where my cells were this model's attributes. I had no problem editing the cells in this case as I was editing the model's fields This time, my cells are not the model's fields themselves: the only model field I have is a JSONField and I'm trying to edit the cells that are that json's values. Model: class Extracted_Variables(models.Model): variables = models.CharField(max_length=500) values = models.CharField(max_length=500) The Template: <tbody> {% for form in formset.forms %} <tr> {% for field in … -
How to force subquery in Django-ORM?
I have the following table: > select * from request_tripinterval order by id +-----+----------------------------+-------+------+-----------+---------+ | id | timestamp | path | time | params_id | trip_id | +-----+----------------------------+-------+------+-----------+---------+ | 411 | 2019-08-25 21:09:18.193870 | 47.0 | 67.0 | 1 | 1 | | 412 | 2019-08-25 21:09:18.311034 | 99.0 | 67.0 | 1 | 1 | | 413 | 2019-08-25 21:09:18.436022 | 66.0 | 67.0 | 1 | 1 | | 414 | 2019-08-25 21:09:18.544529 | 44.0 | 67.0 | 1 | 1 | | 415 | 2019-08-25 21:09:18.636328 | 16.0 | 67.0 | 1 | 1 | | 416 | 2019-08-25 21:09:18.728114 | 18.0 | 67.0 | 1 | 1 | | 417 | 2019-08-25 21:09:18.802324 | 52.0 | 67.0 | 1 | 1 | | 418 | 2019-08-25 21:09:18.886299 | 92.0 | 52.0 | 1 | 1 | | 419 | 2019-08-25 21:09:18.977108 | 13.0 | 52.0 | 1 | 1 | | 420 | 2019-08-25 21:09:19.059118 | 5.0 | 26.0 | 1 | 1 | | 421 | 2019-08-25 21:09:19.134312 | 91.0 | 26.0 | 1 | 1 | | 422 | 2019-08-25 21:09:19.209511 | 75.0 | 87.0 | 1 | 1 | | 423 | 2019-08-25 … -
Does success_url in PasswordChangeView override PasswordChangeDoneView?
When using PasswordChangeView in Django auth: path('password_change/', auth_views.PasswordChangeView.as_view( template_name='accounts/password_change.html', success_url='accounts/password_change_success.html'), name='password_change'), Does the success_url override the PasswordChangeDoneView, as it does when success_url is passed in PasswordResetView and overrides PasswordResetDoneView? From the docs: PasswordResetDoneView This view is called by default if the PasswordResetView doesn’t have an explicit success_url URL set. The docs are silent on the behaviour between success_url in PasswordChangeView and PasswordChangeDoneView. -
Unable to filter, order and search the data for nested endpoints API
My API endpoint is http://127.0.0.1:7009/apps/2/versions I am unable to filter, order and search the particular version data models.py: class App(models.Model): app_id = models.CharField(max_length=40,help_text="app_id of the app",unique=True) name=models.CharField(max_length=40,help_text="name of the app") class AppVersion(models.Model): app_version = models.CharField(max_length=200) app_description = models.CharField(max_length=200,blank=True) Views.py : from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter,SearchFilter class AppVersionListView(mixins.ListModelMixin,mixins.CreateModelMixin,generics.GenericAPIView): lookup_field = 'pk' serializer_class = appVersionsSerializer queryset = AppVersion.objects.all() filter_backends = (DjangoFilterBackend, OrderingFilter,SearchFilter,) filter_fields = ('id','app_version','app_description ') ordering_fields = '__all__' search_fields =('app_version','app_description ') I want to filter the versions data based on "app_description" i.e., GET: http://127.0.0.1:7009/apps/2/versions?app_description =FileCommander Expected Output : Should filter the data and return results which is having that description [ { "apps": 2, "app_version": "v1", "app_description ":"FileCommander" }] Actual Output : [ { "apps": 2, "app_version": "v1", "app_description ":"FileCommander" }, { "apps": 2, "app_version": "v2", "app_description ":"cooking" }] How can I search , filter or order the versions data? -
Django's __ notation
Can anyone describe Django's __ notation. I didn't see any description in Django's documentation or in the internet. When I use this notations I heavily rely on ide's suggestion and intuition is it normal? -
How to fix " AttributeError at /api/doc 'AutoSchema' object has no attribute 'get_link' " error in Django
We are practicing an example of REST API on the Internet. However, the following error occurred. I tried a way in this link, but the situation hasn't changed. why swagger raises unclear error - Django from django.contrib import admin from django.conf.urls import url, include from rest_framework import routers from rest_framework_swagger.views import get_swagger_view import consumer.api app_name = 'consumer' router = routers.DefaultRouter() router.register('consumers', consumer.api.ConsumerViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/doc', get_swagger_view(title='Rest API Document')), url(r'^api/v1/', include((router.urls, 'consumer'), namespace='api')), ] Exception Type: AttributeError at /api/doc Exception Value: 'AutoSchema' object has no attribute 'get_link' -
django, celery : create worker per user basis
Does it make sense (or not at all) to create a worker for each user logged in the website ? The idea came as a user may have some long tasks to execute but must be allowed to cancel them at will. And as there is no warranty that any task stops when it's asked with : revoke(task_id, terminate=True) according to the docs, even with abortable tasks (which does not allow to abort by task_id, with the risk also to terminate the worker. So, to prevent that unknown outcome, I thought of that solution which allows fine control on task execution without risk. Any advice is welcomed, thanks. -
Django allauth login/logout error: is_safe_url() missing 1 required positional argument 'allowed_hosts'
I'v implemented django-allauth on my local website for handling register/login/... things but i keep getting this error when try to login or logout: TypeError at /accounts/login/ is_safe_url() missing 1 required positional argument: 'allowed_hosts' my urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('allauth.urls')), ] all settings mentioned in here have been implied. -
Django 2: upload media to Google Cloud Storage with google-cloud-storage
I want to deploy Django app on Google Cloud (Google AppEngine and Cloud Sql). SO I need to store media files in Google CLoud Storage. I found this code in google docs: from google.cloud import storage client = storage.Client() # https://console.cloud.google.com/storage/browser/[bucket-id]/ bucket = client.get_bucket('bucket-id-here') # Then do other things... blob = bucket.get_blob('remote/path/to/file.txt') print(blob.download_as_string()) blob.upload_from_string('New contents!') blob2 = bucket.blob('remote/path/storage.txt') blob2.upload_from_filename(filename='/local/path.txt') I think I can use this in the views (for a FileField and an ImageField). But what should I do in my Django settings with MEDIA_ROOT in this case? -
Error encountered when generating numbers in series
In every post that will be posted by user, I want number to be generated from Integer field in series. I have encountered the error named "TypeError: unsupported operand type(s) for +: 'dict' and 'int'" How would I get rid off this error? views.py @login_required def Claim(request): max_val = Documents.objects.all().aggregate(Max('pay_no')) # then just make new object, and assign max+1 to 'that_field_in_question' control_number = Documents(pay_no=max_val + 1) control_number.save() return render(request,"loststuffapp/claim.html",context={"documents":Documents.objects.all()})