Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django error: unrecognized arguments:
I'm using django with VB Linux Red Hat. I've tried using the command "python manage.py runserver - 192.168.1.100:8000" in order to get access to my website. It worked fine until now, but then it showed me this message: manage.py runserver: error: unrecognized arguments: 192.168.1.100:8000" I think it has something to do with the settings.py file, I can't remember what exactly I've changed there. Here is the content of the settings.py file: """ Django settings for mysite project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o-g4ql*yum(+ollra+t%1x)$svtr!sd7mrcv=lj@_p&hrbq_&z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = ['192.168.1.100'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'mysite.urls' WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, … -
Django best practice on relative path from an AJAX request
I am currently failing at trying to read a CSV file stored in my django static repository from an AJAX request. Failed to load resource: http://127.0.0.1:8000/static/users/feedbacks/data.csv the server responded with a status of 404 (Not Found) Is there a best practice for this to work properly as well in production? here is the js: if (replayCSV){ $(document).ready(function() { $.ajax({ type: "GET", url: "/static/users/feedbacks/data.csv", dataType: "csv", success: function(data) {readData(data);} }); console.log(dataToRead); }); } And my django project structure looks like: main_repository -... -project_folder --app_folder ---static ----js -----therequest.js static_repository -static --users ---feedbacks ----data.csv -
Django rest api: How to handle method object has no attribute 'COOKIES' error
I have a django api. I want to enforce it to have csrf cookie using @ensure_csrf_cookie but I get error using this curl command: curl -i -c -H 'Accept: application/json; indent=4' -H 'Content-Type:application/json' -H 'Referer:https://dev.ga.coach' -X POST https://mydomain/users/:register/ -d "id=222111&firstname=zinonas&yearofbirth=2007&lastname=Antoniou&othernames=" The error is: File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py" in _wrapped_view 141. result = middleware.process_request(request) File "/usr/local/lib/python3.5/dist-packages/django/middleware/csrf.py" in process_request 205. csrf_token = self._get_token(request) File "/usr/local/lib/python3.5/dist-packages/django/middleware/csrf.py" in _get_token 177. cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME] Exception Type: AttributeError at /users/:register/ Exception Value: 'ApiUserRegister' object has no attribute 'COOKIES' My class in views.py is: class ApiUserRegister(APIView): authentication_classes = (BasicAuthentication,) permission_classes = () serializer_class = RegisterUserSerializer @method_decorator(csrf_exempt) @ensure_csrf_cookie def post(self, request): serializer = RegisterUserSerializer(data=request.data) # Check format and unique constraint serializer.is_valid(raise_exception=True) data = serializer.data token = get_token(request) if User.objects.filter(id=data['id']).exists(): user = User.objects.get(id=data['id']) is_new = "false" resp_status = status.HTTP_200_OK else: user = User.objects.create(id=data['id'], firstname=data['firstname'], yearofbirth=data['yearofbirth'], lastname=data['lastname'], othernames=data['othernames']) user.save() is_new = "true" resp_status = status.HTTP_201_CREATED resp = {"user": serializer.get_serialized(user), "isnew": is_new, "csrftoken": token} return Response( resp, status=resp_status, headers = {"X-CSRFToken":token, "Referer":"https://mydomain/users/:register/"}) In settings.py I have: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( #'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( #'rest_framework.authentication.SessionAuthentication', #'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ) } -
Embedding Tableau into Django Project
I am currently trying to connect Django with Tableau to use Tableau as a reporting unit to my (data input) Django project. Unfortunately I wasn't able to find anything on the web. Does anyone have experience to bridge Django and Tableau? Is it possible to share one Log-In or even pass User-Restriction information from Django to Tableau? Many thanks in advance for the help! -
Django Model form with a hidden field won't pass validation
When I have a field which is hidden but specified in the modelform, it fails to pass validation. The below form fails to pass validation for the postcode field, even though I pass in the postcode data in the constructor. How do I attach data to it to pass validation correctly so that it can save? eg class SupplyAddressForm(forms.ModelForm): full_address = forms.ChoiceField() def __init__(self, postcode, *args, **kwargs): super().__init__(*args, **kwargs) raw_addresses_data = get_full_address(postcode) addresses = raw_addresses_data['data']['addresses'] ........... self.fields['postcode'].initial = postcode def save(self, commit=False): address = super().save(commit=False) cd = self.cleaned_data full_address = cd['full_address'] full_address = json.loads(full_address) ...... return address class Meta: model = Address fields = [ 'supply_months', 'supply_years', 'postcode', 'residential_status', ] widgets = { 'postcode': forms.HiddenInput } -
Tests ran in gitlab-ci fail as Postgres can't been seen
Tests using gitlab-ci in docker fail as the Postgres service in not accessible. In my dev environment, I run tests successfully with: $docker-compose -f local.yaml run web py.test But in gitlab, the command - docker run --env-file=.env_dev $CONTAINER_TEST_IMAGE py.test -p no:sugar in the gitlab-ci.yaml file fails with: 9bfe10de3baf: Pull complete a137c036644b: Pull complete 8ad45b31cc3c: Pull complete Digest: sha256:0897b57e12bd2bd63bdf3d9473fb73a150dc4f20cc3440822136ca511417762b Status: Downloaded newer image for registry.gitlab.com/myaccount/myapp:gitlab_ci $ docker run --env-file=.env $CONTAINER_TEST_IMAGE py.test -p no:sugar Postgres is unavailable - sleeping Postgres is unavailable - sleeping Postgres is unavailable - sleeping Postgres is unavailable - sleeping Postgres is unavailable - sleeping Basically, it cannot see the Postgres service. The text Postgres is unavailable - sleeping comes from an entrypoint.sh file in the Dockerfile Below are some relevant files: gitlab-ci.yml image: docker:latest services: - docker:dind stages: - build - test variables: CONTAINER_TEST_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME before_script: - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY build: stage: build script: - docker build --pull -t $CONTAINER_TEST_IMAGE --file compose/local/django/Dockerfile . - docker push $CONTAINER_TEST_IMAGE pytest: stage: test script: - docker pull $CONTAINER_TEST_IMAGE - docker run --env-file=.env_dev $CONTAINER_TEST_IMAGE py.test -p no:sugar when: on_success Dockerfile: # ... other configs here ENTRYPOINT ["compose/local/django/entrypoint.sh"] entrypoint.sh: # ..... other configs here export DATABASE_URL=postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@postgres:5432/$POSTGRES_USER function postgres_ready(){ … -
Submiting variable number of forms in Django
So I'm working on a web-based process simulator for a steel pickling plant. I have 6 different types of forms (from 6 different Models) on the same template, which should be all submitted by the same button. Here are the models that matter to my question: class Settings(models.Model): simulation = models.ForeignKey(Simulation, on_delete=models.CASCADE) final_time = models.IntegerField(default=3000) time_steps = models.IntegerField(default=50) film_thickness = models.FloatField(default=0.001) plate_thickness = models.FloatField(default=0.0005) plate_width = models.FloatField(default=10.0) number_of_pickling_tanks = models.PositiveSmallIntegerField(default=4) number_of_rinsing_tanks = models.PositiveSmallIntegerField(default=4) coil_temperature = models.FloatField(default=373.0) system_pressure = models.FloatField(default=100000.0) total_vaporization = models.FloatField(default=0.005) plate_velocity = models.FloatField(default=3.0) class PicklingTank(models.Model): settings = models.ForeignKey(Settings, on_delete=models.CASCADE) number = models.PositiveSmallIntegerField() volume = models.FloatField(default=30) concentration_hcl_initial = models.FloatField(default=180.84) concentration_fecl2_initial = models.FloatField(default=11.35) concentration_fecl3_initial = models.FloatField(default=5.81) temperature_initial = models.FloatField(default=323.15) hasextinlet = models.BooleanField(default=False) All of these are made forms as in: class SettingsForm(forms.ModelForm): class Meta: model = Settings fields = '__all__' class PicklingTankForm(forms.ModelForm): class Meta: model = PicklingTank fields = '__all__' I've already done my research on how to submit several forms with one button only (django submit two different forms with one submit button), but my problem is quite different: the number of PicklingTankForms changes dynamically depending on the value the user inputs in Settings.number_of_pickling_tanks (I am rendering one instance of the PicklingTankForm using my views.py and replicating it "on … -
Django POST handler receives different JSON than what I send
I have a Django POST handler like this: class FooListView(View): def post(self, request): fields = request.POST foo = self.Foo.objects.create(**fields) json = serializers.serialize('json', [foo]) return JsonResponse(json, safe=False) And a unit test like this: class FooTests(TestCase): def setUp(self): self.url = '/foo/' self.fields = {'foo': 'bar'} def test_post_data(self): response = self.client.post(self.url, data=self.fields) data = json.loads(response.json()) self.assertEqual(self.fields, data[0]['fields']) In IntelliJ, I set a break point on the first lines of test_post_data() and post(). Inspecting self.fields in test_post_data() shows the dict that I set it to. But then when I inspect fields in post(), it's value is <QueryDict: {'foo': ['bar']}>. I see the correct key in this QueryDict, but now the value is a list containing the string that I sent from the test. Why is the value changed from what I sent? p.s. My model is like this: class Foo(models.Model): foo = models.CharField(max_length=25) -
redefine options metadata documentation in a @detail_route method
Im trying to redefine the @detail_route documentation end point to make a better explanation of the method that I had, This is my views.py class SomeModelViewSet(viewsets.ModelViewSet): """ This is the documentation of SomeModel viewset, and its visible from the navigator, I also can edit some things as shown here http://www.django-rest-framework.org/topics/documenting-your-api/#self-describing-apis """ queryset = SomeModel.objects.all() serializer_class = SomeModelSerializer @detail_route(methods=['GET']) def somemethod(self, request, pk=None, *args, **kwargs): # pk= None """ I want that this documentation where shown in the API GUI in the navigator as shown here http://www.django-rest-framework.org/api-guide/routers/#example """ return Response({'name': 'some response')}) the problem its that I can't find the way to edit that description or options, when i access to mydomine.com/somemodel/1/somemethod I've got Api Root > SomeModel List > SomeModel Instance > SomeModel Options = {"name": "SomeModel", "description": "This viewset automatically provides `list`, `create`, } I want to have something like Api Root > SomeModel List > SomeModel Instance > somemethod Options = {"name": "somemethod", "description": "this is the description that i want to edit" } It's there a way to make that? should I define a new metadata ? Thanks !! -
Django - Createview form_valid object.id error
I'm trying to create a form where the object created (a project) has a relationship with another model (the channel). The problem is I can't workout how to call the channel's primary key for the project's relationship. Models.py: class Project(models.Model): channel = models.ForeignKey( 'Channel', on_delete=models.CASCADE, ) Views.py: class ProjectCreate(CreateView): model = Project fields = ['name', 'description'] def form_valid(self, form): Project = form.save(commit=False) form.instance.channel = Channel.objects.get(id=self.kwargs['channel']) Project.channel = channel return super(ProjectCreate, self).form_valid(form) I think something else needs to be added to the forms.py file as well: Forms.py: class ProjectForm(forms.Form): name = forms.CharField(max_length=50) description = forms.CharField(widget=forms.Textarea) -
Seo for hidden anchor tags
I have a very simple doubt, does google seo or other seos recursively crawl hidden hyperlink tags. I googled but could not find any solution. Any experience or any lead will be helpful. -
error "The current path, user_info/, didn't match any of these."
Well, this question has been asked by many users, and I have tried some of the resolution provided in the query, but that doesn't seem to resolve my issue, maybe I am doing some other mistake. I am trying to create a simple user registration/login/logout forms SchoolnSkill ---Project name, and below is the SchoolnSkill/url details:- from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^user_info/', include('user_info.urls')), ] user_info--App name, and the user_info/url details are below:- from django.conf.urls import url from . import views urlpatterns = [ # url(r'^$', views.index, name='index'), url(r'^registration/', views.UserFormView, name='registration') ] My views.py output is as below:- from django.shortcuts import render, redirect from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from django.contrib.auth import authenticate, login from django.views import generic from .models import Registration from django.views import View from .forms import UserForm class UserFormView(View): #from_class = UserForm template_name = 'user_info/registration_form.html' #dispaly blank form, new user coming to the website def get(self, request): form = self.UserForm(None) return render(request, self.template_name, {'form':form}) def post(self, request): form = self.UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() form.py content as below: from django.contrib.auth.models import User from django import forms from … -
django-rest-auth + allauth Facebook registration requires CSRF token
I am trying to build a register API using Facebook in my app. I've followed the both packages documentations and using example from rest-auth doc. I've followed all the steps and I can successfully use this API from DRF browse-able API view and it is successfully performing the registration. When I try this API from somewhere else like postman it asks for CSRF token. I tried to use csrf_exempt decorator but that doesn't seem to be effective on this url. Here is my url config: url(r'^rest-auth/facebook/$', csrf_exempt(FacebookLogin.as_view()), name='fb_login'), Rest of the things are same as they mentioned in the documentation for django-rest-auth. I can't figure out what am I missing, or where should I look for a fix. Any help to diagnose the issue would be appreciated. -
HTML page not showing values
I a have a Python web app that sending parameter from the database to an HTML page when the page is loaded i cant see the result. I have check in the network tab in inspect mode and i can see the values are getting to the page . The parameter that are not presented in the page are: chaccount_id ,bank_name ,Company, seq_id This is my code : <form id="accounts_form" method="post" enctype="multipart/form-data"> {% csrf_token %} {% load staticfiles %} Account Number:<input list="accountslist" id="accounts_id" name="accountsname" value="{{ Account_id }}" > <button id="getacc_id" type="submit" name="getacc" value="commit">Get Account Details</button> <img id="GETACC_loading" src="{% static "app/images/small_loading.gif" %}" hidden> <br /> <br /> <br /><br /> <datalist id="accountslist"> <select id="accounslist" size="5"> {% for account in accounts %} <option value="{{ account.0 }}"></option> {% endfor %} </select> </datalist> </form> <table id="theTable" hidden> <thead> <tr> <td>Account id</td> <td>Bank Name</td> <td>Company Name</td> <td> Counter</td> </tr> </thead> <tbody> <tr> <td>{{ chaccount_id }}</td> <td>{{ bank_name }}</td> <td>{{ Company }}</td> <td>{{ seq_id }}</td> </tr> </tbody> </table> {% endblock %} {% block scripts %} <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script> <script> $(function () { $('#getacc_id').click(function(evt){ acctoshow=document.getElementById('accounts_id').value; evt.preventDefault(); $('#GETACC_loading').show(); $.ajax({ type: "POST", url: 'Accountinfo', data: { 'acctoshow' : acctoshow, 'csrfmiddlewaretoken': '{{ … -
Django rest api: Postman can't get csrftoken cookie
I'm using django rest-framework api for user registration. This my curl command is: curl -i -H 'Accept: application/json; indent=4' -H 'Content-Type:application/json' -H 'Referer:https://domain' -X POST https://domain/users/:register/ -d "id=222111&firstname=zinonas&yearofbirth=2007&lastname=Antoniou&othernames=" When I try it from cygwin is working properly and I get the csrftoken in cookies. This is the output: HTTP/1.1 200 OK Date: Thu, 26 Oct 2017 08:35:40 GMT Server: Apache/2.4.18 (Ubuntu) Allow: POST, OPTIONS Referer: https://domain/ Content-Length: 188 X-Frame-Options: SAMEORIGIN Vary: Accept,Cookie X-CSRFToken: MLJKNmBdYdF02ANX7pvZ7UavOVXtuPdW34vcF0RuLy94c1mQrL6blzkLMHCAFYkP Set-Cookie: csrftoken=sFkh2JjHxma3qnGpcRiOkQmH0xs9txqIJY6JUnzYkHE7AOfiwdT0yvwXYj7gEGxB; expires=Thu, 25-Oct-2018 08:35:40 GMT; Max-Age=31449600; Path=/ Content-Type: application/json { "isnew": "false", "user": { "firstname": "zinonas", "id": "222111", "lastnames": "Antoniou", "yearofbirth": 2007, "othernames": "" } } When I try the curl command in postman I get forbidden 403 error - CSRF token missing or incorrect. I have enabled postman interceptop and I set Referer header equal to https://domain. However I get the csrf cookie as can be seen in the image below: -
add NEXT_POST button to django template
i know that someone asked similar question but the answers didn't help me because i dont want to send the user to the next post, i want to send him to the next post in specific series. Models.py class Series(models.Model): title = models.CharField(max_length=100) tags = models.CharField(max_length=100) requirements = models.CharField(max_length=100) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=150) summery = models.CharField(max_length=100) body = MarkdownxField() # create/update info created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User) # Post info tags = models.CharField(max_length=100) series = models.ForeignKey(Series, blank=True, null=True) views = models.PositiveIntegerField(default=0) votes = models.PositiveIntegerField(default=0) def __str__(self): return self.title the button should appear in the post_detail template so the template contains the post and its fields if this will help in the answer thanks in advanced -
How to add another database server node in Django
I've a 2 databases which I've been running on a single machine. my question is how how can I add More database server along with that I wanna use django sharding so how can I shard my data from both database according to users means user 1 data from db1 and db2 on 1st server user 2's data on another -
Django: Fields of DeclarativeFieldsMetaclass (without instance)
I try to discover the fields which a django form class has. I only have a class, not an instance. The form-class is of type DeclarativeFieldsMetaclass. If I try this: class FooForm(forms.Form): spreadsheet = forms.FileField() for field in FooForm: print(field) I get this exception: TypeError: 'DeclarativeFieldsMetaclass' object is not iterable I know that I could do FooForm() instead of FooForm, but in my real use case I only have a class. -
How can I provide the Rest Framework API to intranet machine?
I use the rest framework write APIs, and when I runserver the website I can access the APIs in the development machine(the intranet ip is 10.10.10.111): But how can I access the API in other computer which is in the 10.10.10.0/24 intranet? If can, this will become more convenient for our team to debugging. -
Django form not showing in template
Why is the form not showing in the browser? index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{ structure.name }} - Details</title> </head> <body> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <h3>Structure: {{ structure }}</h3> <h3>Ajouter enregistrement</h3> <form action="{% url 'Structure:addrecord' structure.id %}" method="post"> {% csrf_token %} {% for structure in all_structures %} <input type="radio" id="record{{ forloop.counter }}" name="record" value="record.id"> <label for="record{{ forloop.counter }}"> Nom de l'enregistrement: {{ record.record_name }} </label> {% endfor %} </form> </body> </html> When I test this in my browser, and inspect it, it gives me a form of this size: 1340px * 0 px. I even explicitly gave a style="height: 500px", but it still gives me an empty form. Here's a screenshot Thanks for the help guys! -
Speeding up chat bot replies in django python
I have made a chat bot in django python which listens via Http requests. Certain chat channels, such as slack, require an immediate 200OK http response from the server. Hence I register a celery task (into a queue) to return http 200OK instantly and let the reply be processed in background. It is taking 3-4 seconds in production (SQS based) for the bot's reply to be received by the end user. Through logs I have found out that the delay is in the task to reach the celery worker. I want to make my chat bot's replies to come really fast when a user types in a message and am looking for a faster alternative to celery for this specific use case. Thank you! Note that I do not want to use slack's RTM api because I do not intend to make my bot slack specific. -
Why not use enctype="multipart/form-data" always?
By change I discovered that the django admin interfaces uses enctype="multipart/form-data" always. I would like to adopt this pattern, but I am unsure if I see all consequences this has. Why not use enctype="multipart/form-data" always? -
Django migrations : relation already exists
I have trouble with django model migrations. I have some models in my app, and I already have some data inside. When I added some models in my application, and I run makemigrations, the app report that there is no change. I know that sometimes some errors came when migrate, so I delete django_migrations table in my database and run makemigrations again, and now program found my new fields. The problem now is that if I run migrate system tell me that some tables already exist. (Which is ok and correct, because they do). I don't want to delete those tables, because I have data already inside. I can't run migrate --fake, because program will think that I already have all the tables, which is not true. So, I am looking for a way to tell the program : run migration, if table exist skip it. (--fake it) Another question is why is this happening to me, that makemigrations don't recognise my changes (some cache problems,...)? -
Reseting URL in Django through views.py
I am using Python 3.6, Django 1.11 with Salesforce NPSP as my back-end. I have an issue, where-in I generate a User activation link URL & send mail to the user. Once user clicks & confirms, he will be logged-in & allowed to use the application. The url which I generate for mail activation is something like below, it has token values in it localhost:8080/naka/activation/abg479843fiuegf/hfduige433274 Once user clicks above url he will be taken to home page which is having url localhost:8080/naka/activation/abg479843fiuegf/hfduige433274/home.html I am looking to reset the above url as localhost:8080/naka/home.html Reason being it will be easy to access my other pages like localhost:8080/naka/aboutus.html localhost:8080/naka/contactus.html and so on I have added my view.py file which has activation method in it def activate(request, uidb64, token): context=locals() try: uid = force_text(urlsafe_base64_decode(uidb64)) user = uid except(TypeError, ValueError, OverflowError): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user, backend='django.contrib.auth.backends.ModelBackend') return render(request,'home/home.html',context) #return HttpResponseRedirect('http://localhost:8000/naka/home.html') else: return HttpResponse('Activation link is invalid!') I have also added a line from my urls.py file related to activation url(r'^naka/activate/(?P[0-9A-Za-z_-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), kindly suggest. -
Make_Password returning different hash value for same password
i don't want to use django default user table so i created a user table with username and hashed password. I hashed the password with make_password() when posting to database but when i tried retrieving information from the database using the same method to hash user input password, i get a different hash for same password. below is the view code for saving the user and retrieving the details. view.py class HMUser(APIView): def post(self, request): request.data['password'] = make_password(request.data['password']) print(request.data['password']) serialize = serializers.HMUserSerializer(data=request.data) if serialize.is_valid(): serialize.save() return Response(1, status=status.HTTP_201_CREATED) return Response(serialize.errors, status=status.HTTP_400_BAD_REQUEST) class Login(APIView): def get(self, request, username, password): print("pass ", password) userpassword = make_password(password) print("Hash", userpassword) user_details = models.HMUser.objects.get(username=username, password=userpassword) serialize = serializers.HMUserSerializer(user_details) return Response(serialize.data)