Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checkbox instead of boolean writting
models.py @python_2_unicode_compatible class Request(RequestProcess, FolderLinkMixin, TimeStampedModel): DENIED_AT_STATE_CHOICES = ( ('application', _('application')), ('documents', _('Documents')), ('validation', _('Validation')), ('evaluation', _('Evaluation')), ('signature', _('Signature')), ('deposit', _('Deposit')), ) folder_auto_create_childs = [] customer = models.ForeignKey('customers.CustomerProfile') request_type = models.CharField( _('Type'), max_length=15, choices=settings.LOANWOLF_REQUEST_TYPE_CHOICES) state = dxmodels.StateField(RequestWorkflow) validation = models.OneToOneField( 'core.ValidationData', blank=True, null=True) created_by = models.ForeignKey('users.User') rejection_reason = models.CharField( _('Reason of denial'), max_length=250, blank=True, null=True) expires_at = models.DateTimeField(_('Expires at'), blank=True, null=True) copied_from = models.OneToOneField( 'requests.Request', blank=True, null=True, default=None) delete = models.BooleanField(default=False) notes = GenericRelation(Note) contract = models.OneToOneField('contracts.Contract', on_delete=models.SET_NULL, blank=True, null=True, default=None) models.py class RequestsIndexView(StaffRestrictedMixin, FrontendListView): ... class Meta: ordering = ('-created', '-modified') sortable = ('created', 'state', 'modified') list_filter = ('state', 'request_type', created_at, modified_at, entered_state, entered_state_at, expired_at, expired_at_state, 'denied_at_state', rejected_or_denied_state, rejected_or_denied_state_at,) list_display = ( 'product', 'customer_menu', 'state', 'request_type', 'modified', 'created', 'delete_request' ) I put delete = models.BooleanField(default=False) in a my models.py file and I added delete in the Meta class from Request class view, and it showed me that picture instead of multiple checkboxes. How could I fix that so that it show me a checkbox? Please let me know if the question is unclear -
Django: Calling a model's function in my template - not working
I'm trying to call a function from my model (check_nick) in my template. It appears that the template is successfully hitting the function since the items in the function are printed. However I'm not getting the expected result (True) as the user.group I'm testing with is NICK which is part of the NICK_BRANDS list. MODEL.PY: NICK_BRANDS = ['NICK', 'NICKT', 'NICKN', 'NICKK', 'NICKA'] class User(): group = models.ForeignKey(Brand, null=True, blank=True) def check_nick(self): brand = self.group print brand //prints NICK print brand in NICK_BRANDS //prints False (should be True!) if brand in NICK_BRANDS: return True else: return False TEMPLATE: {% if user.check_nick %} //add some markup {% endif %} -
How could you get the local time in django?
I am trying to get the local time but I get the wrong time date all the time: from django.utils import timezone import datetime date = str(timezone.localtime(timezone.now()).now().strftime('%Y-%m-%d')) Local region: Europe/Prague -
Get list of objects with one object from m2m field pointing to self
I have Business model with m2m field holds branches. class Business(models.Model): order = models.IntegerField() branches = models.ManyToManyField('self') And I want to get list of ordered businesses with only one (top) branch from the chain. For example let's the first letter means belonging to the chain, and the number means the sort order: AA-0 AB-1 AC-2 AD-3 B-4 C-5 D-6 E-7 FA-8 FB-9 FC-10 The list I want to get is: AA, B, C, D, E, FA Is it possible to do it with Django ORM or PostgreSQL? -
Django Rest Framework TemplateDoesNotExist about Filter
I used Django 1.10 with django rest framework. I want to filter the url like http://127.0.0.1:8000/api/weathers/?school_id=nhsh And the page will show up all the datas about the nhsh school_id. So I filters_backends and filters_fields under the WeatherViewSet But I am confused why after adding the filters_fields then cause the TemplateDoesNotExist at api/weathers It will open the django_filters/rest_framework/form.html link urls.py from django.conf.urls import include, url from rest_framework import routers from weather import views router = routers.DefaultRouter() router.register(r'weathers', views.WeatherViewSet) urlpatterns = [ url(r'^api/', include(router.urls,namespace='api')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] view.py from rest_framework import viewsets from weather.serializers import WeatherSerializer from .models import Weather from rest_framework import filters class WeatherViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('time' ,'temperature','humidity' ,'uv' ,'light','rainfall','school_id') queryset = Weather.objects.all() serializer_class = WeatherSerializer lookup_field = "school_id" serializers.py from .models import Weather from rest_framework import serializers class WeatherSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Weather fields = ('time' ,'temperature','humidity' ,'uv' ,'light','rainfall','school_id') -
ValueError at / Missing staticfiles manifest entry for ''
I'm trying to migrate from Django 1.9.7 to Django 1.11.5. I have three different django apps, and they are pretty much the same regarding packages and settings. I have deployed all three of them to a web server and two apps are working without any problems, but third one gives me headache - i get this error all the time: ValueError at / Missing staticfiles manifest entry for '' Here are the most relevant settings from settings.py: # -*- coding: utf-8 -*- from settings import * SECRET_KEY = '***' SITE_ID = 3 ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', '.example.com', '.example.com.', ] INSTALLED_APPS += ( 'storages', 'example', 'example2', 'el_pagination', 'debug_toolbar', ) ROOT_URLCONF = 'example.urls' WSGI_APPLICATION = 'example.wsgi.application' DEFAULT_FROM_EMAIL = 'web@example.com' MANAGERS = ADMINS CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'DEFAULT_MIDDLEWARE_ALIAS': 'default', 'DEFAULT_MIDDLEWARE_SECONDS': '300', 'DEFAULT_MIDDLEWARE_KEY_PREFIX': '', } } PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.SHA1PasswordHasher', ) #AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires # 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', # 'Cache-Control': 'max-age=94608000', #S } # AMAZON S3 & CLOUDFRONT SERVING MEDIA FILES AWS_S3_HOST = 's3.eu-central-1.amazonaws.com' AWS_STORAGE_BUCKET_NAME = '***' AWS_CLOUDFRONT_DOMAIN = '***.cloudfront.net' AWS_ACCESS_KEY_ID = "***" AWS_SECRET_ACCESS_KEY = "***" MEDIAFILES_LOCATION = 'example/media' MEDIA_ROOT = '/%s/' % MEDIAFILES_LOCATION MEDIA_URL = '//%s/%s/' % (AWS_CLOUDFRONT_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE … -
How can I serve a webpack'ed (Vue) app through Django without recompiling for every change?
I set up a Django project and want to develop a Vue frontend to go along with it. To set up the Vue app, I used vue init webpack myproject-frontend. Developing both separately is pretty straight-forward, using python manage.py runserver and npm run dev, respectively. Putting the app inside one page of my Django project is easy as well; if I build the Vue app using npm run build first. Obviously, that has the downside of being slow, plus I have to take care of the hash-containing file names (which can be automated, of course). Regarding npm run dev, I'm not too satisfied with only being able to see just the Vue app in the browser. I can still communicate with my API (taking care of CORS), but that's not how the website is going to look in the end. I plan to have multiple Vue components on the same page, and different components on different pages at one point, and that's not reflected by dev. How can I achieve the quickness of not having to rebuild constantly, while retaining the fidelity of not omitting the Django part of the application? I tried to look at what is served by … -
printing a factory error message in terminal django
I am getting an error message in django and I want to print it in the terminal to see wha tthe actual error is and figure out how to fix the error. can anyone help me. this is the error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/omarjandali/Desktop/yap/opentab/tab/views.py", line 1207, in loginAccountSynapse authorizeLoginSynapse(request, form) File "/Users/omarjandali/Desktop/yap/opentab/tab/views.py", line 1223, in authorizeLoginSynapse synapseUser = SynapseUser.by_id(client, str(user_id)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/users/user.py", line 132, in by_id response = client.users.get(id, full_dehydrate=full_dehydrate) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/api/users.py", line 54, in get response = self.client.get(path, **params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/http_client.py", line 58, in get return self.parse_response(response) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/http_client.py", line 86, in parse_response raise ErrorFactory.from_response(response) synapse_pay_rest.errors.NotFoundError The thing i want to print is the following: packages/synapse_pay_rest/http_client.py", line 86, in parse_response raise ErrorFactory.from_response(response) Here is the code that is creating the issue, it is an api call to SynapsePays api. user_id = currentProfile.synapse_id synapseUser = SynapseUser.by_id(client, str(user_id)) print(synapseUser) bank_id = 'synapse_good' bank_pw = 'test1234' bank_code = 'fake' print(bank_code) print(bank_id) print(bank_pw) bank_type = 'ACH-US' args = { 'bank_name':bank_code, 'username':bank_id, … -
limiting a decimal value to only 2 decimal places in django
This is how I get average marks of a bunch of schools def get_clu_average(self): clu_strength = 0 clu_total = 0 for school in self.school_set.all(): clu_strength = clu_strength + school.strength clu_total = clu_total + school.get_average() * school.strength return clu_total / clu_strength So the value will be a decimal number. When I directly use that in template I am getting a lot of decimal places. How do I restrict the value to only 2 decimal places? -
Bypassing Django GenericKey using a property? Good or bad idea?
I have a model where an operator can be a Convive or a Manager. Instead of using a Generic Foreign Key field with operator attribute, is there something wrong doing the following: operator_convive = models.ForeignKey(Convive, blank=True, null=True) operator_manager = models.ForeignKey(Manager, blank=True, null=True) @property def operator(self): return self.operator_convive or self.operator_manager def save(self, *args, **kwargs): # ... override here to prevent operator_convive and operator_manager to be both None, or both not None. -
Checkbox instead of boolean writting
I put delete = models.BooleanField(default=False) in a my models.py file and I added delete in the Meta class from Request class view, and it showed me that picture instead of multiple checkbox. How could I fix that so that it show me a checkbox? -
Python - Max retries exceeded with url (only on production server)
I'm trying to connect to one webpage. This is my code: class AddNewSite(): def __init__(self, url, user=None, email=None, category=None, subcategory=None, date_end=None): self.url = url self.user = user self.email = email req = Request(self.url, headers={'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 \ Safari/537.36'}) self.page = urlopen(req).read() self.soup = BeautifulSoup(self.page) self.meta = self.soup.find_all('meta') In my views.py (It is a Django project) I have: try: page = AddNewSite(siteurl, user) except Exception as e: print(e) messages.add_message(request, messages.ERROR, 'ERROR') return render(request, 'mainapp/subcategory.html', context) Everything works fine on localhost. It connects to site without eny errors. On production server I get an exception. Below I paste error from logs. HTTPConnectionPool(host='exeo.pl', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x80897ff98>: Failed to establish a new connection: [Errno 60] Operation timed out',)) HTTPConnectionPool(host='exeo.pl', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x80940aeb8>: Failed to establish a new connection: [Errno 60] Operation timed out',)) HTTPConnectionPool(host='exeo.pl', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x80949fdd8>: Failed to establish a new connection: [Errno 60] Operation timed out',)) <urllib.request.Request object at 0x808b92048> Why problem exists only on production server? -
Django include static loaded html file
I'm writing a web app that requires a template to load an HTML file in a block that has been uploaded by a user and stored somewhere in the media directory, along with any images or other media referenced by the HTML file using relative paths. Is there some way to do this given the HTML file path is unknown? I want something like.... {% extends 'parent.html' %} {% block content %} {% include {{ htmlpath }} %} {% block content %} to fill the parents content block with a loaded version of the HTML file. -
Django - Inline formset - storing only the last row of the child model (in 1 to many relationship)
Python :3.6.2 Django : 1.11.4 We are trying to use foreignkey across apps. Address is consumed by both customer and agent. We are also using inline formset. Form showing up correct. Please see below for the picture. Create Agent Screen However, when you save it, it saves just the just last of address. Also please note that in edit, a blank line is added which I think should not added by default. Please see below for the pic. Edit Agent screen Folder structure apps (Folder) agent (app) models.py views.py customer (app) models.py views.py sharedmodels(app) models.py forms.py agent/views.py from django.shortcuts import render # Create your views here. from django.db import transaction from django.urls import reverse_lazy from django.views.generic import CreateView, UpdateView, ListView from apps.agent.models import Agent from apps.sharedmodels.forms import AgentAddressFormSet from multiApps.logger import log class AgentList(ListView): model = Agent class AgentCreate(CreateView): model = Agent fields = ['first_name'] #log.info(fields) class AgentAddrLocArefCreate(CreateView): model = Agent fields = ['first_name'] success_url = reverse_lazy('agent-list') def get_context_data(self, **kwargs): data = super(AgentAddrLocArefCreate, self).get_context_data(**kwargs) log.info('i m here 1') if self.request.POST: log.info('i m here 2') #data['location'] = LocationFormSet(self.request.POST) data['address'] = AgentAddressFormSet(self.request.POST) #data['agentreferal'] = AgentReferalFormSet(self.request.POST) else: #data['location'] = LocationFormSet() data['address'] = AgentAddressFormSet() #data['agentreferal'] = AgentReferalFormSet() return data def form_valid(self, form): context = … -
Automatically refreshing table in Django using Jquery
I am developing a code in Django and trying to refresh the table automatically. I have used jquery but it does not refresh the table. Here is the my view: (views.py) from django.http import HttpResponse from django.template import loader from models import objectDB def index(request): objects= objectDB.objects.all() template = loader.get_template('Myapp/index.html') context= { 'objects': objects} return HttpResponse(template.render(context, request)) def refreshedindex(request): increment = int(request.GET['increment']) increment_to = increment + 10 objects= objectDB.objects.all() template = loader.get_template('Myapp/refreshedindex.html') context= {'objects': objects} return HttpResponse(template.render(context, request)) Here is my table plus java script: (index.html) <style> #customers { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } #customers td, #customers th { border: 1px solid #ddd; padding: 8px; } #customers tr:nth-child(even){background-color: #f2f2f2;} #customers tr:hover {background-color: #ddd;} #customers th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #4CAF50; color: white; } </style> {% if objects %} <table style="width:100%" border="1" id = "customers"> <tr> <th>obj Value</th> <th>item</th> <th>Type</th> <th>Tags</th> <th>Date First</th> <th>Date Last</th> </tr> {% for obj in objects %} <tr> <td>{{ obj.value }}</td> <td>{{ obj.item }}</td> <td>{{ obj.type }}</td> <td>{{ obj.tags }}</td> <td>{{ obj.date_first }}</td> <td>{{ obj.date_last }}</td> </tr> {% endfor%} </table> {% else %} <h3>These is no obj to show</h3> {% endif %} <script type="text/javascript" src="jquery-1.11.3.min.js"></script> <script> … -
page redirect with href don show data
im doing an app that get data from course and show it in a table. The url is: url(r'^(?P<id_course>\d{12}M\d{2})/enroll/$', enroll_course, name='enroll_course'), The issue is when redirect with these: <a href="{% url 'enroll_course' id_course=course.id_course %}" ><span class="new badge red darken-4" data-badge-caption="Enroll"></a> This is the function in views.py def enroll_course(request, id_course): print("desde la pagina") course_bites=get_course_detail(id_course) try: course_str = (course_bites).decode('utf-8') except UnicodeDecodeError: course_str= (course_bites).decode('latin1') course = json.loads(course_str ) print(course) print(type(course)) try: course['professor_name']= get_professor(course['professor_course']) except TypeError: print("Error") registration_form = RegistrationForm() context = { "course": course, "registration_form": registration_form, } return render(request, "public/enroll_course.html", context) It charge de page with no information of course, but when i reload with f5 in the browser, charge de data of the course. Any ideas ? Thank so much. -
How to log Django CronJob function errors to the console?
I jave a CronJob function in Django, parsing and saving data.The huge problem is that if something is wrong, no logs appear in console in terminal, which makes life and debugging very difficult. How to log to console in development mode on localhost? class ParseFromKarabasCron(CronJobBase): RUN_EVERY_MINS = 1 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'app.my_cron_job' # a unique code def do(self): pass http://django-cron.readthedocs.io/en/latest/installation.html -
Jenkins GAE Deploy hangs on Getting current resource limits
I am deploying a django project to GAE. When I deploy locally everything runs as smooth as silk, however when I try to deploy from Jenkins it gets hung on the following line: 12:42 PM Getting current resource limits. Full Deploy Log 12:42 PM Application: <gaeproject>; version: dev (was: 1) 12:42 PM Host: appengine.google.com 12:42 PM Starting update of app: <gaeproject>, version: dev 12:42 PM Getting current resource limits. Deploy Command python $GAE_PATH/appcfg.py -A $GAE_INSTANCE -V $GAE_VERSION update . -
How to get the name of a class model in template django
This question is similar to this question (Model name of objects in django templates) but not the same. I want to know how gets the Models class name (in this case 'Apple'), or at the very least return a string that I can pass over. Model.py django.db import models class Apple(models.Model): ..... apple.html <p>Sorry, no {{ ***Model class name**** }}</p> An example in the browser::: " Sorry, no Apple " -
How to modify formset's forms in an iteration
As far as I know if you iterate over a list and update its element, you dont update list itself. list_var = ['a','b','c'] for l in list_var: l = 'x' print list_var it prints out ['a', 'b', 'c'], not X's Below code belongs to one of my project. if hasattr(self.model, 'get_disabled_always_fields'): for field in self.model.get_disabled_always_fields(): for form in self.formset_instance: try: form.fields[field].widget.attrs['readonly'] = True except KeyError as e: pass It updates the list element and it effect the list we were iterating. I didn't bother about it until below code didn't affect formset instances, it's almost the same. for form in self.formset_instance: if hasattr(form.instance, 'get_disabled_fields'): for field in form.instance.get_disabled_fields(): try: form.fields[field].widget.attrs['readonly'] = True except KeyError as e: pass They are almost identical except, First one,checked the attribute and started an outer loop, second one started to iterate over formset instance and, another loop inside that. Question is , why formset forms affected by for loop modifications , and why my second code block didn't affect. -
Vue.js: load component from another component in javascript during initial page load
I'm really new to Vue.js so please be patient. Trying to create a page with a Vue.js component, that will have other child components. Managed to create and load the first outer component, but I'm having trouble to load the child/inner components. The main project is made using python Django and my code is below. Made several attempts with the import instruction, but always endup with an Uncaught SyntaxError: Unexpected token import message in the javascript console. Anyone can help me figure out what am I doing wrong? Django template: teleconsultoria/templates/teleconsultoria/registro_consultoria_0800.html ... <div class="col s12 bibliografia"> <div class="row" id="caixa-de-referencias"> <div class="input-field col s6"> <textarea id="textarea-bibliografia" class="materialize-textarea"></textarea> <label for="textarea-bibliografia">Bibliografia</label> </div> <list items=items></list> </div> </div> ... <script src="https://unpkg.com/vue"></script> <script src="{% static 'core/js/componentes_vue/list.js' %}"></script> <script> var appts2 = new Vue({ el: '#caixa-de-referencias', data: { items: [ 'referenciA 1', 'referenciA 2', ] } }); </script> List of items component: core/static/core/js/componentes_vue/list.js import collection_item from './collection_item.js'; var list = Vue.component('list', { props: ['items'], template: ` <div class="col s6"> <div class="search"> <div class="search-wrapper"> <input id="search-bibliografia" placeholder="Referências (sugestões)"> <i class="material-icons">search</i> </div> <ul class="collection with-header search-results"> <li class="collection-header"><p>Sugestões baseadas na "hipotese"</p></li> <collection-item v-for="item in items"></collection-item> </ul> </div> </div>` }); Item component: core/static/core/js/componentes_vue/collection_item.js var collectionItem = Vue.component('collection-item', { props: ['texto'], … -
ProgrammingError at /api/accounts/ relation does not exist
I have this django app on windows 10 python 3.6.2 django 1.11.5 djangorest 3.6.4 postgreSql 9.6 I'm using a custom User Model(AppUser) in the accounts app and i have AUTH_USER_MODEL = 'accounts.AppUser' in my settings file. I migrate in this order as advised from various sources migrate auth migrate accounts migrate to migrate all other apps And migrations succeeds as expected. The problem begins when i try to access the api through the browsable api ProgrammingError at /api/accounts/ relation "accounts_appuser" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_appuser" WHERE " I've delete all .pyc files created migrations again and got the same error. Through the process of trying over and over sometimes migration reports No migrations to apply Im starting to think the problem is from postgre -
login() and logout() of django.contrib.auth.views
//models.py from django.contrib.auth.models import AbstractUser from django.contrib.sessions.models import Session class CustomUser(AbstractUser): addr1= models.CharField(max_length=20) addr2= models.CharField(max_length=20) city= models.CharField(max_length=20) state= models.CharField(max_length=20) forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'})) //project/urls.py(the outer one) from django.contrib.auth import views from student.forms import LoginForm url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/home'}), //login.html(the login template) <div class="container"> <section id="content"> <form action="{% url 'login' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1>Login Form</h1> <div class="imgcontainer"> <img src="{% static 'student/patient.jpg' %}" alt="Avatar" class="avatar"> </div> <div class="username"> {{ form.username.label_tag }} {{ form.username }} </div> <div class="password"> {{ form.password.label_tag }} {{ form.password }} </div> <div class="submitb"> <input type="submit" value="Log In" name="mybtn"> </div> <div class="resetb"> <input type="submit" value="Reset"> <a href="#forgotpwd">Forgot password?</a> </div> <input type="hidden" name="next" value="{{ next }}" /> </form> </section> </div> this is the settings.py //settings.py LOGIN_REDIRECT_URL = '/login/sample' is the login() and logout() being called here when i login and logout in this manner?...if not then can i extend the login() and logout() of django.contrib.auth??? -
selecting specific object from list in django template
I am working with a formset_facotry and I am having an issue trying to figure something out. I have a list of users returned from a queryset in views.py file. I also have a list of forms that are created based on the number of objects returned from the list query. What I want to happen is that it selects the first object returned and display it before the first form that is to be displayed. Then grab the second object and displayed it right before the second form and so on... General idea behind it is the followoing: I want it to do something like this general template: header = 'Add record' + groupName if message: print(message) count = 0 for f in form: expenses[0] f.as_p count = count + 1 I want to grab a specific item based on the count within the loop: Here is the code that I have in the template: {% extends "base.html" %} {% block content %} <h2>Add expense - {{ currentGroup.name }}</h2> {% if message %} <p>{{message}}</p> {% endif %} <form action="." method="POST"> {% csrf_token %} {{ form.management_form }} {% with count=0 %} {% for f in form %} {% for expense … -
Anchor tag appending field to current url
I have a model with a field website_link class Partner(models.Model): website_link = models.CharField(max_length=120) And I access it in the template like so <div class="col-sm-3 col-sm-offset-1"> {% if instance.logo %}</a> <!-- website link just gets appended to the end of current url for some reason--> <a href="{{ instance.website_link }}"><img src='{{ instance.logo.url }}' class='img-responsive' alt=""></a> {% endif %} </div> When I call this in the template inside of an anchor tag the link navigates to the current url with the website_link appended to the end. So if instance.website_url = www.partnerone.com instead of the linke going to "www.partnerone.com" it goes to "http://127.0.0.1:8000/partners/partner-one/www.partnerone.com"