Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
playing audio when a button is clicked in html django template
i have the following html code snippet: <audio controls><source src="{{sound.sound.url}}" type="audio/mpeg" id="yourAudioTag">Your browser does not support the audio element.</audio> <button id="play">Play</button> <script> $(document).ready(function() { var audioElement = document.createElement('audio'); $('#play').click(function() { audioElement.play(); }); }); </script> but it doesn't seem to play the audio when i click on the button PLAY. how can i do it? -
Django - Design choices, Override the model save() so it palys nice with contrib.admin?
I'm with some design issues in Django and getting all to play nice with contrib.admin. My main problem is with Admin Inlines and the save_formset() method. I created a create() classmethod for the model but this do not play nice with save_formset(). I think Django admin have a way of doing this, not with a create() method. In the create() method in the AdPrice I basicaly want to update the field 'tags' in the model Ad. My question: Instead of creating a create() classmethod it would be nice to override the model save() method so I don't have problems with contrib.admin? My code: Models: class Ad(models.Model): title = models.CharField(max_length=250) name = models.CharField(max_length=100) description = models.TextField() tags = TaggableManager() comment = models.TextField(null=True, blank=True) user_inserted = models.ForeignKey(User, null=True, blank=True, related_name='user_inserted_ad') date_inserted = models.DateTimeField(auto_now_add=True) user_updated = models.ForeignKey(User, null=True, blank=True, related_name='user_updated_ad') date_updated = models.DateTimeField(null=True, blank=True) def __str__(self): return self.name class AdPrice(models.Model): ad = models.ForeignKey(Ad) name = models.CharField(max_length=50) price = models.DecimalField(max_digits=6, decimal_places=2) user_inserted = models.ForeignKey(User, null=True, blank=True, related_name='user_inserted_ad_price') date_inserted = models.DateTimeField(auto_now_add=True) user_updated = models.ForeignKey(User, null=True, blank=True, related_name='user_updated_ad_price') date_updated = models.DateTimeField(null=True, blank=True) def __str__(self): return self.name @classmethod def create(cls, ad_id, name, price, date_inserted, user_inserted_id): # Save price new_register = AdPrice(ad_id=ad_id, name=name, price=price, date_inserted=date_inserted, user_inserted=User.objects.get(id=user_inserted_id)) new_register.save() # … -
Unable to import a model into views.py file from models.py file in Django
I recently started with Django. While writing a basic web app, I am unable to import Album model into views.py file. I am using PyCharm IDE. While using objects.all() and DoesNotExit I couldn't see any suggestions from IDE after using dot operator. Album.ojects.all() is working in python shell. I am posting the error message and code spinets. Here is my views.py file. from django.shortcuts import render from django.http import Http404 from .models import Album def index(request): all_albums = Album.ojects.all() return render(request, 'music/index.html', {'all_albums':all_albums}) def detail(request, album_id): try: album = Album.objects.get(pk=album_id) except Album.DoesNotExist: raise Http404("Album does not exit") return render(request, 'music/detail.html', {'album':album}) here is my models.py file: from django.db import models class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) def __str__(self): return self.album_title + '-' + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) def __str__(self): return self.song_title index.html {% if all_albums %} <h3>Here are your albums</h3> <ul> {% for album in all_albums %} <li><a href="/music/{{ album..id }}">{{ album.album_title }}</a> </li> {% endfor %} </ul> {% else %} <h3>You dont have any albums </h3> {% endif %} detail.html {{ album }} Error msg -
Django urls is not working properly
I have a djnago project with a quiz app. So, when I specify the url like this in my main urls.py url(r'^quiz/', include('quiz.urls')), In the quiz urls.py works if I add prefix / in the pattern. Example: 1. This works but I dont want the prefix / urlpatterns = [url(r'^$', view=QuizListView.as_view(), name='quiz_index'), # These two patterns have / prefix which I don't want. url(r'^/(?P<slug>[\w-]+)/$', view=QuizDetailView.as_view(), name='quiz_start_page'), url(r'^/(?P<slug>[\w-]+)/take/$', view=QuizTake.as_view(), name='quiz_question')] 2. This does not works as I have removed the prefix /. urlpatterns = [url(r'^$', view=QuizListView.as_view(), name='quiz_index'), # These two patterns have / prefix which I don't want. url(r'^(?P<slug>[\w-]+)/$', view=QuizDetailView.as_view(), name='quiz_start_page'), url(r'^(?P<slug>[\w-]+)/take/$', view=QuizTake.as_view(), name='quiz_question')] Can anyone please tell why am I facing this issue? -
Selenium redirect error 404!=302 even when I have defined the view and url
I am following TDD web development with Python to learn Django and web development. Currently, I am having a problem with a test. I followed the book correctly but, I still get an unexpected assertion error by selenium. Traceback (most recent call last): File "/home/abhi/Development/DjangoDev/superlists/lists/tests.py", line 123, in test_redirects_to_list_view self.assertRedirects(response, 'lists/%d/' % (correct_list.id,)) File "/home/abhi/.local/lib/python3.5/site-packages/django/test/testcases.py", line 294, in assertRedirects % (response.status_code, status_code) AssertionError: 404 != 302 : Response didn't redirect as expected: Response code was 404 (expected 302) Here is the test which produces the error def test_redirects_to_list_view(self): other_list = List.objects.create() correct_list = List.objects.create() response = self.client.post( 'lists/%d/add_item' % (correct_list.id,), data = {'item_text': 'A new item for an existing list'} ) self.assertRedirects(response, 'lists/%d/' % (correct_list.id,)) urls, urlpatterns = [ url(r'^$', list_views.home_page, name='home'), url(r'^lists/(\d+)/$', list_views.view_list, name = 'view_list'), url(r'^lists/(\d+)/add_item$', list_views.add_item, name='add_item'), url(r'^lists/new$', list_views.new_list, name = 'new_list'), #url(r'^admin/', admin.site.urls), ] and my view def add_item(request, list_id): list_ = List.objects.get(id = list_id) return redirect('/lists/%d/' % (list_.id,)) any help is appreciated. Thank you! -
Image not displaying in template django
I have this app in which I need to display an image on the html template which is not happening. models.py class cateledetails(models.Model): cdid=models.IntegerField(unique=True,default=0) cid=models.ForeignKey(category,to_field='cid',on_delete=models.CASCADE) elename=models.CharField(max_length=20) imgsrc=models.ImageField(upload_to='elements/',blank=True) def __unicode__(self): return u"{} {}".format(self.cdid,self.elename) class Meta: db_table="cateledetails" views.py def mainpage(request): pic_details=get_object_or_404(cateledetails,pk=1) template=loader.get_template('student/mainpage.html') context={'pic_details': pic_details,} return HttpResponse(template.render(context,request)) urls.py urlpatterns= [ url(r'^mainpage/$',views.mainpage ,name='mainpage'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' mainpage.html {% block body %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <h4>What sound does it make?</h4> {% for image in pic_details.imgsrc_set.all %} <img src="{{ image.imgsrc.url }}" alt="image"> {% endfor %} </form> {% endblock %} what do I do? -
Will adding db.index=True to a Field in my Django Model help if there is no index on that field in the original db
I am reading this documentation : https://docs.djangoproject.com/en/1.7/topics/db/optimization/#use-standard-db-optimization-techniques and it says you should add indexes to fields that you frequently query using filter(), exclude(), order_by(). I agree with the statement but will this addition really help if there is no index on the actual database . -
Django ImageField Model: Get file path on upload_to callable
I have a Django admin field for uploading images, in my model I'm using a callable to get the FileField instance and Filename. My goal is to open the file the user is trying to upload and upload it to my Dropbox account through their API and return the URL where the image is saved. How do I get the full path for the file being uploaded? Here is what I currently have in my model: def upload_to_dropbox(self, filename): return DropboxStorage.store_file(self.image, filename) image = models.ImageField(upload_to=upload_to_dropbox) I tried using the ImageField's .url property but that returns my MEDIA_ROOT path, maybe I'm going about this the wrong way? -
nginx config : for websocket(django channels)
I'm using google Compute engine VM instance(OS : Ubuntu 16.04) I've tried to deploy django app using channels. andrewgodwin's multichat app. url I installed nginx and below is my config. 1) $ vim /etc/nginx/nginx.conf user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } 2) $ vim /etc/nginx/conf.d/default.conf server { listen 8000; server_name localhost; charset utf-8; #access_log /var/log/nginx/host.access.log main; location /stream { proxy_pass http://127.0.0.1:8443; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /static { alias /home/juhyun1849/Django/channels-examples/multichat/staticfiles; } location /media { alias /home/juhyun1849/Django/channels-examples/multichat/media; } location / { uwsgi_pass unix:/tmp/worker.sock; include uwsgi_params; } } 3) this is client side. <script> $(function () { // Correctly decide between ws:// and wss:// var ws_path = ("ws://" + window.location.host + "/stream"); console.log("Connecting to " + "/stream!"); var socket = new ReconnectingWebSocket(ws_path); socket.onopen = function () { ... }; socket.onmessage = function () { ... }; socket.onclose = function () { ... }; }; </script> 4) $ multichat/settings.py CHANNEL_LAYERS = { "default": { # This example … -
Jinja not executing HTML in Django Web Application: RuntimeError
I have created a web application called 'My_Website.' Inside this web application, there is a directory called 'My_Website'. In this directory, is the settings.py file, where I have already installed the Application I am using, called 'Home.' In my settings.py file (PycharmProjects/My_Website/My_Website/settings.py): INSTALLED_APPS = ( 'Home', 'Register', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) This is just the INSTALLED_APPS tuple. There is more in the file. In the directory PycharmProjects/My_Website/My_Website/urls.py, I have the following: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^Home/', include('Home.urls')) ] In the directory PycharmProjects/My_Website/Home/urls.py, I have the following: from django.conf.urls import url, include urlpatterns = [ url(r'^$', include('Home.urls')) ] Now, I am using Jinja templates, in the directory PycharmProjects/My_Website/Home/templates/home/ In this home directory there are 2 files: header.html and home.html header.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> {% block content %} {% endblock %} </div> </body> </html> home.html file: {% extends "home/header.html" %} {% block content %} <p>Hey!</p> {% endblock %} Here comes the problem. I am running this Web application in my localhost:8000 (Port 8000), and when I try to enter, it will not load the tag, and it gives me an … -
Distinguish API call from own app/webapp vs server
I am using Django and we are planning on opening some of our API for 3rd party usage. Till now we have been using DRF along with session authentication for our Django Web App and DRF with JWT for our Android application. What I would like to know is whether the call is from our own app (webapp/android app) or from 3rd party apps (they can call from their own applications, which can be other webapps/phone apps). Is there any way this can be distinguished? We want to count the no.of 3rd party API call to our server. -
admin page showing error in django
TypeError at /admin/student/user/ coercing to Unicode: need string or buffer, tuple found Any idea what's it about? admin.py from django.contrib import admin from .models import user class userAdmin(admin.ModelAdmin): fieldsets=[ (None,{'fields':['uid']}), (None,{'fields':['uname']}), (None,{'fields':['email']}), (None,{'fields':['password']}), ] admin.site.register(user,userAdmin) -
Django: Common/Reusable ModelAdmin Class
I have some functions like: has_delete_permission, has_add_permission, get_actions, formfield_for_foreignkey get_queryset Etc are the built-in ModelAdmin functions which I am using in almost all the ModelsAdmin's in my project. How to create a common/reusable class which include these functions and reuse in the other ModelAdmin classes? How to pass the reference of the Model or the ModelAdmin class to the common class? What should be the file structure to be maintained, in case this has to be used for many apps in a project. Some direction will be great help. Thanks. -
Changing session variable after views are rendered Django
I have two session variables that are required to be altered after rendering.When I try the following- def my_view(request) rend= render(request,"chat_page.html",{"answer":questions[request.session["stage"]]["instruction"]}) request.session["stage"]=request.session["stage"]+1 return rend I observe that first stagevariable is modified and then rendering is done.Is there a way that I can change value of stage after rendering is done. -
Django tests failing when run with all test cases
I have a problem with tests. When I run some tests I launch separately, they pass. When all together then fail. @mock.patch( 'apps.abstract.validators.years_range_is_not_future', new=fake_years_range_is_not_future ) def test_create_building_with_validation_of_foundation_period(self): self.c.login(username=self.user.username, password='111') response = self.c.post( '/en/api/buildings/', data={ 'name': "New Building", 'foundation_period': { 'lower': MIN_INT_VALUE, 'upper': MAX_INT_VALUE }, 'stream': { 'uuid': s_uuid(self.stream) } } ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) I read about this problem here why would a django test fail only when the full test suite is run? and tried to patch the validator in the serializer file as shown here @mock.patch( 'apps.buildings.api.serializers.years_range_is_not_future', new=fake_years_range_is_not_future ) def test_create_building_with_validation_of_foundation_period(self): .............................................................. but then I get an incomprehensible for me exception Error Traceback (most recent call last): File "/usr/lib/python3.5/unittest/mock.py", line 1049, in _dot_lookup return getattr(thing, comp) AttributeError: module 'apps.buildings.api' has no attribute 'serializers' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.5/unittest/mock.py", line 1149, in patched arg = patching.__enter__() File "/usr/lib/python3.5/unittest/mock.py", line 1205, in __enter__ self.target = self.getter() File "/usr/lib/python3.5/unittest/mock.py", line 1375, in <lambda> getter = lambda: _importer(target) File "/usr/lib/python3.5/unittest/mock.py", line 1062, in _importer thing = _dot_lookup(thing, comp, import_path) File "/usr/lib/python3.5/unittest/mock.py", line 1051, in _dot_lookup __import__(import_path) File "/home/env/project/apps/buildings/api/serializers.py", line 12, in <module> from apps.communities.api.serializers import CommunityBriefSerializer File "/home/env/project/apps/communities/api/serializers.py", line 297, in <module> … -
How to update a client-side page without js and jquery on django?
It is necessary to make a static application that uses a constant connection to the server to receive messages or updates the page in a period of time. With Django, python 2.7 and without js and jquery. -
django channels, celery and sockets: debug why data not sending
I need to send data via sockets so a user can get live update of the status of a background process. Here's a video of a simple working version: https://youtu.be/3561_VqQzRg (can provide code) and mine which works all the way till live feed where it fails: https://youtu.be/7FDaLkCRHpw I'm stuck with debugging but here's the code starting with javascript $('.test-parse').unbind().click(function() { parent = $(this).parent().parent(); var x = parent.find('.x').text(); var y = parent.find('.y').text(); var area_id = parent.find('.area').text(); if (area_id != '') { var area = areas[area_id]; } else { var area = null; } var cropped = $('.zoom-in').hasClass('btn-success'); if (cropped) { var img_url = $('#main-img-src').text(); } else { var img_url = $('.img-class').attr('src'); } var data = { 'x': x, 'y': y, 'image': img_url, 'width': $('.img-class').width(), 'height': $('.img-class').height(), 'color': parent.find('#color').css('background-color'), 'variance': parent.find('.color').val(), 'switch-color': parent.find('.switch-color').prop('checked'), 'new-color': parent.find('.color-code').val(), 'keep-perspective': parent.find('.perspective').prop('checked'), 'cls-id': parent.find('.cls-id').text(), 'area-id': area, 'grayscale': $('.gl-scale input').prop('checked'), } var unique_processing_id = ''; var task_id = ''; var csrftoken = $.cookie('csrftoken'); $.ajax({ url: "/start-render-part", type: "POST", dataType: 'json', beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier xhr.setRequestHeader("X-CSRFToken", csrftoken); … -
Why does docker-compose use ~60GB to build this image
When I start docker-compose build I have 60 gigs free. I run out of space before it finishes. Any idea what could possibly be going on? I'm running latest of Docker for Mac and docker-compose here's my docker-compose file: version: '3' services: db: image: postgres:9.6-alpine volumes: - data:/var/lib/postgresql/data ports: - 5432:5432 web: image: python:3.6-alpine command: ./waitforit.sh solr:8983 db:5432 -- bash -c "./init.sh" build: . env_file: ./.env volumes: - .:/sark - solrcores:/solr ports: - 8000:8000 links: - db - solr restart: always solr: image: solr:6-alpine ports: - 8983:8983 entrypoint: - docker-entrypoint.sh - solr-precreate - sark volumes: - solrcores:/opt/solr/server/solr/mycores volumes: data: solrcores: and my dockerfile for the "web" image: FROM python:3 # Some stuff that everyone has been copy-pasting # since the dawn of time. ENV PYTHONUNBUFFERED 1 # Install some necessary things. RUN apt-get update RUN apt-get install -y swig libssl-dev dpkg-dev netcat # Copy all our files into the image. RUN mkdir /sark WORKDIR /sark COPY . /sark/ # Install our requirements. RUN pip install -U pip RUN pip install -Ur requirements.txt This image itself when built is ~3 gigs. I'm pretty flummoxed. -
Django routing not working as expected
I know there should be a little thing that i missed. But I couldn't figure the problem out for ours. And I give up. Here is my root url conf: urlpatterns = [ url(r'^$', include('admin.urls')), ] And admin.urls file: urlpatterns = [ url(r'^$', views.index, name="index"), url(r'^user$', views.user, name='user'), ] When i hit "localhost/" index works great. But localhost/user (localhost/user/ too) is not working, i get 404 not found. admin is my application name so do not confuse it with django.contrib.admin. Django version :(1, 11, 5, 'final', 0) Python 3.6.2 -
docker nginx failed to make connection with web container
My docker nginx container failed to connect with gunicorn container. docker compose logs looks like, dj | [2017-09-16 12:37:14 +0000] [22] [INFO] Starting gunicorn 19.7.1 dj | [2017-09-16 12:37:14 +0000] [22] [DEBUG] Arbiter booted dj | [2017-09-16 12:37:14 +0000] [22] [INFO] Listening at: http://127.0.0.1:8000 (22) dj | [2017-09-16 12:37:14 +0000] [22] [INFO] Using worker: sync dj | [2017-09-16 12:37:14 +0000] [25] [INFO] Booting worker with pid: 25 dj | [2017-09-16 12:37:14 +0000] [22] [DEBUG] 1 workers ng | 2017/09/16 12:37:22 [error] 8#8: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.20.0.1, server: localhost, request: "GET /api HTTP/1.1", upstream: "http://127.0.0.1:8000/api/v1", host: "localhost" ng | 172.20.0.1 - - [16/Sep/2017:12:37:22 +0000] "GET /api HTTP/1.1" 502 537 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" "-" ng | 2017/09/16 12:37:31 [error] 8#8: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.20.0.1, server: localhost, request: "GET /admin HTTP/1.1", upstream: "http://127.0.0.1:8000/api/admin", host: "localhost" ng | 172.20.0.1 - - [16/Sep/2017:12:37:31 +0000] "GET /admin HTTP/1.1" 502 537 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" "-" If I make a curl request inside django container, it shows the relevant html text. $ … -
Unresolved library "staticfiles" - Pycharm Django
So, basically I can't access my static files because the {% load staticfiles %} tag gets highlighted with the "unresolved library" error message in my Pycharm project. I have django.contrib.staticfiles in my INSTALLED_APPS. My settings file: if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media") STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static", "static"), ) -
Status Code 405 while using google oauth2
I am using Django with Angular JS to access the Google Drive API. I am following this document from Google. The FLOW.step1_get_authorize_url() gives me the URL similar to the sample URL mentioned on the page. But the problem is that after return HttpResponseRedirect(authorize_url) the browser does not redirect to the authorize_url and gives the error as shown in the picture below (Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. The response had HTTP status code 405). But if I copy pasted the URL, it works fine. The oauth2 function looks like this. def index(request): FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope='https://www.googleapis.com/auth/drive', redirect_uri='http://127.0.0.1:8000/oauth2callback/' ) FLOW.params['access_type'] = 'offline' authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) And here is the oauth2callback function. def auth_return(request): credential = FLOW.step2_exchange(request.GET) return HttpResponseRedirect("/mycustomurl") I used this to enable CORS in the Django Server Side. Here is my part of service in Angular that makes the call to oauth2. (function () { 'use strict'; angular.module('myApp') .service('myService', function ($http) { this.saveToDrive = function (startYear, endYear, shape) { var config = { params: { start: '1999', end: '2002', action: 'download-to-drive' }, headers: { 'Access-Control-Allow-Origin': '*', 'X-Requested-With': null … -
Unsupported SRS when saving polygon in SRID=0 field
I'm trying to save a polygon with the default GeoDjango admin widget in an SRID 0 field. It gives an SRSException. I don't get what's wrong here, must there be a SRID for polygons to be saved? If so, is there a work around as I wish to save the coordinates of the polygon in raw simple CRS given in Leaflet (image overlay giving one pixel as one unit iirc) and using the default SRID changes the coordinates. What I'm trying to do is just a fake map with markers and polygons on it. -
filter company based on category
I was doing the project on Django to get into it more deeply. I have a problem in the model part. There is a model Company, Product, Category. Company is simply the introduction part. Product model is about what product a company has and its divided into category which is ManyToManyField. I have list all the categories in a page where if certain category is clicked then the list of companies that has product of that category should be filtered. But I don't know how to access it. Here is my model class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) class Product(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) company = models.ForeignKey('Company', related_name='products', blank=True, null=True, on_delete=models.SET_NULL) website = models.URLField(unique=True) slug = models.SlugField(unique=True) categories = models.ManyToManyField(Category, related_name='products') class Company(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) slug = models.SlugField(unique=True) description = models.CharField(max_length=400) editor = models.ForeignKey(User, related_name='company') # product = models.ForeignKey(Product, related_name='company') -
django redirect does not work
I wanted to have function that every time get the request and check that user is login and then return user object if user is login otherwise redirect to login , so this is what I tried to do def is_login(request): userID = request.session.get('mainSession', 0) next = resolve(request.path_info).url_name print(1) if userID != 0: print(2) user = msignup.objects.filter(id=userID).first() return user print(3) return HttpResponseRedirect(reverse('login') + "?next= {}".format(next)) I tried to test this function with below view when user is loged out and request has no mainSession : def email_activation(request): user = is_login(request) print(4) if req.method == 'GET': print(5) email = user.email return render(request, 'account/emailActivation.html',{'email': email}) return redirect('login') and in response I got this : 'HttpResponseRedirect' object has no attribute 'email' and the response for prints that I had made is : 1 3 4 5 why after 3 redirect does not happens ?what am I doing wrong?