Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
url, path in urlpatterns Django is not working
path('',include('personal.urls')), ^ SyntaxError: invalid syntax I'm new to Django and when I run the server using "python manage.py runserver" for the following code I got this error. This is mypage code from django.contrib import admin from django.urls import include from django.conf.urls import url from django.urls import path #from django.conf.urls import url #from django.urls import path urlpatterns = [ url('admin/', admin.site.urls) path('',include('personal.urls')), ] This is the code of the new app that I'm trying to add, from django.urls import include from django.conf.urls import url from django.urls import path from . import views #import URLs urlpatterns = [ path('', views.index, name='index'), ] This is views.py code from django.shortcuts import render # Create your views here. def index(request): return render(request,'personal/home.html') -
Django Chartit - Display values of each model instance separately
I'm using django-chartit to display results of a survey as a stacked pivot chart. Each column is a question, in which each element of stack is one of the choices for this question. The structure of the models (omitted the vars I think are irrelevant to the question): Survey: <omitted> Question: survey = ForeignKey to a Survey question_text = CharField Choice: question = ForeignKey to a Question choice_text = CharField votes = IntegerField I spent some time with the chartit's tutorial and I'm starting to doubt whether this is at all possible without some trick or additional Model. Unfortunately, I'm very new to Django. This is the view containing the chart: class Results(CreateView): template_name = 'surveys/results.html' model = Survey form_class = ResearcherCreationForm def create_chart_data(self, survey): all_choices = Choice.objects.none() for question in survey.question_set.all(): all_choices |= question.choice_set.all() data = DataPool( series=[{ 'options': { 'source': all_choices, 'legend_by': 'choice_text' }, 'terms': [ 'choice_text', 'votes', 'question__question_text' ] }] ) return Chart( datasource=data, series_options=[{ 'options': { 'type': 'column', 'stacking': True, 'stack': 0, 'xAxis': 0, 'yAxis': 0 }, 'terms': { 'question__question_text': ['votes']} }]) def get(self, request, *args, **kwargs): self.object = None survey_id = self.kwargs.get('survey_id') survey = Survey.objects.get(pk=survey_id) cht = self.create_chart_data(survey) return self.render_to_response({'chart': cht}) So far I only … -
Django: reference context variable in an {% if %} block
I'm working on a Django project and editing a base template which the rest of the views inherit from. I have a context variable generally in this format: context = { 'metadata': { 'data1': value, # etc }, 'data': { 'value1': True, 'value2': False, # etc }, } I've been trying to add tags based on if the values in 'data' are true/false like so: {% if data.value1 is True %} {% load some_module %} {% endif %} {% if data.value2 is True %} {% load something_else %} {% endif %} My problem is that even if data.value1 is False the template tries to load the packages in that if block resulting in broken pages. I can't figure out where i'm going wrong. Can you not reference context variables like that? Am i just using the if block wrong? Is there a better way to do this? -
Django Pagination with Ajax
I am trying to display an HTML table that is dynamically updating every 3 seconds. With some help, I managed to get this part working, however, once the database grows big, Pagination will be needed. Django-Pagination is fairly straightforward, but I am having troubles getting it to work with the additional Ajax complexity. I looked at the related SO questions, but they were either very old, or they had no answers. The code: index.html {% extends 'app/base.html' %} {%load staticfiles %} {% block body_block %} <div class="container" > {% if elements %} <table id="_appendHere" class="table table-bordered"> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>User</th> <th>Date</th> </tr> {% for e in elements %} <tr> <td><a href="{{ e.A.url }}">{{e.A}}</a></td> <td><a href="{{ e.B.url }}">{{e.B}}</a></td> <td>{{ e.C }}</td> <td>{{ e.D }}</td> <td>{{ e.User }}</td> <td>{{ e.Date }}</td> </tr> {% endfor %} </table> {% else %} No data to display! <br/> {% endif %} </div> {% endblock %} <script> setInterval(function() { $.ajax({ type: "GET", url: "get_more_tables/", // URL to your view that serves new info }) .done(function(response) { $('#_appendHere').append(response); }); }, 1000) </script> views.py def paginate(input_list, request): page = request.GET.get('page', 1) paginator = Paginator(input_list, 10) elements = paginator.page(page) return {'elements': elements} def index(request): elements = ElementFile.objects.all().order_by('-upload_date') context_dict … -
Dynamic filter with Django in detail view
I have two models: rooms and holdings. Rooms is a list of rooms, and holdings is a list of things stored in those rooms. I would to have a detail page (with the generic DetailView) for each room, showing some information from the rooms model about that room and all the records in the holdings model that match that room. The first part was relatively easy, but I can't figure out how to filter the holdings and display the result on the detail page. Here's what I have so far: models.py class rooms(models.Model): room = models.CharField(primary_key=True, max_length=100, help_text='Room/storage area ID') location = models.CharField(max_length=100, help_text='Location', null=True) def __str__(self): return self.room def get_absolute_url(self): return reverse('room-detail', args=[str(self.room)]) class holdings(models.Model): id = models.IntegerField(primary_key=True) room = models.ForeignKey('rooms', on_delete=models.SET_NULL, null=True) contact = models.CharField(max_length=100, help_text='Contact', null=True) survey = models.ForeignKey('surveys', help_text='Survey ID, Cruise ID, FACS ID, or FAN', on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.room}, {self.contact}, {self.survey}' views.py class RoomDetailView(generic.DetailView): model = rooms def get_queryset(self): self.room = get_object_or_404(rooms, room=self.kwargs['room']) return holdings.objects.filter(room=self.room) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['room'] = self.room return context rooms_detail.html {% extends "base_generic.html" %} {% block content %} <h3>Room Detail </h3> <p></p> <p><strong>Room: </strong>{{ rooms.room }}</p> <p><strong>Location:</strong> {{ rooms.location }}</p> {% endblock %} That gives me … -
Dynamically populate ChoiceField Select within Form/Formwizard
First of all, I did my homework and tried finding a similar question :). I have been trying things out for the last couple of hours, but to no avail. What I'm trying to do seems very simple. I have several forms in a Formwizard. In the first form I have a text-input. In the next step I have a FormSet (but this could also be a simple Form) that contains a forms.Select (dropdown). I want to show the value of the text-input in this dropdown. However, I just can't get it to work. This is my code: In forms.py: class FirstForm(forms.Form): first_point = forms.CharField( widget=forms.TextInput( attrs={ 'class' : 'form-control' })) class SecondStepForm(forms.Form): dropdown_select = forms.ChoiceField( widget=forms.Select( attrs={'class' : 'form-control' })) SecondStepFormSet = formset_factory(SecondStepForm, extra=5) In views.py: FORMS = [("firstform", FirstForm), ("secondform", SecondStepFormSet)] class FormWizardView(LoginRequiredMixin, SessionWizardView): template_name = 'test.html' def get_context_data(self, form, **kwargs): context = super(FormWizardView, self).get_context_data(form=form, **kwargs) if self.steps.current == 'secondform': data = self.get_cleaned_data_for_step('firstform') print(data) context.update({'dropdown_select': data}) return context def done(self, form_list, **kwargs): return None And in my html-file: {% block content %} <div class="row"> <div class="col-md-12"> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} … -
common file to be translated for python program and a Django app
`I need to use a set of constants in both a Django application and a Python program. These constants includes string to translate. I defined these constants in a separate file named constants.py: E6000_Stitch_Tech_RANGES_TYPES = ( ('CO', _ ('Cast_On'), (1,15)), ('BA', _ ('basic point no grid pattern'), (100,122)), ('TK', _ ('Tuck stitch'),(129,175)), ) In my ptyhon program I import gettext and the '_' seems to be recognized. In my Django models I do : from django.utils.translation import gettext_lazy as _ from .constants import E6000_Stitch_Tech_RANGES_TYPES as RANGES_TYPES and I get the following error message : ('CO', _ ('Cast_On'), (1,15)), NameError: name '_' is not defined. Any solution? -
301 Moved Permanently in Django Rest Framework
I just created a new end-point in my Django Rest Framework project, and I get a 301 Moved Permanently error. It is a standard end-point: This is my model: class InvoiceEntryComponent(models.Model): invoice_entry = models.ForeignKey(InvoiceEntry, on_delete=models.PROTECT, related_name='components', verbose_name=_("Invoice Entry")) reservation_component = models.ForeignKey(ReservationComponent, on_delete=models.PROTECT, related_name='invoice_entries', verbose_name=_("Reservation Component")) rate = models.ForeignKey(Rate, null=True, blank=True, on_delete=models.PROTECT, related_name='invoice_entries', verbose_name=_("Rate")) markup = models.ForeignKey(MarkupSeason, null=True, blank=True, on_delete=models.PROTECT, related_name='invoice_entries_as_markup', verbose_name=_("Markup")) commission = models.ForeignKey(MarkupSeason, null=True, blank=True, on_delete=models.PROTECT, related_name='invoice_entries_as_commission', verbose_name=_("Commission")) class Meta: verbose_name = _("Invoice Entry Component") verbose_name_plural = _("Invoices Entries Components") def __str__(self): return "[{}] {}/{}/{}/{}".format(self.pk, self.invoice_entry.invoice.invoice_number, self.invoice_entry.id, self.reservation_component.reservation.booking, self.reservation_component.id) This is my serializer: class InvoiceEntryComponentSerializer(serializers.ModelSerializer): class Meta: model = models.InvoiceEntryComponent fields = ('id', 'invoice_entry', 'reservation_component', 'rate', 'markup', 'commission') This is my viewset: class InvoiceEntryComponentViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) queryset = models.InvoiceEntryComponent.objects.all() serializer_class = serializers.InvoiceEntryComponentSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,) search_fields = ('id', 'invoice_entry__invoice__invoice_number', 'reservation_component__reservation__booking') filter_fields = ('id', 'invoice_entry', 'reservation_component', 'rate', 'markup', 'commission') And this is my urls.py: from django.urls import path, include from rest_framework import routers from InvoicesManagerApp import views APP_NAME = 'InvoicesManagerApp' router = routers.DefaultRouter() router.register(r'entries_components', views.InvoiceEntryComponentViewSet) router.register(r'invoices', views.InvoiceViewSet) router.register(r'invoices_entries', views.InvoiceEntryViewSet) router.register(r'warnings', views.WarningViewSet) urlpatterns = [ path('', include(router.urls)), path('invoice_composition/', views.InvoiceCompositionViewSet.as_view({'get': 'list', 'post': 'create'})), path('create_invoices/<int:pk>/', views.CreateInvoicesViewSet.as_view({'get': 'list'})), path('get_invoice_number/', views.GetInvoiceNumberViewSet.as_view({'get': 'get'})), path('invoice_print/<int:pk>/', views.InvoicesPDFViewSet.as_view({'get': 'list'})), path('invoice_print_test/<int:pk>/', views.InvoicesJSONViewSet.as_view({'get': 'list'})), path('invoice_print_word/<int:pk>/', views.InvoiceWordViewSet.as_view({'get': 'list'})), path('invoice_print_word/', … -
Live search in Django with help of Ajax
I have a similar question to this: How do I jQuery ajax live search for the models in Django?. I want to create Live search in Django with help of Ajax, but it does not work for some reasone. In my project I have following information. In file locallibrary\catalog\urls.py urlpatterns += [ url(r'^search-user/$', views.SearchUser, name='search_user'), url(r'^search_status/$', views.search_status, name='search_status'), ] In file locallibrary\catalog\views.py def search_status(request): if request.method == "GET": search_text = request.GET.get('search_text', None) else: search_text = '' statuss = Trip.objects.filter(town__icontain=search_text) return render(request, 'search_user.html', {'statuss':statuss}) In file locallibrary\catalog\static\js\ajax.js $(function () { $('#search').keyup(function () { $.ajax({ type: "GET", url: "/catalog/search_status/", data: { 'search_text': $('#search').val(), 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data); } In file locallibrary\catalog\templates\catalog\search_user.html <!DOCTYPE html> <html> <head> <title>Простой живой поиск</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> </head> <body> <h3>Search</h3> {% csrf_token %} <input type="text" id="search" name="search" /> <ul id="search-results"> </ul> {% if statuss.count > 0 %} {% for status in statuss %} <li><a ">{{ status.town }}</a></li> {% endfor %} {% else %} <li>None to show!</li> {% endif %} {% load staticfiles %} <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script src="{% static 'js/ajax.js' %}"></script> </body> </html> When I try to print something an error occurs: FieldError at … -
unique constraints in django
I have a database in django that contains persons and roles. persons has a one-to-many relationship to roles. The problem is that roles doesn't have a unique constraint, for example person adam and david can be artists in roles but django creates two identical artists entries, but I want the same entry, i.e. adam and david should point to one entry. If I add unique to my role field than django says it should be one-to-one. Any ideas? part of model.py: from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. # possibillitas models here class Person(models.Model): mail=models.EmailField(default='yourname@gmail.com') firstName=models.CharField(max_length=200,default='firstname') lastName=models.CharField(max_length=200,default='lastname') phoneNumber=PhoneNumberField() streetAdress=models.CharField(max_length=200,default='streetAdress') zipcode=models.CharField(max_length=200) city=models.CharField(max_length=200,default='Göteborg') country=models.CharField(max_length=200,default='Sweden') def __str__(self): return "%s %s" % (self.firstName,self.lastName) class Meta: ordering = ('firstName','lastName') class Role(models.Model): role=models.CharField(max_length=200) # person=models.ManyToManyField(Person) person=models.ForeignKey(Person,on_delete=models.CASCADE) def __str__(self): return self.role class Meta: ordering = ('role',) class Name(models.Model): name=models.CharField(max_length=200) role=models.ForeignKey(Role,on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ('name',) -
Django Rest Framework: how to use DynamicFieldsModelSerializer for excluding serializer fields
I have a serializer that is used in a couple of endpoints (generics.ListAPIView), but in one of them I need to hide a serializer field. I would prefer to not write a new serializer just to cover this case. Starting from DRF 3.0 we have dynamic fields for serializers (https://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields), but I'm having some troubles to fully understand how to use them. I created this serializer: class TestSerializer(DynamicFieldsModelSerializer): user_req = UserSerializer(read_only=True) user_tar = UserSerializer(read_only=True) class Meta: model = TestAssoc fields = ("user_req", "user_tar") and this is my endpoint: class TestEndpointListAPIView(generics.ListAPIView): serializer_class = TestSerializer permission_classes = [IsAuthenticated] lookup_field = 'test_username' def get_queryset(self): return ... Now I need to hide the 'user_tar' field from the output, and according to the documentation I should instantiate the serializer with something like: TestSerializer(fields=('user_req')) but how should I do this inside my TestEndpointListAPIView? Should I override get_serializer_class? Thanks for the help -
install django bootstrap 3 for python 2.7 from source code
python 2.7, I cannot connect to the internet with pip but if I download the source file or a zip I can use pip install I want to install django-bootstrap3 here is the github page https://github.com/dyve/django-bootstrap3 which file will allow me to install it correctly? do I just download and stick it in my site-packages? please be nice -
server process that beats every second in Django
In my project, several users access the same page, and when the group is there, then a certain process on the server side needs to run and change a model field in the database every second. When they leave the page, the process must stop. I know that it's doable using Celery crontab function, but I wonder if there are more efficient or compact way of achieving the same result in Django? -
ListView is missing a QuerySet. Define ListView.model, ListView.queryset, or override ListView.get_queryset()
I don't really understand what causes the error i checked the documentations and there was a very similar example of this one here is my views.py, urls.py under my app i use include, and the template views.py class SchoolListView(ListView): context_object_name = 'schools' model = models.School urls.py from django.urls import path from . import views #My name space app_name = 'basicapp' urlpatterns = [ path('', views.ListView.as_view(), name='list'), path('details', views.DetailView.as_view(), name='details') ] and my template {% extends 'basicapp/basicapp_base.html'%} {% block body_block %} <div class="jumbotron"> <h1>Welcome to list of all schools</h1> <ol> {% for school in schools %} <h2><li><a href="{{school.id}}">{{school.name}}</a></li></h2> {% endfor %} </ol> {% endblock %} -
Django: TypeError when I attempt to create a new User object
I have a Contact model that is 1 to 1 with auth.User: class Contact(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) libid = models.CharField(max_length=100) library = models.CharField(max_length=100, null=True) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=15) lib_web_address = models.CharField(max_length=100, null=True) class Meta: ordering = ['user__email'] def __str__(self): return "{}".format(self.user.email) I'm attempting to first create the user, then create the contact object. However, when I attempt to create a user (either using the class constructor or the create method on the objects manager: from django.contrib.auth.models import User User.objects.create(username='test') ), I get: TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' I'm using Django 1.11 and Python 3.6. -
Passing a model's string parameter to URL with TemplateView
I am listing data from a search result matching the name parameter of my Model. For each result I have a link to the detail page with the key parameter (which is a string) passed in the url, Like this <ul> {% for x in results %} <li><a href = '/index/{{x.key}}'>{{x.name}}</a></li> {% endfor %} </ul> My url.py looks like this app_name = 'kpi' urlpatterns = [ path('login/index/search', views.SearchView.as_view(), name="search"), path('login/index/<slug:key>', views.EpicDetailView.as_view(), name="detail") ] And my views.py look like this: class SearchView(LoginRequiredMixin, TemplateView): template_name = 'KPI/search.html' def get(self, request, *args, **kwargs): self.q = request.GET.get('q','') self.results = Epic.objects.filter(name__icontains= self.q) return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(SearchView, self).get_context_data(**kwargs) context['results'] = self.results return context class EpicDetailView(LoginRequiredMixin, TemplateView): template_name = 'KPI/epic_detail.html' def get_context_data(self, **kwargs): context = super(EpicDetailView, self).get_context_data(**kwargs) context['lone_epic2'] = Epic.objects.get(key=self.kwargs['key']) I know I am missing a step here, probably how i created the url path, or needing logic in my views. The purpose is to be able to click on the search result, push the key to the url, and store that key value as a variable to use in the EpicDetailView page NOTE: Although I'm not showing it in the code above, my detail view will be displaying data from … -
How to use if statement inside a block in Django for image retrieval
I'm stuck. I have been trying to use all of my google fu to find this answer, but can't find it asked or answered anywhere. This is one of my first projects that I am trying to do not following a tutorial, so I apologize for my ignorance ahead of time. I am building my first blog and am trying to add a feature to display an image in the article. The problem is, I only want it to display if there is an image, as not all of them will have images. I can get the image to display, but if I go to an article without one, it gives me an error saying that it can't find the image. I thought I would try to do an if statement, but I am getting an error there as well and am not sure if I am doing the statement incorrectly (which is my guess) or not. #models.py from django.db import models from datetime import datetime # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) image = models.ImageField(upload_to='blog/', null=True, blank=True) def __str__(self): return self.title #view.py from django.shortcuts import render from django.http import … -
Is it possible to login user with URL parameter? (DJANGO)
I want to autologin the user by click with an URL with the format like: username:password@mysite.com or mysite.com/?username=""&password="" something like this. It would also work with an authentication token: mysite.com/AUTHTOKEN Has anyone an idea? -
Django object error needs to have a value for field "id" before this many-to-many relationship can be used
Tell me, I solved the problem correctly? Here is my solution in models.py class UserRoleMeta(models.Model): TYPEMETA = ( ... ('review', 'Отзывы'), ) parents = models.ManyToManyField("self", blank=True, related_name="parents_list") type = models.CharField(max_length=10, choices=TYPEMETA, default='cat', verbose_name='Тип мета') rating = models.DecimalField(...) def save(self, commit=False, *args, **kwargs): super().save(*args, **kwargs) self.save_m2m(*args, **kwargs) def save_m2m(self, *args, **kwargs): if self.type == 'review': for parent in self.parents.all(): rating = UserRoleMeta.objects.filter(parents=parent).aggregate(average=Avg('rating')) parent.rating = rating['average'] parent.save() super().save(*args, **kwargs) It works, but I am concerned about the correctness of the decision. Is there nothing extra here? -
Get Topojson from postgresql django
I already finish input and run all the geodjango code, it worked. But time after time my data got bigger and result in big size of geojson. I used this code to read database from postgresql (postgis) as geojson and view it in leaflet : def testcrud_datasets(request): testcrud = serialize('geojson', Testcrud.objects.all()) return HttpResponse(testcrud, content_type='json') some solution I read suggest that I should use topojson, how to get topojson format from my postgresql database since serialize does not support topojson type? -
In Django field with null=False, can set value to None?
I'm working in a project which uses the Django ORM, but doesn't use Django migrations and instead runs a venmo_tests.sql file to set up the venmo_tests MySQL database. The venmo_tests.sql database setup contains the following SQL commands: DROP TABLE IF EXISTS `compliance_user_identity_verification_info`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `compliance_user_identity_verification_info` ( `id` int(11) NOT NULL AUTO_INCREMENT, `legal_first_name` varchar(30) NOT NULL, `legal_last_name` varchar(30) NOT NULL, `date_of_birth` date NOT NULL, `external_paypal_user_id` varchar(255) NOT NULL DEFAULT '', `identification_type` varchar(32) NOT NULL, `user_id` int(11) NOT NULL, `datetime_created` datetime NOT NULL, `datetime_updated` datetime NOT NULL, PRIMARY KEY (`id`), KEY `user_id_ix` (`user_id`), KEY `datetime_created_ix` (`datetime_created`), KEY `date_of_birth_ix` (`date_of_birth`), KEY `external_paypal_user_id_ix` (`external_paypal_user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; Thus in particular, the date_of_birth field should be NOT NULL. The UserIdentityVerificationInfo model reads: from django.db import models from model.fields import MySQLDateTimeField class UserIdentityVerificationInfo(models.Model): NONCE_LENGTH = 16 NONCE_DELIMITER = ':' class Meta: db_table = 'compliance_user_identity_verification_info' app_label = 'compliance' legal_first_name = models.CharField(max_length=30) legal_last_name = models.CharField(max_length=30) date_of_birth = models.DateField() external_paypal_user_id = models.CharField(max_length=255) identification_type = models.CharField(max_length=32) user = models.ForeignKey('authentication.User', related_name='identity_verification_info') datetime_created = MySQLDateTimeField(auto_now_add=True) datetime_updated = MySQLDateTimeField(auto_now=True) which seems to me consistent with the way the compliance_user_identity_verification_info table is set up in venmo_tests.sql, because it leaves Field.null … -
Django Close Bootstrap Modal On Submit
When using Django with a Bootstrap Modal to submit a radio button choice, the modal does not want to close with the submission. It proceeds with the submission to the view in views.py but does not close. When changing the name so that it does not go to the view the modal does close. I have tried many of the suggestions from other posts including this one. main html <!DOCTYPE html> {% load static %} <html> <body> <div id="spacer"> </div> <div style="padding-left:20px;"> <button type = "button" class="btn" data-toggle="modal" data- target="#filetypeModal">Get Device Data</button> </div> <!-- File Type Modal --> <div class="modal fade" id="filetypeModal" tabindex="-1" role="dialog" aria-labelledby="filetypeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <form action="" method="post" id="getAPI"> {% csrf_token %} <div class="modal-header" style="background-color: darkblue; color: white"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true" style="color: white">&times;</button> <h4 class="modal-title" id="filetypeModalLabel">File Types</h4> </div> <div class="modal-body" style="text-align: center;"> Choose file type to download.<br> <br> <label class="radio-inline"><input type="radio" name="choices" value="Excel" checked>Excel</label> <label class="radio-inline"><input type="radio" name="choices" value="CSV">CSV</label> </div> <div class="modal-footer" style="background-color: darkblue;"> <button type="submit" class="btn btn-primary" value="OK" name="getAPIsubmit">OK</button> </div> </form> </div> </div> </div> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"> views.py def tasks(request): if request.POST.get('getAPIsubmit'): request.session['choice'] = request.POST.get("choices") response = INDget.indget(request) return response return render(request, 'tasks.html') -
multiple foreign keys to the same table but to different columns fetches models.object
i have two models which are truck and order and they have a relationship. from django.db import models from django.contrib.auth.models import User class Truck (models.Model): truck_number = models.CharField(max_length=200); condition = models.CharField(max_length=20); insurance = models.CharField(max_length=20); gps_tracking = models.CharField(max_length=20); owner_name = models.CharField(max_length=20); id_number = models.IntegerField(); telephone_number=models.IntegerField(); driver_name=models.CharField(max_length=30, default=None); driver_id_number=models.IntegerField(); driver_phone_number=models.IntegerField(); driving_license=models.CharField(max_length=20); good_conduct=models.CharField(max_length=30); def __str__(self): truck_number = self.truck_number return truck_number class Order(models.Model): truck_number= models.Foreignkey(Truck,related_name='relation_truck') date= models.DateField() product=models.CharField(max_length=30) depot = models.CharField(max_length=10) volume = models.CharField(max_length=30, blank=True) volume_delivered = models.CharField(max_length=30, blank=True) driver_name=models.ForeignKey(Truck, max_length=30,default=None) driver_id_number=models.ForeignKey(Truck, related_name='relation_id') driver_phone_number=models.ForeignKey(Truck, related_name='relation_tel') order_status = models.CharField(max_length=50, blank=True) def __str__(self): truck_number = self.truck_number return truck_number all the fields with foreign keys are fetching the whole object Truck but not the specific value of the foreign key. like i want truck_number in Order to fetch truck_number only from table Truck and not the whole Truck object. how can i get the foreign key values instead of the the whole object. -
IE 11 - Django based views issue
I have a Django app, and I'm using class-based views in some parts of it. When I try to access to these views on IE 11 it downloads the html instead of rendering it. I've searched the web and found this other posts talking about the same problem: https://www.reddit.com/r/django/comments/74r2af/django_not_working_with_internet_explorer/ Django: internet explorer download page content instead render it IE 11 Downloads Page instead of opening it, works in Chrome and Firefox According to this is some rendering issue caused by a wrong definition of the context, but my view looks like this: class BaseContentMixin(ActiveLoginRequiredMixin, TenantHasRolePermMixin, TenantActiveNotExpiredMixin, TenantHasPermMixin, SetDefaultTimezoneMixin): """ Attributes: content (str): content name, i.e 'training'. content_type (str): content type, 'shared' or 'custom'. permission (str): permission, i.e 'TRAININGS'. """ content = '' content_type = '' role_permission = 'SEE' permission = '' def get_content_class(self): return Util.get_content_class('{}-{}'.format(self.content, self.content_type)) def get_content_shared_class(self): return Util.get_content_class('{}-shared'.format(self.content)) class ContentListView(BaseContentMixin, TemplateView): def get_context_data(self, **kwargs): context = super(ContentListView, self).get_context_data(**kwargs) context['title'] = Util.get_content_title(self.content) context['active'] = self.content context['submenu_active'] = '{}_{}'.format(self.content, self.content_type) context['objects'] = self.get_content_class().objects.get_for_user(self.request.user) context['toggle_url'] = reverse('{}_{}_active_toggle'.format(self.content, self.content_type)) context['add_url'] = reverse('{}_{}_add'.format(self.content, self.content_type), kwargs={'lang': get_language()}) if self.content_type == 'custom': contents_shared = self.get_content_shared_class().objects.get_topics(self.request.user) context['form'] = Util.get_content_form_from_template(self.content)(contents_shared=contents_shared) context['add_url_from_template'] = reverse('{}_custom_add_from_template'.format(self.content), kwargs={'lang': get_language()}) return context When i print the context it gives me this: { … -
Getting the HTML ID of a ModelForm in Django Views
So I start with a list of objects X (dynamic size), and for each X object I create a row on my template with a form to post a different model Y. However, if/when a user decides to post a Y object, I want to then update X's foreign key to point to the newly created Y object. The problem is, I can't figure out a good way to retrieve X's id. My question is about one way I thought of, but I would love other suggestions: Each form for creating Y has an ID (ie, in HTML) that has the X id in it. Is there a way in my django view to do something like this: if request.method == 'POST': video_element_form = VideoElementForm(request.POST, request.FILES) if video_element_form.is_valid(): print('form id: ' + $(#video_element_form).id); so that I can parse the id out of it? I know this isn't ideal but it seems really hard and I don't want to change the infrastructure if I don't have to, its quite fleshed out and this is the only problem I think is present.