Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Formatting and incrementing a Django form in HTML
OK so I have a running form in Django that updates the model and displays this on the page, but I was hoping to better format it. What happens is that the page displays all data imputed in the form. What I want to do is to numerically list it. This is what I have in my home.html right now: {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Home</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% for post in posts %} <h2>Object:{{ post.post }}</h2> {% endfor %} </div> {% endblock %} So say I have data "a", "b", and "c". It would display itself as Object: a Object: b Object: c If I added d to the form, it would add Object: d What I'm hoping to do is add an increment to this so it displays itself as Object 1: a Object 2: b Object 3: c And add d as Object 4: How would I go about implementing this? Another thing I wanted to know is whether I can change the "Post:" comment next to the form. Right now my form displays itself with "Post:" at the left side. Is there … -
Django Building A Restful API
I want to build a Django Api App that allows me to render multiple variations of data. For example take a look at my code: urlpatterns = [ url(r'nav-func$', views.FundNavApi.as_view(option='nav_func')), url(r'fund_nav/(?P<fund_id>[0-9]+)$', views.FundNavApi.as_view(option='fund_nav')) ] Views.py class FundNavApi(APIView): option = 'default' model_class = NAV fund_id = None def get(self, request, format=None): if self.option == 'nav_func': res = self.nav_func print(res) elif self.option == 'fund_nav': print(self.kwargs['fund_id']) return Response("Hi") @staticmethod def nav_func(): querysets = NAV.objects.filter(fund__account_class=0, transmission=3).values( 'valuation_period_end_date').annotate( total_nav=Sum(F('outstanding_shares_par') * F('nav'))).order_by('valuation_period_end_date') df = read_frame(querysets, coerce_float=True) df.loc[:, 'valuation_period_end_date'] = pd.to_datetime(df.valuation_period_end_date) df.loc[:, 'timestamp'] = df.valuation_period_end_date.astype(np.int64) // 10 ** 6 df.loc[:, 'total_nav'] = df.total_nav df = df.round(0) print(df[['timestamp', 'total_nav']].values.tolist()) return df[['timestamp', 'total_nav']].values.tolist() As you can see, I want to use the same model but manipulate the data differently based on the url. So, I use the option='' parameter as a way to tell the controller what to render. So I have two questions: The nav_func function doesn't seemed to be called when res = self.nav_func is being run. The print statement isn't displaying anything. Is this the correct approach? Like is this what professionals do in terms of building an API that renders different variations of data while using one type of model? -
Django: display multiple objects on a single page
I have a lot of data from my fantasy basketball league displayed at index.html When I click a player name, I am taken to that player's single season's statistics. What I want to happen, when I click a player name, is for all of that player's career statistics to show up, not just a single year. What's the best method for going about doing that? I've been stuck on this for about two weeks now, lol Note: each 'player' object contains a separate "game_id" that belongs to each real-life player (e.g. each player object in this list of Aaron Brooks objects has the same "game_id"), but I haven't been able to figure out how to use it yet! Thanks in advance! Views.py: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'players_list' def get_queryset(self): return Player.objects.order_by('full_name', 'season', 'team', '-ppg', 'full_name') class PlayerView(generic.DetailView): model = Player template_name = 'polls/player.html' Models.py: class Player(models.Model): def __str__(self): return self.full_name first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') full_name = models.CharField(max_length=200, default='') nba_live_id = models.IntegerField(default=0) season = models.CharField(max_length=4, default='') team = models.CharField(max_length=3, default='') pos = models.CharField(max_length=2, default='') gp = models.IntegerField(default=0) gs = models.IntegerField(default=0) ppg = models.FloatField(default=0) rpg = models.FloatField(default=0) apg = models.FloatField(default=0) spg = models.FloatField(default=0) bpg = … -
Django simple Post request is not working
I am new to Django and trying to build a simple web page. I am trying for post request but there no values getting inserted into the database.I hope the problem should be in views.py forms.is_valid() Since no logs are recorded after this line.Please assist model.py from django.db import models from django.contrib.auth.models import User from django.db.models import Q from django.forms import ModelForm from django import forms # Create your models here. class aws_cred(models.Model): aws_access_user_id = models.ForeignKey(User,null=False,related_name="aws_acc_user") access_key = models.CharField(max_length=300) secret_key = models.CharField(max_length=300) class aws(ModelForm): class Meta: model = aws_cred fields = ['access_key','secret_key','aws_access_user_id'] views.py from django.shortcuts import render_to_response,HttpResponseRedirect,render,redirect,reverse from django.contrib.auth.decorators import login_required from django.template import RequestContext from s3comp.models import aws_cred,aws import logging @login_required def fileinput(req): logging.basicConfig(filename='log_filename.txt',level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') if req.method == 'POST': form = aws(req.POST) logging.debug(form) try: logging.debug('step 4') if form.is_valid(): logging.debug('step 5') access_key_val = req.POST.get('access key','') secret_key_val = req.POST.get('secret key','') aws_access_user_id_val = req.POST.get('aws access user id', '') logging.debug(access_key_val+" " +secret_key_val+" " +aws_access_user_id_val) cred_obj = aws(access_key = access_key_val,secret_key =secret_key_val,aws_access_user_id = aws_access_user_id_val) cred_obj.save() return HttpResponseRedirect(reverse('s3comp:fileinput')) except Exception as e: logging.debug(e) else: form = aws() return render(req,'s3comp/fileinput.html',{'form':form}) html file <form action="{% url 'fileinput_home' %}" method="post"> {% csrf_token %} <p><label for="Aws access user id">User:</label><input type="text" name="Aws access user id" value={{ user.get_username … -
How can I display a model and a form under one class in views.py in Django?
I am trying to display the data in details template that I would obtain using AgentForm and I am also trying to add a Matrix1Form that will be unique to each agent, and that matrix1form would be displayed in details.html. Here is my views.py and if I try to display the Matrix1Form, the data from Agent model doesn't get displayed and vice versa, if I want to display an agent, I have to comment out the Matrix1Form. There are no errors popping up so far. The data just don't get displayed. views.py class AgentDetailsView(generic.DetailView): template_name = 'User/AgentDetails.html' class Meta: model = Agent def get(self, request, *args, **kwargs): matrix1form = Matrix1Form() return render(request, self.template_name, {'matrix1form': matrix1form}) forms.py class AgentForm(forms.ModelForm): prefix = 'agentform' class Meta: model = Agent fields = '__all__' class Matrix1Form(forms.ModelForm): prefix = 'matrix1form' class Meta: model = Matrix1 fields = '__all__' models.py class Agent(models.Model): AgencyName = models.CharField(blank=True, max_length = 50, verbose_name="Agency Name") OtherAgencyName = models.CharField(max_length=50, blank=True) FirstName = models.CharField(max_length=50, null=True) LastName = models.CharField(max_length=50, null=True) details.html <ul> <li>AgencyName: {{agent.AgencyName}} </li> <li>OtherAgencyName: {{agent.OtherAgencyName}} </li> <li>First Name: {{agent.FirstName}} </li> <li>Last Name: {{agent.LastName}} </li> </ul> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ matrix1form.as_table }} </table> </form> -
Django Rest Framework i18n works on GET but doesn't works on POST
I have API in my project and need to make some data in response translatable. So I have model: class Ticket(models.Model): NEW = 'new' CONFIRMED = 'confirmed' USED = 'used' CANCELED = 'canceled' STATUS_CHOICES = ( (NEW, _('New')), (CONFIRMED, _('Confirmed')), (USED, _('Used')), (CANCELED, _('Canceled')), ) service_subscription = models.ForeignKey(ServiceSubscription) price = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) ticket_order = models.ForeignKey(TicketOrder) begin_stamp = models.DateTimeField() status = models.CharField(max_length=15, choices=STATUS_CHOICES, default=NEW) code = models.CharField(max_length=36, null=True, blank=True) created = models.DateTimeField(default=timezone.now) changed = models.DateTimeField(auto_now=timezone.now) processed_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True) Serializer for that case: class TicketViewSetSerializer(serializers.ModelSerializer): status = serializers.SerializerMethodField() class Meta: model = Ticket fields = ('begin_stamp', 'status', 'changed') def get_status(self, obj): return obj.get_status_display() And I have viewset where I call this: class TicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.all() serializer_class = TicketViewSetSerializer permission_classes = (IsAuthenticated, IsCorpMember) @list_route(methods=['get', 'post'], url_path='check/(?P<event_schedule_pk>[0-9]+)') def check_ticket(self, request, event_schedule_pk, *args, **kwargs): event_schedule = get_object_or_404(EventSchedule, pk=event_schedule_pk) data = {} status = 200 if request.method == "POST": # get ticket code code = request.data.get('code') try: ticket = self.queryset.select_for_update().filter( code=code, begin_stamp=event_schedule.start, service_subscription__data__jcontains={'id': event_schedule.event_id})[0] except IndexError: return HttpResponseNotFound(ugettext('Code invalid or ticket is not for this event')) if ticket.status == 'confirmed': ticket.status = 'used' ticket.processed_by = request.user ticket.save() else: status_msg = { 'new': ugettext('Need to be paid firstly'), 'used': ugettext(u'Already used'), … -
Creae a form from a ListView
I am trying to create a radio form type with using input based on a List object from my model team. To make it clearer I have a model team and I want my user to be able to select from one of the team that was created before. I don't thing that I am taking the right direction: views.py: class LinkTeam(generic.ListView): template_name = 'link_project.html' def get_queryset(self): #import pdb; pdb.set_trace() #team2 = Team.objects.all().filter(team_hr_admin = self.request.user) queryset = Team.objects.filter(team_hr_admin=self.request.user) return queryset def team_select(request): if request.method == 'POST': print("it is working") return HttpResponse('test') html: {% extends 'base.html' %} {% block body %} <div class="container"> <div class="jumbotron"> <h2>Select one of your team and link it to your project</h2> </div> <div class="col-md-8 col-md-offset-2"> <form class="" method="post"> {% csrf_token %} {% for i in team_list %} <div class="col-md-4"> <div class="radio"> <label><input type="radio" name="optradio"> {{ i }}</label> - details </div> </div> {% endfor %} <div class="col-md-2 col-md-offset-10"> <button type="submit" class="btn btn-primary">Select</button> </div> </form> </div> </div> {% endblock %} models.py from django.db import models from registration.models import MyUser from django.core.urlresolvers import reverse # Create your models here. class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return … -
How to redo tables without dropping it in Heroku
Every time I change columns name or length or anything, I need to drop the entire database in heroku. This is after doing makemigrations and migrate. On local, it works fine. I don't need to adjust. On heroku it's becoming to a point where I can't keep resetting. I reset by using heroku pg:reset DATABASE_URL. What is another way where I don't need to drop the entire database every single time i make an adjustment? -
How to setup URLs with subfolders in Django?
I have the following setup of links that allow me to navigate through the different URLs of my Django web app, however, I am missing something that is making my web app to throw a Page not found (404) error. This is the scenario: I have the following structure of folders and html files: personal_website (web app name) -no_results_graphs (folder) -graph_no_results.html --test_no_results_table (subfolder) --table_no_results.html -results_graphs (folder) -graph_results.html --test_results_table (subfolder) --table_results.html header.html home.html When I navigate from: graph_no_results.html -> graph_results.html = OK graph_results.html -> graph_no_results.html = OK table_no_results.html -> graph_no_results.html = OK table_no_results.html -> table_results.html = OK graph_no_results.html -> table_no_results.html = NOT OK graph_results.html -> table_no_results.html = NOT OK And I encounter the following errors: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/graph_results/test_no_results_table/table_no_results/ Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/graph_no_results/test_no_results_table/table_no_results/ The setup of the views was set as the following: url(r'^test_no_results_table/table_no_results/$',views.tickets_current_week), url(r'^test_results_table/table_results/$',views.tickets_current_week, name='current_week'), What am I missing or why my pages cannot be found? -
Two values totally different
def count_customers_per_period(self): if not self.request.GET.get('period'): period = self.request.GET['period'] entry_date_production = datetime.datetime(2017, 6, 1) start_date = CustomerProfile.objects.filter(user__date_joined__gte=entry_date_production).\ first().user.date_joined end_date = CustomerProfile.objects.last().user.date_joined @property def start_end_period(period): start = start_date - datetime.timedelta(period) end = start + datetime.timedelta(period - 1) return start, end if period == 'day': array = np.array([]).astype(int) while start < end: count = CustomerProfile.objects.filter(user__date_joined__date=start_date).count() array = np.append(array, count) start_date += datetime.timedelta(1) elif period == 'week': array = np.array([]).astype(int) start, end = start_end_period(7) while start < end: count = CustomerProfile.objects.filter(user__date_joined__range=[start, end]).count() array = np.append(array, count) start = end + datetime.timedelta(1) end = start + datetime.timedelta(6) elif period == 'month': array = np.array([]).astype(int) start, end = start_end_period(months=1) while start < end: count = CustomerProfile.objects.filter(user__date_joined__range=[start, end]).count() array = np.append(array, count) start = end + datetime.timedelta(1) end = start + datetime.timedelta(months=1) elif period == 'year': array = np.array([]).astype(int) start, end = start_end_period(years=1) while start < end: count = CustomerProfile.objects.filter(user__date_joined__range=[start, end]).count() array = np.append(array, count) start = end + datetime.timedelta(1) end = start + datetime.timedelta(years=1) return array Analyzes the content when the period is at week : In [181]: array = np.array([]).astype(int) ...: start, end = start_end_period(7) ...: test_count = CustomerProfile.objects.filter(user__date_joined__gte=start).count() ...: while start < end_date: ...: count = CustomerProfile.objects.filter(user__date_joined__range=(start, end)).count() ...: print('The start date is {} … -
how to change pywebview and cherrypy base core from mozilla to chrome
I am working on a semi-standalone app (Django app as native desktop app ) using cherrypy as a server, django for the development and Py2exe and pywebview to create the semi standalone app. When I test it on browsers, chrome works fine, but Mozilla is not because of Mozilla's standards, and it's the same for Pywebview's browser. I noticed that it's using Mozilla core: INFO:cherrypy.access.4371749296:127.0.0.1 - - [25/Sep/2017:15:50:39] "GET /static/test/js/ned.js HTTP/1.1" 404 658 "http://localhost:9090/Departments/test/" "Mozilla/5.0 PS:-when I inspect elements on Firefox, I notice that it detect the css file. But the Pywebview does not. -I am following this tutorial: https://moosystems.com/articles/14-distribute-django-app-as-native-desktop-app-01.html Thank you!! -
Django pagination error: That page contains no results
I have results object which has 2 objects inside of it: Teacher 1 and Teacher 2. I wanted to build a pagination, so that only a single teacher is displayed per page. I have a teacher_list function view: def teacher_list(request, **kwargs): #get results variable #get number of teachers count = "{} Results Found".format(results.count()) page = request.GET.get('page', 1) paginator = Paginator(results, 1) try: results = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. results = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. results = paginator.page(paginator.num_pages) return render(request, "users/teacher_list.html", context={"teacher_list": results,"count": count,}) Template.html {% if is_paginated %} {% load users_tags %} {% if teacher_list.has_previous %} <li><a href="?{% url_replace page=teacher_list.next_page_number %}">{{ teacher_list.previous_page_number }}</a></li> {% endif %} <li><a href="#" class="current-page">{{ teacher_list.number }}</a></li> {% if teacher_list.has_next %} <li><a href="?{% url_replace page=teacher_list.next_page_number %}"><i class="sl sl-icon-arrow-right"></i></a></li> {% endif %} {% endif %} The if_paginated logic in the template doesn't work, since I don't get anything displayed. When I manually change the parameter in the URL to page=2, I get the second teacher. So I decided to remove if_paginated and run my pagination without it. The {% if teacher_list.has_next %} part works fine … -
Django Integrity Error:Cannot add or update a child row: a foreign key constraint fails using factory_boy in django unit test
I started writing unit tests for my django app, and I used factory boy to create objects with data. but I'm having this error IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails This my code : models class Group(models.Model): created_by = models.ForeignKey(User) name = models.CharField(_('Name'), max_length=100) description = models.TextField(_('Description'), max_length=1000) members = models.ManyToManyField(User, verbose_name='Members', related_name='member', blank=True) class User(models.Model): username = models.CharField(_('username'),max_length=30,unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), blank=True) password = models.CharField(_('password'), max_length=128) factories class UserFactory(factory.django.DjangoModelFactory): class Meta: model = models.User # to have unique user names username = factory.Sequence(lambda n: 'name%d' % n) first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') # email based on the username email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) password = 'admin' class GroupFactory(factory.django.DjangoModelFactory): class Meta: model = models.Group created_by = factory.SubFactory(UserFactory) @factory.post_generation def members(self, create, extracted, **kwargs): if not create: # GroupFactory.build() return if extracted: # A list of users were passed in, use them for member in extracted: self.members.add(member) and in tests.py I wanted to test the Group model, here how I'm creating Group instance: class GroupTest(BaseModelTest): model = Group group = GroupFactory.build() BaseModelTest contains some abstract methods to … -
Redirecting after autocomplete selection in Django
I have done an autocomplete search bar using Django and JQuery. I managed to get the selection written into the textbox but what I want to do is to redirect the user to an url which uses the data in the textbox. Here are my HTML and JS files: <script> $(function() { $("#places").autocomplete({ source: "{% url "get_places" %}", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } </script> <h1>Bienvenue sur le site de la Kfet !</h1> <h2>Rechercher un Klient dans la barre de recherche ci-dessous :</h2> <!-- jQuery !--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script> <!-- jQuery UI !--> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <div class="ui-widget"> <label for="places">Rechercher un klient : </label> <input id="places"> </div> I guess I have to put a kind of "link" in the JS file, but I don't know how to do it and to pass it the argument I want (the input text selected) Thanks in advance. -
How can I specify expiry time on session in django>=1.6?
Here is my code. Bu it works only if I set 'SESSION_SERIALIZER = "django.contrib.sessions.serializers.PickleSerializer"' in the settings file. ... tz = timezone.utc expire_time = timezone.datetime.utcfromtimestamp(oa_token_expire_time).replace(tzinfo=tz) request.session.set_expiry(expire_time) ... -
Adding new field to existing database table in django python
I have a Postgresql database connected with my django application, Now I have a existing table in the database and want to add a new field to this table using the migrate command. But when I try to add this new field to my models.py and run makemigration and migrate commands, django says there are no new migrations to apply. Can you help me with how to add a new field to existing table. -
Django Filter Backend filter by latitude and longitude
I'm using django-google-maps to get the the location of a place. In models i have this field: models.py class PlaceLocation(models.Model): name = models.CharField(max_length=200) address = map_fields.AddressField(max_length=200) geolocation = map_fields.GeoLocationField(max_length=100) When i add an address it automatically finds the latitude and longitude in this format: 44.4385334,26.005750199999966 I want to use django filter backend to filter by latitude and longitude, but i can't get the values separated. filters.py class LocationFilter(django_filters.FilterSet): ids = NumberInFilter(name='id', lookup_expr='in') geolocation = django_filters.NumberFilter(name='geolocation', lookup_expr='iexact') If i access: 'http://127.0.0.1:8000/locations/places/' it will show me all the places. 'http://127.0.0.1:8000/locations/places/?geolocation=44.4385334,26.005750199999966' it's giving me an empty list. How can i get the values separated so i can filter like this: 'http://127.0.0.1:8000/locations/places/?lat=44.4385334&long=26.005750199999966' -
NoReverseMatch at / with templates in different folders
I have a problem with Django Templates in nested folders. I read the other questions with this problem, but I didn't find the correct solution for my problem. Could you help me? My project has the next schema: . ├── eventus │ ├── eventus │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── db.sqlite3 │ │ ├── settings │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ ├── base.cpython-36.pyc │ │ │ │ └── local.cpython-36.pyc │ │ │ ├── base.py │ │ │ ├── local.py │ │ │ ├── prod.py │ │ │ └── staging.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── myapps │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-36.pyc │ ├── events │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── admin.cpython-36.pyc │ │ │ ├── models.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── views.cpython-36.pyc │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ ├── 0001_initial.py … -
django db_table not changing
Hi i have created a dynamic table model and it is not changing whenever i select another table from the list i ve created in the template... if i select the first table to see the data of it and then go back to the list and select the second table i get this error InternalError: (1054, u"Unknown column 'table_name1.id' in 'field list'") So basically when i change from http://127.0.0.1:8000/tables/id=1/ to http://127.0.0.1:8000/tables/id=2/ it gives me error. But if i restart the server and go straight to http://127.0.0.1:8000/tables/id=2/ it works. But now http://127.0.0.1:8000/tables/id=1/ it doesn't work. this is the party of views.py def addview(request, pk): table_name = Crawledtables.objects.get(id=pk) print table_name AllTables._meta.db_table = table_name.name print AllTables._meta.db_table tbl_detail = AllTables.objects.all() print tbl_detail return render(request, 'tables/table_list.html', {'details': tbl_detail}) The prints are just for testing and they work. It prints out the correct table i select. But the tbl_detail it doesn't print when i go to the 2nd table that i selected. only when i restart the server. CrawledTables holds all the table names inside that DB with the date of creation of each table. I get the table name of the CrawledTables and put it in the AllTables._meta.db_table. AllTables access all the tables in … -
`error: unpack requires a string argument of length 4` error when using syncdb to migrate
Never seen anything like it. When I do python manage.py syncdb in a Django app on the Ubuntu terminal, I'm seeing: error: unpack requires a string argument of length 4 I'm not sure what that means or how to fix it. p.s. I know syncdb is deprecated from 1.9 onwards. Put that on the back-burner for the purposes of this question. -
Django, define intermediate model AFTER m2m
I have a m2m field; class MyModel(BaseModel): initiatives = models.ManyToManyField('app.OtherModel',) But now, I need to define my own intermediate model for this m2m, after the fact; class MyModel(BaseModel): initiatives = models.ManyToManyField( 'app.OtherModel', through='app.Intermediate' ) Is there a way for me to seamlessly define one, without Django or my migrations getting really mad at me? Thanks in advance! -
Django RestFrame Work Not Registering Router Urls
I am trying to use Django's rest_framework but am having trouble with the routing. base.urls.py url(r'^api/', include('api.urls', namespace='api'), name='api'), api.urls.py from django.conf.urls import url, include from rest_framework import routers from api import views router = routers.DefaultRouter() router.register(r'test', views.UserViewSet, base_name='NAV') urlpatterns = [ url(r'^', include(router.urls)), ] api.views.py class UserViewSet(APIView): renderer_classes = (JSONRenderer, ) def get(self, request, format=None): querysets = NAV.objects.filter(fund__account_class=0, transmission=3).values( 'valuation_period_end_date').annotate( total_nav=Sum(F('outstanding_shares_par') * F('nav'))).order_by('valuation_period_end_date') content = {'qs': querysets} return Response(content) But when I try http://localhost:8000/api/test, I get a 404 Page not Found error. Any ideas? -
Using TextInput as widget for ManyToManyField
I have two models: class Post(models.Model): title = models.CharField() body = models.TextField() author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) tags = models.ManyToManyField( Tag, related_name='posts', blank=True, ) class Tag(models.Model): name = models.CharField(max_length=30, unique=True, null=False, blank=False) And ModelForm for Post: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'body', 'tags'] widgets = { 'tags': forms.TextInput, } Default widget for tags field in PostForm is MultipleSelect, but I want to use TextInput and force users to type tags and separate them with commas and if there are new tags then add its into database. The question is what field (and how) should I overwrite in PostForm in order to specify logic for setting (before rendered) and getting (after post request) value from TextInput widget? -
Django context error in extended template called by view
I'm working in Django 1.11 with Django-Jet template. Now I need to extend template in order to showing some data retrived from a view. So, I defined my template and my view. Here is the code: views.py from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import View from django.template.context import RequestContext from django.template import Context, Template class MyView(View): def get(self, request, *args, **kwargs): op = str(self.kwargs['op']).strip().lower() pk = self.kwargs['pk'] if op =='get': template='frontend/templates/show_my_data.html' return render_to_response(template,{'foo':'bar'}) else: return HttpResponse("Not found") My simple template: {% extends "admin/base.html" %} {% load i18n admin_urls static admin_modify %} {% block content %} {{ foo }} {% endblock %} settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'static/')], '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', ], }, }, ] .... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] But when I run a test I get a key error: Request Method: GET Request URL: http://127.0.0.1:8000/admin/data_from_db/get/24/ Django Version: 1.11.2 Exception Type: KeyError Exception Value: 'user' Exception Location: /home/marco/sviluppo/myapp/myvenv/lib/python3.4/site-packages/django/template/context.py in __getitem__, line 87 Python Executable: /home/marco/sviluppo/myapp/myvenv/bin/python So, I make some test, and I found that the problem is (maybe) in context variables. This is my base template that I need … -
Django Pagination with other variables in the GET request in a Function Based View
I've tried to implement the following solution from here: How to paginate Django with other get variables? I added this to my views.py from urllib.parse import urlencode from django import template register = template.Library() @register.simple_tag def url_replace(request, field, value): dict_ = request.GET.copy() dict_[field] = value return dict_.urlencode() def teacher_list(request, **kwargs): paginator = Paginator(results, 1) page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. results = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. results = paginator.page(paginator.num_pages) template.html {% if teacher_list.has_next %} <li><a href="?{% url_replace request 'page' teacher_list.next_page_number %}">Next</a></li> {% endif %} However, this gives me: Invalid block tag on line 155: 'url_replace', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? I also tried loading: @register.simple_tag(takes_context=True) def url_replace(context, **kwargs): query = context['request'].GET.dict() query.update(kwargs) return urlencode(query) without success. I also tried: @register.simple_tag(takes_context=True) def url_replace(request, **kwargs): query = request.GET.dict() query.update(kwargs) return urlencode(query) None of these seem to work.