Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to query database with conditional expression in Django?
I have three models: Business, Offers and OfferPlan: Business: class Business(models.Model): name_of_business = models.CharField(max_length=255) Offers: class Offers(models.Model): business = models.ForeignKey(Business, related_name="business_offer", on_delete=models.CASCADE) title = models.CharField(max_length=255) subtext = models.CharField(max_length=255) OfferPlan: class OfferPlan(models.Model): WEEKDAYS = [ (1, _("Monday")), (2, _("Tuesday")), (3, _("Wednesday")), (4, _("Thursday")), (5, _("Friday")), (6, _("Saturday")), (7, _("Sunday")), ] offer = models.ForeignKey(Offers, related_name="business_offer_plan", on_delete=models.CASCADE) weekday = models.IntegerField( choices=WEEKDAYS, ) from_hour = models.TimeField() to_hour = models.TimeField() I have a ListView which search for businesses open based on different params such as city, category etc. I also want to now search by weekday, say which business is open on Monday will be displayed and which are not wont be displayed on that day. Weekday information is stored in OfferPlan and there could be multiple timings for the offers that day in OfferPlan table, but I want to query (filter, exclude) the businesses who has even a single entry on that weekday number. Here is my ListView: class SearchListView(ListView): template_name = 'search/search.html' model = Business def get_queryset(self): # queryset = Business.objects.filter(business_address__city=AppLocations.objects.first().city) if 'city' in self.request.GET: queryset = Business.objects.filter(business_address__city=self.request.GET.get('city')) if 'category' in self.request.GET: queryset = queryset.filter(category__code=self.request.GET.get('category')) # if 'date' not in self.request.GET: # queryset = B raise return queryset How could this be possible? … -
User Authentication in Django REST Framework
I have a Django REST backend, and it has a /users endpoint where I can add new users through POST method from frontend. /users endpoint url: http://192.168.201.211:8024/users/ In this endpoint I can view all users information and add new user, so I must avoid others entry it except Administrator. I create a superuser admin with password admin123 by python manage.py createsuperuser. My question is, If I want to do a HTTP POST from frontend(I use Angular) I have to pass the Administrator's user name and password, admin and admin123, along with POST head information. So I let others know the user name and password who check the source code of frontend. Is there any other way to do this Authentication without exposing Administrator's user name and password to others? -
400 ERROR (all-auth facebook) - Django
I'm using all-auth and Django RESTful Framework for authorization. I could receive token from Facebook from My Login page (login was successful with facebook id and password, ). Then I passed the token to the all-auth server (/rest-auth/facebook/). Here is the HTTP body { "access-token" : "TOKEN_FROM_FACEBOOK" } Then it printed 400 with "Incorrect value" (I got 400 so tested on Postman) { "non_field_errors": [ "Incorrect value" ] } I'm not sure which part of code I should post here. So can I comment back and edit this post once you ask? Thank you so much!:) -
Django - pre-save VS post-save VS view save
I want to perform some action (sending email) after updating an (already existing) object. In order to do it I need to compare values of the object before and after saving and only if something specific has changed - do that action. From reading other related question I understood that I can only do it in pre-save signal, since I can't get the old version inside 'post-save', but - what if there will be some issue with saving and the item will not be saved? I don't want to perform the action in that case. So I thought about implementing it somehow by overriding the view save, but I'm not sure that's the correct way to do it. What do you think? This is implementing in pre-save: @staticmethod @receiver(pre_save, sender=Item) # check if there is change that requires sending email notification. def send_email_notification_if_needed(sender, instance, raw, *args, **kwargs): try: # if item just created - don't do anything pre_save_item_obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass # Object is new, so field hasn't technically changed else: # check if state changed to Void if pre_save_item_obj.state_id != VOID and instance.state_id == VOID: content = {"item_name": instance.title, "item_description": instance.description} EmailNotificationService().send_email("item_update" ["myemail@gmail.com"], str(instance.container.id) + str(instance.id) + … -
ManyToManyField already populated with users
I have a table called Story with a ManyToManyField to the User table. This is meant for user to subscribe. But when I check the admin/panel. The ManyToManyField is already populated with all users. And I can not change anything on this field. Also when I try to query all Stories I get no results. view: stories = Story.objects.filter(users=request.user) This is how I subscribe a user to a story: story = get_object_or_404(Story, pk=story_id) user = request.user story.users.add(user) This is the Story model: class Story(models.Model): story_name = models.CharField(max_length=550) users = models.ManyToManyField(User, related_name='subscriber') dateAdded = models.DateTimeField(auto_now_add=True) userAdded = models.ForeignKey(User) -
Django Rest Framework - Cache 'list' function but not 'retrieve' function (detail) in ModelViewSet
I have the following code: class OrderListViewSet(viewsets.ModelViewSet, ReadOnlyCacheResponseAndETAGMixin): permission_classes = (NoUpdatePermission,) model_class = Order lookup_field = 'unique_reference' serializer_class = OrderSerializer pagination_class = OrderPagination @method_decorator(cache_page(settings.ORDER_CACHE_LIFETIME)) def dispatch(self, *args, **kwargs): return super(OrderListViewSet, self).dispatch(*args, **kwargs) def get_serializer_class(self): if self.request.method == 'POST': return CreateOrderSerializer return super(OrderListViewSet, self).get_serializer_class() def get_queryset(self, filters=None, **kwargs): self.queryset = Order.objects.all() return super(OrderListViewSet, self).get_queryset() def perform_create(self, serializer): if not self.request.user.is_authenticated: _create_anonymous_user(self.request) serializer.save(user=self.request.user) return super(OrderListViewSet, self).perform_create(serializer) I want to migrate to: class OrderListViewSet(viewsets.ModelViewSet, ReadOnlyCacheResponseAndETAGMixin): permission_classes = (NoUpdatePermission,) model_class = Order lookup_field = 'unique_reference' serializer_class = OrderSerializer pagination_class = OrderPagination @method_decorator(cache_page(settings.ORDER_CACHE_LIFETIME)) def dispatch(self, *args, **kwargs): return super(OrderListViewSet, self).dispatch(*args, **kwargs) def get_serializer_class(self): if self.request.method == 'POST': return CreateOrderSerializer return super(OrderListViewSet, self).get_serializer_class() def get_queryset(self, filters=None, **kwargs): self.queryset = Order.objects.all() return super(OrderListViewSet, self).get_queryset() def perform_create(self, serializer): if not self.request.user.is_authenticated: _create_anonymous_user(self.request) serializer.save(user=self.request.user) return super(OrderListViewSet, self).perform_create(serializer) My goal is to cache the ListView for 60 seconds but not the DetailView (always return latest data from there as it is used for long pulling). The error which I get is: TypeError: never_cache() missing 1 required positional argument: 'view_func' Would it be reasonable to remove the never_cache decorator all together? -
TypeError: tuple indices must be integers, not str Python/django
I'm having an error with this: cursor = connection.cursor() cursor.execute("SELECT username as username, sum(ACCTSESSIONTIME) as total_acctsessiontime FROM RADUSAGE GROUP BY username LIMIT 0, 10") usage_summary = cursor.fetchall() for row in usage_summary: row['total_acctsessiontime'] = 0 if row['total_acctsessiontime'] is None else humanize_seconds(row['total_acctsessiontime']) row['total_acctinputoctets'] = 0 if row['total_acctinputoctets'] is None else naturalsize(row['total_acctinputoctets']) row['total_acctoutputoctets'] = 0 if row['total_acctoutputoctets'] is None else naturalsize(row['total_acctoutputoctets']) return jsonify(cursor) Error: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/rachelbustamante/gridloc_radiator2/admin_app/dashboard.py", line 57, in inquiry row['total_acctsessiontime'] = 0 if row['total_acctsessiontime'] is None else humanize_seconds(row['total_acctsessiontime']) TypeError: tuple indices must be integers, not str This is my first time to use the cursor connection. I hope someone could help me with this. -
Google app engine cron django failed after 30 seconds
I am trying to schedule a task on app engine using cron that will run continuously on background. I have written the cron task it works fine on local server but it failed after 30 seconds. cron.yaml cron: - description: daily tweets streaming url: /path/to/cron schedule: every 24 hours views.py def testing(request): print("okasha---") from streamTweets import start_stream start_stream() urls.py url(r'^path/to/cron$', views.testing, name="testing"), I have read a solution that says to divide the task into subtasks but i am not able to divide it into subtasks. My log says No entries found but when I access it directly by url it starts the script but after 30 seconds it gives 502 bad gateway error. -
Django how to use the slug in URL as a variable
I want to use the slug in the URL as a variable for my API. So first I need to me to put the slug in the urls.py which looks something like this. url(r'^use/(?P<slug>[\w-]+)/$', view_function, name="api") Then I need to includ the slug in the view.py, which look something like this: def urlextractor(request, slug): if request.method == 'POST': serializer = Serializer(data=slug) # do something with slug The problem that is that I get the code 404. Can you give me some example or references that I can look at? -
django media not found (uploaded in admin page)
I'v set an Imagefield for one of my Models in this way: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) points = models.IntegerField(default=0) avatar = models.ImageField(upload_to=user_directory_path, default='/defaultavatar.jpg') and this is my setting for media root and url: BASE_DIR = os.path.dirname(os.path.abspath(__file__)) MEDIA_ROOT= os.path.join(BASE_DIR,'site_media/media/') MEDIA_URL='/media/' STATIC_ROOT=os.path.join(BASE_DIR,'site_media/static/') STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'static') ] when I create a profile I can access defalutavatar.jpg but when I upload another image via admin page and try to open image it says 404 Not Found (although image is created in MEDIA_ROOT) DEBUG is false (in case you want to suggest urlpattern += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)) -
django rest framework - You cannot access body
I'm using django 1.8 rest api as below. @api_view(['GET', 'POST']) @authentication_classes((TokenAuthentication, SessionAuthentication, BasicAuthentication)) @permission_classes((IsAuthenticated,)) @staff_member_required def api(request): print request.data The problem with this is that it retrieves all parameters as string so I have to convert numbers and boolean manually. I tried using: print json.loads(request.body) but apparently django rest framework reads from the data stream which causes this error: Error: RawPostDataException: You cannot access body after reading from request's data stream I also tried json.loads(request.stream.body) because the documentation says stream should work. Is there a way I can retrieve the request post data with the appropriate types? Note that I'm using ajax to send the data with JSON.stringify. -
Increasing page speed with gzip in nginx
I have a live Django site running gunicorn, nginx, supervisord. I am trying to implement the suggestions found here to increase my page speed score by using gzip in nginx. The resulting config file is as follows: upstream app_server_wsgiapp { server 127.0.0.1:8000 fail_timeout=0; } server { listen 80; server_name www.example.com; return 301 https://www.example.com$request_uri; } server { server_name www.example.com; listen 443 ssl; if ($host = 'example.com') { return 301 https://www.example.com$request_uri; } ssl_certificate /etc/nginx/example/example.crt; ssl_certificate_key /etc/nginx/example/example.key; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_protocols TLSv1.1 TLSv1.2; ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA'; ssl_prefer_server_ciphers on; access_log /var/log/nginx/www.example.com.access.log; error_log /var/log/nginx/www.example.com.error.log info; keepalive_timeout 5; proxy_read_timeout 120s; # nginx serve up static and media files and never send to the WSGI server location /static { autoindex on; alias /path/to/static/files; } location /media { autoindex on; alias /path/to/media/files; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://app_server_wsgiapp; break; } } gzip on; gzip_comp_level 5; gzip_min_length 256; gzip_proxied any; gzip_vary on; gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy; location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf)$ { expires 7d; } } After restarting nginx and opening my site in a browser, everything appears … -
What is the recommended way to handle multiple api calls from angular to backend server on the same page(=angular component)?
I'm a backend developing using python/django stack to build a backend api server for our team's frontend developer, who uses angular2 to build SPA for our service. There are times when frontend need to make GET api call to two or more separate resources to backend server. For example, we have payments page, which needs information both from users and products tables. Is it better to make two separate calls at endpoints as follows: /api/users/:user_id /api/products/:product_id or it better to make backend django server to do some data processing to mix up the information and return the results containing both user-related info and product-related info at a single endpoint as follows: /api/payments/:payment_id Which do you think is more standard de facto? -
Djagno login_required unittesting
I have a problem with template testing. Everything has worked fine until I've added a login_required decorator. Now I receive an assertion error when I testing status code and error with template load during Template Used testing. I've tried many things (create superusers, is_active=True and so on) but with no results. What I'm doing wrong? test.py class CityViewTests(TestCase): def setUp(self): user = User.objects.create_user(username='test_username', password='12345', email='random@wp.pl') def test_call_view_loads(self): self.client.login(username='test_username', password='12345') response = self.client.get('main_view') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'main_view.html') url.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^main_view/$', views.main_view, name='main_view'), url(r'^turn_calculations/$', views.turn_calculations, name='turn_calculations') ] -
how to write update query in django webapps
class Login(View): def get(self,request): username=request.GET['username'] password=request.GET['password'] return login_f(username,password) def login_f(username,password): print(username,password) db.employee.insert([{"Username":username,"Password":password,"employee age": 24}]) db.employee.update([{"Username":"username"},{"$set",{"Username":" ","Password":" "}}]) return HttpResponse(d({"username":username,"password":password})) -
Format + Key Error - balance - Django
I am getting a format error for a form field that is not a date form field. I am not sure why it is giving me a form for something not related to the form field i am trying to fill... Here is the exact error that is showing up: ValidationError at /transfer/ ["'0' value has an invalid date format. It must be in YYYY-MM-DD format."] Request Method: POST Request URL: http://localhost:8000/transfer/ Django Version: 1.8.6 Exception Type: ValidationError Exception Value: ["'0' value has an invalid date format. It must be in YYYY-MM-DD format."] Exception Location: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py in to_python, line 1287 Python Executable: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\OmarJandali\\Desktop\\opentab\\opentab', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Here is the models file: class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # server first_name = models.CharField(max_length=25, default='first') last_name = models.CharField(max_length=25, default='last') dob = models.DateField(default='0') city = models.CharField(max_length=45, default='city') # user state = models.CharField(max_length=25, default='state') phone = models.BigIntegerField(default=0) # user privacy = models.SmallIntegerField(default=1) # user balance = models.DecimalField(decimal_places=2, max_digits=9, default=0) created = models.DateTimeField(auto_now_add=True) # server here is the form.py: class TransferForm(forms.ModelForm): acct_choices = (('Tabz', 'Tabz - Username'), ('Wells Fargo', 'Wells Fargo - Username')) main = forms.TypedChoiceField( choices=acct_choices ) transfer = forms.TypedChoiceField( choices=acct_choices ) class Meta: model = … -
Django - using a form from another app - issue creating a redirect
I have a contact app in my project. To use the contact form from that app in the home page I created this in my views.py: from django.views import generic from contact.forms import ContactForm class HomePage(generic.TemplateView): template_name = "home.html" def get_context_data(self, *args, **kwargs): context=super(HomePage, self).get_context_data(*args, **kwargs) context['form'] = ContactForm return context When I submit the form on the home page it redirects to a blank page, instead of either the home page, or a thank you page. Here is the definition in the views.py of the contact app: def contact(request): form_class = ContactForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name', '') contact_email = request.POST.get('contact_email', '') form_content = request.POST.get('content', '') template = get_template('contact/contact_template.txt') context = dict({'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content,}) content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" +'', ['you@company.com'], headers = {'Reply-To': contact_email } ) email.send() return render(request, 'contact/thank_you.html') return render(request, 'contact/contact.html', { 'form': form_class, }) I noticed that filling the form and hitting submit does not output to the console like the contact app page, nor do I get the confirmation page. I believe that means that I need to give the form a path to those files, … -
Colors do not match to json data
Colors do not match to json data. Now my web site is Originally,color(white or green or pink) corresponds to background's color,but now it cannot be done. Console in Google verification,it shows json can be load accurately ,so I really cannot understand why color and background one is not match each other. index.html is <!DOCTYPE html> <html> <head lang="ja"> <meta charset="UTF-8"> </head> <body> {{ form }}<br> <hr> <h1>h1LETTER</h1> <p>pLETTER</p> {{ form }}<br> <hr> <h1>h1LETTER</h1> <p>pLETTER</p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> var xhr = new XMLHttpRequest(); xhr.onload = function(){ colors = JSON.parse(xhr.response) console.log(colors) color_array = [] for (var i=0 ; i<=colors.length ; i++){ color_array[i] = { "background-color" : colors[i]["background_color"], "h1" : colors[i]["h1_color"] , "p" : colors[i]["p_color"] , }; } } xhr.open("GET","http://localhost:8000/app/api/get/",false); xhr.send({}) function change_color(){ color_id = $("#id_color").val(); color_object = color_array[color_id]; $("body").css("background-color", color_object["background-color"]); $("h1").css("color", color_object["h1"]); $("p").css("color", color_object["p"]); } $( '#id_color' ).change( function () { change_color(); }); change_color(); </script> </body> </html> {{ form }} is drill down can be choiced color. forms.py is from django import forms from .models import Color class ColorForm(forms.Form): color = forms.ModelChoiceField( queryset=Color.objects.all(), empty_label=None, required=False, ) Model of Color has background color data. Why does such a strange thing happen? How can I fix this? -
Djongo primary key error
I'm writing a website on Python, Django using MongoDB and djongo (to connect Mongo with Django) and I want to be able to add and delete documents from the database using my website. But i have an error while doing it: If I don't set primary key in my models then I can successfully add documents, but when try to delete have AssertionError (object can't be deleted because its id attribute is set to None), however when I check the database _ID field is there created automatically. If I do set primary key by primary_key = True in models.py I can successfully delete a document, but on insertion I got AssertionError (No exception message supplied). Also, if primary key is not set, then I cannot access documents from admin panel, but can add them to the database (through admin panel); and if pk is set then from admin panel I can access, delete and edit, but cannot add a new document to the database. This is my model: class DevList(models.Model): dev_num = models.CharField(max_length = 200 , primary_key = True) dev_name = models.CharField(max_length = 200) dev_descr = models.CharField(max_length = 200) dev_type = models.CharField(max_length = 200) *** If no pk set, then … -
How do I turn off the built-in header row onclick function in a Django table?
I am building a django table. The headers are clickable by default. It doesn't really do anything besides refreshing the page. I would really like to remove this. Does anyone know how to do this? -
Heroku JawsDB Leopard Shared plan is throwing ulimit error when Django runs migrations
In Heroku we have a hosted Django app with provisioned MySQL database from JawsDB (Leopard Shared plan). The problem occurs on while running Django migrate command as part of Heroku release cycle. We get this error: django.db.utils.OperationalError: (1041, "Out of memory; check if mysqld or some other process uses all available memory; if not, you may have to use 'ulimit' to allow mysqld to use more memory or you can add more swap space") We pinpointed that it fails on the ALTER TABLE that adds a new foreign key column. Any idea what can we do from here or what can we do as a workaround? -
is the "Definite Guide to Django" up to date and still a relevant source for django beginners in 2017?
I just started reading "the definite guide to django" the 2007 edition and Ive noticed some of the information is outdated. It looks like a really in depth book but I want to know if Im not wasting my time reading a 11 year old book with outdated information. -
Django Rest Framework(DRF) Json Web Token(JWT) Authentication and Login Process
I want to implement JWT authentication for my project since this seems to be the most simple one out of all the authentication procedures - but I don't quite understand how an User can actually login using the JWT-auth. It would be helpful if anyone could share some reading materials or provide some insights on the workflow of the login of an user using JWT. My own thoughts were somewhat along these lines: The frontend sends a obtain_jwt request to the backend via drf api The api returns a token in json format, if username and password were provided It's from here I don't understand what needs to done going forward. Does the backend need to do anything else to complete the authentication/login process? Do I need to do anything else with DRF Permissions? If this completes the login process, then there is something else which bugs me. For example, I have an APIView LoginView which has a post method to handle the login process. Now, does the frontend need to call the obtain_jwt function to get the function and then do another post-method to the LoginView? Or is there a way to return the json-web-token from that LoginView? It … -
Didnt return HttpResponse object. It returned None instead - django
I am getting an error with a view that i have and i was wondering if anyone can help me figure out where it is coming from. I am pretty sure it is something small that I am not seeing where it is coming from... Within the view there will be a form that is displayed for the user to input informaiton, once the form is submitted, it is processed and then redirect to the users home... Here is the error: ValueError at /transfer/ The view tab.views.transfers didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://localhost:8000/transfer/ Django Version: 1.8.6 Exception Type: ValueError Exception Value: The view tab.views.transfers didn't return an HttpResponse object. It returned None instead. Here is the views.py def transfers(request): if 'username' not in request.session: return redirect('login') else: username = request.session['username'] currentUser = User.objects.get(username = username) if request.method == 'POST': form = TransferForm(request.POST) if form.is_valid(): cd = form.cleaned_data from_acct = cd['from_acct'] to_acct = cd['to_acct'] amount = cd['amount'] memo = cd['memo'] new_transfer = Transfers.objects.create( user = currentUser, from_acct = from_acct, to_acct = to_acct, amount = amount, memo = memo, frequency = 1, status = 1, ) return redirect('home_page') else: form = TransferForm() form.fields['from_acct'].queryset … -
Bootstrap Navbar-right error
Bootstrap classes are not allowing me to pull my items in the div to the right on my navbar. I am following a Django tutorial online and creating a HTML page with bootstrap. Here is my code: <!-- Individual items in the navbar --> <div class="collapse navbar-collapse" id="topNavBar"> <!-- This makes the collapse three bar button work --> <ul class="nav navbar-nav"> <li class="active"> <a href="{% url 'pics:index' %}"> <span class="glyphicon glyphicon-folder-open" aria-hidden="true"></span>&nbsp; Folders </a> </li> <li class=""> <a href="#"> <span class="glyphicon glyphicon-picture" aria-hidden="true"></span>&nbsp; Pictures </a> </li </ul> <form class="navbar-form navbar-left" role="search" method="get" action="#"> <div class="form-group"> <input type="text" class="form-control" name="q" value=""> </div> <button type="submit" class="btn btn-default">Search</button> </form> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="#"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp; Add Folder </a> </li> <li class=""> <a href="#"> <span class="glyphicon glyphicon-off" aria-hidden="true"></span>&nbsp; Logout </a> </li> </ul> </div> This should work, and the "Add Folder" and "Logout" buttons should be to the right, but it does not work, and these buttons are right next to the search bar. Any help would be appreciated!