Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Class-based Views in Django
I'd like to ask you if you can clear something up to me. I'm designing a web app powered by Django and I'm also learning about OOP as I go. From what understand main purpose of class-based views is to keep my code DRY. To avoid any repetitive or redundant code. I've tried to implement class-based views however at the end I always ended up tossing everything into function-based view 'coz all the views are fairly unique. When I looked over the views I asked myself: "Does your code repeat anywhere ?" Answer was no. The question is: Despite using classed-based views being considered to be the best coding practice it's not always possible. Am I right ? -
PrimaryKeyRelatedField does not include value in validated_data
I'm creating a serializer that is suppose to create an object on a POST request. However when run serializer.validated_data it does not include currency in the QueryDict. if i for instance change from PrimaryKeyRelatedField to IntegerField it includes it, but that is not optimal when it is suppose to point to a record in another table. Why is it that currency is not being included in validated_data when i use PrimaryKeyRelatedField? serializer class InvoiceSerializer(serializers.ModelSerializer): deposit_amount = serializers.FloatField() receive_amount = serializers.FloatField() currency = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: """Meta class to map serializer's fields with the model fields.""" model = Invoice fields = ('task', 'deposit_amount', 'receive_amount', 'currency') read_only_fields = ('created_at', 'updated_at', 'currency') def create(self, validated_data): return Invoice.objects.create(**validated_data) When i call request.data in my viewset it returns: {'currency': 2, 'task': 1, 'deposit_amount': 2.01, 'receive_amount': 118652.7} however when i return serializer.validated_data: OrderedDict([('task', 1), ('deposit_amount', 2.01), ('receive_amount', 118652.7)]) -
django modelform booleanfield not appearing as required
I'm trying to render a modelform which has a booleanfield from the model (with yes, no choices) that fails to appear as default (what I thought was the default). the model field is: BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) same_address = models.BooleanField(choices=BOOL_CHOICES) And used in the form via (and not altered in the form constructor or elsewhere): .... class Meta: model = Address fields = [ 'same_address', ] -
MultiValueDictKeyError Django 1.8
I am trying to import a file using forms.py. This code is the same code I used in another model and it worked, but this time it gives me this error: MultiValueDictKeyError at /importraw Exception Value: "u'rawname'" These are the snippets of code you need to know about: Views.py def importraw(request): form = UploadRaw(request.POST, request.FILES) if form.is_valid(): raw = Raw(title=request.POST['rawname'], file='raw_files/' + request.POST['file']) raw.save() handle_uploaded_raw(request.FILES["file"], request.POST["name"]) raw.save() return redirect('/importations') Urls.py: url(r'^importraw$', views.importraw), Models.py: class Raw(models.Model): title = models.CharField(max_length=200) file = models.FileField(upload_to='raw_files') uploaded_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.name Index.html <!--IMPORT--> <div class="col-md-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Importer un fichier brut</h3> </div> <div class="panel-body"> <form class="form-horizontal" action="/importraw", method="post"> {% csrf_token %} <fieldset> <div class="form-group"> <label for="name" class="col-lg-4 control-label">Structure</label> <div class="col-lg-6"> <select name="id" id="id" class="struct form-control"> {% for structure in structures %} <option value="{{ structure.name }}">{{ structure }}</option> {% endfor %} </select> </div> </div> <div class="form-group"> <label for="file" class="col-lg-4 control-label">Nom du fichier brut</label> <div class="col-lg-6"> <input type="text" name="rawname" id="rawname" class="form-control"> </div> </div> <div class="form-group"> <label for="file" class="col-lg-5 control-label">Fichier brut</label> <div class="col-lg-6"> <input type="file" name="file" id="file"> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2" align="center"> <button type="submit" value="Create" class="btn btn-primary">Importer</button> </div> </div> </fieldset> </form> </div> … -
Django URL and making a portion of it optional, but using the same class API View
So I have this API URL on the back-end and I am wondering how to make a portion of it optional. url(r'^api/documents/(?P<id>[0-9]+)$', GetDocumentsAPIView.as_view(), name='documents'), So two things can happen coming from the front-end. 1) When the user logs in, it brings them to the /home which lists all of their projects. Clicking on the project brings them /documents/85 where the number is the number of the project and it lists all the documents for that project. This is sent to the API URL /api/documents/85. This much is working fine. 2) The other option is the user will just click on a Documents link in the navbar, which will just bring them to /documents. This should just go to the API URL /api/documents/ and eventually onto the serializer.py where their most recent project is determined and the documents for that are returned and rendered in the front-end This I can't get working. Not sure if I can do it with just one url(), or if I need two. Was hoping the one I posted would look at the (?P<id>[0-9]+)$ as optional and if nothing was there would return the same GetDocumentsAPIView, but this is not the case. -
Django Rest Framework JWT Unit Test
I am using DRF with the JWT package for authentication. Now, I'm trying to write a unit test that authenticates itself with a JWT token. No matter how I try it, I can't get the test API client to authenticate itself via JWT. If I do the same with an API client (in my case, Postman), everything works. This is the test case: from django.urls import reverse from rest_framework.test import APITestCase from rest_framework_jwt.settings import api_settings from backend.factories import member_factory jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER class MemberTests(APITestCase): def test_get_member(self): member = member_factory() payload = jwt_payload_handler(member.user) token = jwt_encode_handler(payload) self.client.credentials(Authorization='JWT {0}'.format(token)) response = self.client.get(reverse('member-detail', kwargs={'pk': member.pk})) assert response.status_code == 200 But I always get a 401 Authentication credentials were not provided. In response.request I see the token is there, it's just not being applied I guess. If I rewrite the test to use rest_framework.test.RequestsClient and actually send it to the live_server URL, it works. Any help on this? -
How to send a django signal from other signal
I'm currently developing a library for django that requires a lot of comes and goes with the post_save signal in django and I was wondering if it's possible to trigger another signal after the post_save so I could implement my own and not intervene the post_save in case a project that uses the library needs to do it. So far I know that signals are expected to receive a class as a sender argument, and if I trigger manually the signal from the post_save I would be doing nothing (I'd still be intervening it). Is there any workaround for this? Am I missing something in the docs? TL;DR I need a way to trigger a custom signal after the post_save signal, automatically, is there any way of doing it? -
Can't install stream-django
When I try and install getstream for the django framework, I get an error. Warning: GMP or MRIP library not found: Not Building Crypto.PublicKey._fastmaths I have already installed Visual C++ build tools. -
Using a frontend JS framework with Django
I am looking to start a SPA project that will be data intensive. I am comfortable with Django and decided to use it for this project. I want to use a javascript technology to handle the front end and essentially replace the django templates. I know this is possible as I've seen people discuss integrating Angular/Vue/React with Django. I have yet to see discussion on which one is best. The two major factors: 1. relatively easy to learn 2. quick to implement Is there a general consensus on this? Thanks -
Dynamic Chart using django and Chart.js
Hi Guys I have a question or a request that I do not really know how to achieve. I am using chart.js in my django app in order to retrieve data and render it in great graphs. I followed the tutorial and I managed to make it work but I would like my chart to add dataset dynamically. I would like to create a radar chart showing data from a team of x numbers. I created a test for a team of 2 people manually HTML/Script: labels_list = data.labels info_data1 = data.data1 info_data1 = data.data2 var radar1 = { labels: labels, datasets: [{ label: "Team-member1", fillColor: "rgba(255,255,255,0)", strokeColor: "rgba(63,169,245,1)", pointColor: "rgba(63,169,245,1)", pointStrokeColor: "#fff", data: info_data1 }, { label: "Team-member2", fillColor: "rgba(255,255,255,0)", strokeColor: "rgba(102,45,145,1)", pointColor: "rgba(102,45,145,1)", pointStrokeColor: "#fff", data: info_data2 }] } views.py: def get(self, request, format=None, *args, **kwargs): team_member_list = Project.objects.get(id=kwargs['pk']).team_id.members.all() labels = ["Janv","Fev","March","April","May"] data1 = [35,56,45,34,25] data2 = [43,41,56,28,45] data = { "labels":labels, "data1":data1, "data2":data2 } return Response(data) How can I create the same kind of graph for X team members using dynamic data ?? ps: I just want to understand the logique.. so if someone can help me to render dynamically the dataset label (now "team member1/2") it … -
Customizing permissions and responses for detail routes in Django rest framework
Overview - I am creating a Django REST API that returns data from nested url routes. The best way I have found to do this so far is by manually adding in the url regexes to the urls.py and then using @detail_route in my views to retrieve the filtered serializer data. Right now I have user objects and goal objects that will need different data responses based on authentication, etc... How do I customize the detail routes to do this? For example: If a user is an admin they can use the 'post' method at the /api/v2/users url. If they are not authenticated they get a bad request 400 response. If a user is an admin they can use the 'get' method to retrieve all users names, emails, and passwords, but if they are not they can only get usernames. urls.py urlpatterns = [ url(r'^api/v2/users/$', UserViewSet.as_view({'get': 'users', 'post': 'users', 'put': 'users', 'patch': 'users', 'delete': 'users'}), name='user_list'), url(r'^api/v2/user/(?P<uid>\d+)/goals/$', UserViewSet.as_view({'get': 'user_goals', 'post': 'user_goals', 'put': 'user_goals', 'patch': 'user_goals', 'delete': 'user_goals'}), name='user_goals_list'), ] serializers.py class GoalSerializer(serializers.ModelSerializer): class Meta: model = Goal fields = ('id', 'user_id', 'name', 'amount', 'start_date', 'end_date', ) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'id', 'password') read_only_fields … -
How to safely give an object the next highest value in a model - Django
I want to assign a position parameter to each user created in my Django app. The position is modified at various points down the line, however when a user is created I need the position parameter to be set to the next highest value. The model is as follows: from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User) position = models.PositiveIntegerField(null=False, default=0, unique=True) At the moment I am assigning this parameter as follows: user_count = User.objects.all().count() new_user = User() new_user.profile.position = user_count + 1 new_user.save() Clearly if two users are registered at the same time, then there is a potential for them both to get the same value of user_count assigned, if that occurs before the save is made. Given the uniqueness constraint this would raise an error, but I'm not sure how to resolve it safely. How should I do this to ensure uniqueness (and deal with any unique conflicts that might arise)? -
Django testing function with request.user
I'm trying to write a test for a custom function in my Django model and having some issues. The function works correctly tested manually so this is a test code issue. I have read all the related questions on this but they have not solved my problem. I am using pytest. Code examples below: models.py - I want to test this function def save(self, *args, **kwargs): if self.in_progress: MyModel.objects.filter(user=request.user, flag=True).update(flag=False) super(MyModel, self).save(*args, **kwargs) tests.py class MyTest(TestCase): def setUp(self): self.factory = RequestFactory() self.user = UserFactory.create() def test_that_works(self): request = self.factory.get('/mypage/') request.user = self.user response = my_view(request) self.assertEqual(response.status_code, 200) def test_that_doesnt_work(self): request = self.factory.get('/') request.user = self.user myitem = MyModelFactory.create() myitem.flag = True myitem.save() assert myitem.flag is True When I run these tests, the first test works, but the second says NameError: global name 'request' is not defined The full traceback makes it clear that it is getting to myitem.save() in the test and the error is something to do with passing the request.user into the save() function. Can anyone help please? -
Django: url in "form action" doesn't work
In html: <form id="answer_form" class="form-horizontal" action="{% url 'puzzle:update' puzzle.id %}" method="POST" onSubmit="return ValidateAnswer();"> {% csrf_token %} <p>Please entry your answer below: (Case insensitive)</p> <div class="form-group col-xs-12"> <input id="player_answer" maxlength="30" name="player_answer" type="text"> </div> <div class="form-group col-xs-12"> <button id="submit_answer_btn" class="btn btn-success" type="submit">Submit</button> </div> </form> In url.py app_name = 'puzzle' urlpatterns = [ url(r'^(?P<pk>[0-9]+)/$', login_required(views.PuzzleDetailView.as_view()), name='detail'), url(r'^(?P<puzzle_id>[0-9]+)/update/$', views.update_user_game_history, name='update'), ] In views.py class PuzzleDetailView(DetailView): model = Puzzle template_name = 'puzzle/detail.html' def update_user_game_history(request, puzzle_id): player_game_history = PlayerGameHistory.objects.get(user=request.user) solved_puzzle = Puzzle.objects.get(id=puzzle_id) player_game_history.score += solved_puzzle.point player_game_history.save() return HttpResponseRedirect('/') What I am trying to do is to click on Submit button, via 2nd url, go to the update_user_game_history function in views.py. However, everytime I submit, the flow tries to, via 1st url, go to the PuzzleDetailView. And I get Method Not Allowed (POST): /2/ in terminal -
Django dynamic form values not storing
def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) // user = authenticate(username=username, password=password) if form.is_valid(): form.save() token = jwt.encode({'user_id': user.id}, SECRET_KEY) My query is how do I store form details from this just created dynamic form unlike under: def login_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) -
ImportError: No module named 'datasets'
I'm using inception_v3 inside my django app. I have cloned this repository "https://github.com/tensorflow/models.git" and have made a incep.py file and written a function **generator():** as instructed on this link: "https://github.com/tensorflow/models/blob/master/research/slim/slim_walkthrough.ipynb" have changed the inception_v1 to v3 in the code. when called the incep.py returns the tags generated from the given image. i have cloned the git repository inside my django app folder and have also made a incepTest.py file where i'm calling the incep.py file. I'm facing the error "ImportError: No module named 'datasets'". I have already tried the solutions provided here: "ImportError: No module named datasets" but i'm still getting the error of no module named 'datasets'. i have imported the incep.py file as follows: from models.research.slim.incep import generator Also i have placed a blank init.py file in every working folder of models. Any help would be helpful. -
Data access between application Django / Cart - Products
Hi guys I have a question. I am trying to implement Cart application in my simple online shop. I created a cart model with ManyToManyField(Product, blank=true). Now, I want to access all the products, from the CartManager Level. cart_obj.products.all(), but it display empty query set :(. When in my admin site cart contains 3 items. I tested function all(), which is in ProductManager class, and it works fine in "Product" application. CartModel: from django.conf import settings from django.db import models from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): #creates new cart or gets cart based on the session #example: user was logged off added to the cart then he logs in # app will automatically updates this cart and assign it to the user def new_or_get(self, request): cart_id = request.session.get('cart_id', None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = self.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): print(user) user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) # Create your models here. class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) products … -
Bad Request when deploying Django app on heroku
I just completed my first Django app and having extreme troubles deploying it on Heroku. I had to set DISABLE_COLLECTSTATIC=0. Procfile web: gunicorn linky.wsgi:application --log-file - WSGI_APPLICATION = 'linky.wsgi.application' 2017-11-30T12:36:14.432878+00:00 app[api]: Release v1 created by user namangupta111@gmail.com 2017-11-30T12:36:14.432878+00:00 app[api]: Initial release by user namangupta111@gmail.com 2017-11-30T12:36:14.620376+00:00 app[api]: Release v2 created by user namangupta111@gmail.com 2017-11-30T12:36:14.620376+00:00 app[api]: Enable Logplex by user namangupta111@gmail.com 2017-11-30T12:36:53.000000+00:00 app[api]: Build started by user namangupta111@gmail.com 2017-11-30T12:36:53.000000+00:00 app[api]: Build failed -- check your build logs 2017-11-30T12:40:30.000000+00:00 app[api]: Build started by user namangupta111@gmail.com 2017-11-30T12:40:30.000000+00:00 app[api]: Build failed -- check your build logs 2017-11-30T12:42:38.000000+00:00 app[api]: Build started by user namangupta111@gmail.com 2017-11-30T12:42:38.000000+00:00 app[api]: Build failed -- check your build logs 2017-11-30T12:45:35.467417+00:00 app[api]: Release v3 created by user namangupta111@gmail.com 2017-11-30T12:45:35.467417+00:00 app[api]: Set DISABLE_COLLECTSTATIC config vars by user namangupta111@gmail.com 2017-11-30T12:45:45.000000+00:00 app[api]: Build started by user namangupta111@gmail.com 2017-11-30T12:47:42.708932+00:00 app[api]: Attach DATABASE (@ref:postgresql-solid-33244) by user namangupta111@gmail.com 2017-11-30T12:47:43.038119+00:00 app[api]: Release v5 created by user namangupta111@gmail.com 2017-11-30T12:47:42.708932+00:00 app[api]: Release v4 created by user namangupta111@gmail.com 2017-11-30T12:47:43.038119+00:00 app[api]: Deploy a591e78d by user namangupta111@gmail.com 2017-11-30T12:47:43.061780+00:00 app[api]: Scaled to web@1:Free by user namangupta111@gmail.com 2017-11-30T12:45:45.000000+00:00 app[api]: Build succeeded 2017-11-30T12:47:56.253034+00:00 heroku[web.1]: Starting process with command `gunicorn linky.wsgi:linkey --log-file -` 2017-11-30T12:47:58.504110+00:00 heroku[web.1]: Process exited with status 127 2017-11-30T12:47:58.443015+00:00 app[web.1]: bash: gunicorn: command not found 2017-11-30T12:47:58.521776+00:00 heroku[web.1]: … -
django-admin runserver throws error
I have installed Django==1.10.0 pymongo==2.7.1 MongoDB 2.6 Python==2.7 six==1.10.0 MongoDB 2.6 mongoengine==0.9.0 in mysite/mysite/settings.py i have, # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { #'ENGINE': 'django_mongodb_engine', 'ENGINE': 'django.db.backends.dummy', 'NAME': 'test', 'USER': 'admin', 'PASSWORD': 'smmis@123#', } } #start AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', ) from mongoengine import * connect('test') # connect('test', host='mongodb://127.0.0.1', port=50226) #end when i run django-admin runserver it throws error Traceback (most recent call last): File "/opt/VirEnv_p2.7/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/core/management/base.py", line 317, in run_from_argv connections.close_all() File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/db/utils.py", line 229, in close_all for alias in self: File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/db/utils.py", line 223, in __iter__ return iter(self.databases) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/db/utils.py", line 156, in databases self._databases = settings.DATABASES File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/opt/VirEnv_p2.7/lib/python2.7/site-packages/django/conf/__init__.py", line 116, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Even though SECRET_KEY = '9&q3vm=wpl3&r_8vgqch3*$+h*kp+urol&z=!gk*79lhwvjx' in mysite/settings.py What am i missing i am new to Django -
django form - raising specific field validation error from clean()
I have a validation check on a form which depends on more than one field, but it would be good to have the validation error show the user specifically which fields are causing the issue, rather than just an error message at the top of the form. (the form has many fields so it would be clearer to show specifically where the error is). As a work around I tried to create the same validation in each of the relevant fields clean_field() method so the user would see the error next to those fields. However I only seem to be able to access that particular field from self.cleaned_data and not any other? Alternatively is it possible to raise a field error from the forms clean() method? Attempt 1: def clean_supply_months(self): if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_months'): raise forms.ValidationError('Please specify time at address if less than 3 years.') def clean_supply_years(self): if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_years'): raise forms.ValidationError('Please specify time at address if less than 3 years.') def clean_same_address(self): ..... -
Redirect not working django
I've a problem about Django URL-redirection. The structure of the code is the following : The reactor view displays an HTML page with a list of elements. When clicking on one of them, an ajax request is done to the view. The ajax request is calling an another view with necessary informations The measurementReactor is called and displays details about one reactor. All functions are correctly called, the GET request is done but the page doesn't redirect in browser... Http requests #urls.py urlpatterns = [ url(r'^reactors/$', views.reactors, name = 'reactors'), url(r'^measurements/reactor/$', views.measurementReactor, name='measureReact'), ] #views.py @login_required def reactor(request): if request.method == "POST" and request.is_ajax(): if request.POST.get('type') == "measurement" : return redirect('/measurements/reactor/?ref='+request.POST.get('id')) @login_required def measurementReactor(request): reactobj = reactor.objects.get(id=request.GET['ref']) query = measurements.objects.filter(id_reactor=reactobj.id) return render(request, "measureReact.html",{"query":query}) #reactor.js var table1 = $('#datatable').DataTable(); $('#datatable tbody').on('click', 'tr>th:not(.controls.mdl-data-table__cell--non-numeric)', function () { var data = $(this).parent().find("[name=pk]").text(); $.ajax({ type : "POST", data : {'csrfmiddlewaretoken' : csrftoken, 'id':data, 'type':"measurement"}, }); }); -
Deploying django app to production server, should I include environment (env) in git clone?
I have a working django app running on mý localhost. It is running inside a virtual environment. No I want to deploy the same project into a Google Compute Engine. For that I have a question. After I set up the production server including starting the virutal environment with vritualenv env do I need to clone in the project code from git including the env directory or only the source code including manage.py? The process is described differently and so it is a bit confusing. Main problem is the clarity of deploying the django app to production and the virtual environment setup using git for the code transfer. Thank you for flow explanation. -
Django hello world page not found on virtual machine OPENSTACK
The problem is that I test the django helloworld in two virtual (ubuntu server) machine. one's virtual ip is xxx.xxx.xxx.xxx(example 123.4.5.6), physical ip is yyy.yyy.yyy.yyy(example 9.87.6.5), another is xxx.xxx.xxx.xxx(example 123.4.5.7) physical ip is yyy.yyy.yyy.yyy(example 9.87.6.4), all these are static "virtual ip" and static ip The problem is, while loading the page of the first django helloworld, everything is fine (this two helloworld are same code and independent to each other), but when I try building the second django helloworld and connect to the server it said Page not found (404) Request Method: GET Request URL: http://9.87.6.4/http:/9.87.6.4/ {'path': 'http://9.87.6.4/'} You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. and the server debugger said Performing system checks... System check identified no issues (0 silenced). November 30, 2017 - 12:13:18 Django version 1.11.7, using settings 'helloworld.settings' Starting development server at http://123.4.5.7:80/ Quit the server with CONTROL-C. Not Found: /http:/9.87.6.4:80/ [30/Nov/2017 12:13:19] "GET http://9.87.6.4:80/ HTTP/1.1" 404 1666 Notice that there's an extra http:/9.87.6.4/ in the Request URL I have tried reinstall the apache2 (but most likely it is not related to apache2 but to the virtual … -
Angular V5 with Django rest framework url not laoding
I am working on Angular5 with Django rest framework. I am trying to integrate the Django url with angular5. it is working only for index page. and if we change the state by clicking on any Button its working good but on page load it showing "Page not found (404)". The url for index page is: url(r'^$',TemplateView.as_view(template_name="index.html"),name="index") -
View not returning an HttpResponse object
def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() token = jwt.encode({'user_id': form.cleaned_data.get( 'username').id}, SECRET_KEY) return HttpResponse(request, {'token': token.decode( "utf-8")}) This logic forms a part of my back-end that has to send response to front-end (just being explicit). But the error being thrown is: The view core.views.signup_view didn't return an HttpResponse object. It returned None instead. Please help me.