Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Leaflet grouping layer doesn't show on the map
I am working in GeoDjango. I am trying to add leaflet group from here. I copied files from the dist folder to my folder with the static files and imported them into HTML file. Anyway I have some problem with this part of code: #GROUP LAYER var osm = 'http://{s}.tile.openstreetmap.org/{z}{y}{x}.png'; var baseLayers = { "OSM":osm } var groupedOverlays = { "layers": { "layer1": datasets_buildings, "layer2": datasets_roads, "layer3": datasets_railways, "layer4": datasets_natural } }; L.control.groupedLayers(baseLayers, groupedOverlays, options).addTo(map); When I typed this, I don't even get my layers on the map, I get just the empty leaflet map and without this part of the code, I get it. Also, I would like to make functionality to this layer group which allows only one layer to be active. This is all my code: <html lang="en"> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <style type="text/css"> #gis { width: 100%; height: 870px; } </style> <link rel="stylesheet" type = 'text/css' href="{% static 'maps/dist/leaflet.groupedlayercontrol.css' %}"> <script type="text/javascript" src="{% static 'maps/dist/leaflet.ajax.js'%}"></script> <script type="text/javascript" src="{% static 'maps/dist/leaflet.groupedlayercontrol.js' %}"></script> </head> <body> <script type="text/javascript"> function our_layers(map,options){ //buildings var datasets_buildings = new L.GeoJSON.AJAX(" {% url 'buildings_json_data' %}",{ onEachFeature : function (feature, layer) { layer.bindPopup(feature.properties.name.toString()) } … -
user_id login Session and Cookies in Django
I am Beginner in Django, I want to know Is there already implemented cookies and session in Django for login. If It's implemented How can I use them? If not How can I implement It for user login? -
Django mysqlclient not installed
I was working with sqlite database in local development . After uploading project to server ubuntu , i installed mysqlclient , but when i try to run makemigraions command this error occurred : ImportError: No module named 'django.db.backends.mysql' Try using 'django.db.backends.XXX', where XXX is one of: 'oracle', 'postgresql', 'sqlite3' I also checked project env folder and mysql lib exists in env/python3.5/site-packages ! settings database : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbname', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': 'localhost', 'PORT': '', } } -
Problem with pagination in template django?
I have such view in my application and I try to paginate in in my temlate. But prev and next don't work. What's wrong? class ForMenView(ListView): model = Post template_name = 'man_index.html' context_object_name = 'all_posts' paginate_by = 1 def get_queryset(self): query = self.request.GET.get('q') qs = Post.objects.filter(sex='M', is_published=True) if query: return qs.filter(title__icontains=query) return qs def get_paginate_by(self, queryset): user = self.request.user if user.is_authenticated and user.sex == 'M': return 1 return self.paginate_by def dispatch(self, request, *args, **kwargs): user = self.request.user if user.is_authenticated and user.sex == 'W': return redirect('/forwomen') # please replace it with the view name else: return super(ForMenView, self).dispatch(self.request ,*args, **kwargs) def get_context_data(self, *args, **kwargs): kwargs = super(ForMenView, self).get_context_data(*args, **kwargs) kwargs['page_range'] = kwargs['paginator'].page_range return kwargs And in my template I try to paginate such way THIS DOESN'T DISPLAY AT ALL {% if all_posts.has_previous %} <li><a class="pgn__prev" href="?page={{ all_posts.previous_page_number }}">Prev</a></li> {% endif %} {% for x in page_range %} <li><a class="pgn__num" href="?page={{ x }}">{{ x }}</a></li> {% endfor %} THIS DOESN'T DISPLAY TOO {% if all_posts.has_next %} <li><a class="pgn__next" href="?page={{ all_posts.next_page_number }}">Next</a></li> {% endif %} My context value of {{all_posts}} = <[Post: TitlePost]> Why dont previous and next work? -
Is it possible to add 2nd slug to URL path in Django?
I'm using Django version 2.1. I want to create this type of URL Path in my Project: www.example.com/bachelor/germany/university-of-frankfurt/corporate-finance Is it possible to do it in Django? -
How to serialize multiple relationship models in django rest framework
I'm new to this Django rest framework and I'm trying to create an API. My model.py looks like the following class FieldTypes(models.Model): field_type = models.CharField(max_length=255, null=False) deleted = models.BooleanField(default=False) class Forms(models.Model): form_name = models.CharField(max_length=255, null=False) deleted = models.BooleanField(default=False) class FormFields(models.Model): form = models.ForeignKey(Forms, related_name = 'form_fields', on_delete=models.CASCADE) field_type = models.ForeignKey(FieldTypes, related_name = 'form_field_types', on_delete=models.CASCADE) description = models.CharField(max_length=255, null=False) deleted = models.BooleanField(default=False) class FormFieldOptions(models.Model): form_field = models.ForeignKey(FormFields, related_name = 'form_field_options', on_delete=models.CASCADE) description = models.CharField(max_length=255, null=False) deleted = models.BooleanField(default=False) and the serializers.py looks like class FormFieldSerializer(serializers.ModelSerializer): form_field_options = FormFieldOptionsSerializer(many=True) class Meta: model = FormFields fields = ('id', 'description', 'form_field_options') class FormSerializer(serializers.ModelSerializer): form_fields = FormFieldSerializer(many=True) class Meta: model = Forms fields = ('form_name', 'form_fields') class FieldTypeSerializer(serializers.ModelSerializer): class Meta: model = FieldTypes fields = ('field_type') with that i was able to produce a result a like { "form_name": "Ticket", "form_fields": [ { "id": 1, "description": "Type", "form_field_options": [ { "id": 1, "description": "Question" }, { "id": 2, "description": "Incident" }, { "id": 3, "description": "Problem" }, { "id": 4, "description": "Task" } ] } ] } but i need to know which field type the form fields belongs to. And I'm not sure about how to bring field types in the JSON data. Kindly … -
Django 404,500,403 custom page redirection problem
I was unable to configure 400,500,404 etc page in my webapp. I have made one dedicated project to test these custom behave but failed to get any result. I have taken following steps to set up those custom pages : 1. Configured project folder urls.py with handler404 = 'testapp.views.not_found' handler500 = 'testapp.views.server_error' handler403 = 'testapp.views.permission_denied' handler400 = 'testapp.views.bad_request' these lines 2. I have created one app name testapp and pasted below codes inside the views.py def server_error(request): return render(request, 'testapp/500.html') def not_found(request): return render(request, 'testapp/404.html') def permission_denied(request): return render(request, 'testapp/403.html') def bad_request(request): return render(request, 'testapp/400.html') Created template directory inside testapp and again created testapp directory inside template directory. enter image description here Set Debug = Flase. 5.But when I hit any wrong url it says "A server error occurred. Please contact the administrator." enter image description here List item Any Suggestions that I can do to bring the desired result ? -
Why is Butter CMS not working with Django?
I have a Django project that needs to use Butter CMS. I managed to successfully pip install "buttercms-python" in my virtual environment. This is the code I need to put in the views.py in order to get it working: from django.http import Http404 from django.shortcuts import render from butter_cms import ButterCMS client = ButterCMS('your_api_token') def home(request, page=1): response = client.posts.all({'page_size': 10, 'page': page}) try: recent_posts = response['data'] except: # In the event we request an invalid page number, no data key will exist in response. raise Http404('Page not found') next_page = response['meta']['next_page'] previous_page = response['meta']['previous_page'] return render(request, 'blog_base.html', { 'recent_posts': recent_posts, 'next_page': next_page, 'previous_page': previous_page }) For some reason, when I try running the project afterwards, I get an error that says that there's no module named butter_cms, even though I clearly installed it and my Python editor would have indicated if the module didn't exist, and it didn't. I actually wrote a quick startup code in a pure Python file located in the same directory of the project: from butter_cms import ButterCMS client = ButterCMS('your_api_token') print client.posts.all({'page_size': 10, 'page': 1}) This time the import actually worked and could run successfully. Why can it run properly in a pure Python … -
Django : Can I Pre-fill forms with a model instance datas in form.py?
i've seen a way to do what I want in the views.py file, but as I'm probably going to use the form in several different places, and because I believe it belongs more in forms.py, I was wondering if and how I could pre-fill my form with the datas already stored in the database for one particular user without modifying the views. Seeing what I tried will speak for itself : models.py : class Customers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='details') city = models.CharField(max_length=50, blank=True, null=True) dpt = models.IntegerField(blank=True, null=True) adress = models.CharField(max_length=100, blank=True, null=True) cplt_add = models.CharField(max_length=100, blank=True, null=True) phone = models.CharField(max_length=14, blank=True, null=True) forms.py : class CustomerForm(ModelForm): def __init__(self): for field in self.fields: user_infos = Customers.objects.get(pk=request.user.details.id) initial_value = user_infos.field field(initial=initial_value) def clean_form(self): ... class Meta: model = Customers fields = ['city', 'adress', 'dpt', 'cplt_add', 'phone'] widgets = { 'city': TextInput(attrs={ 'class': 'form_input', 'placeholder': 'Ville'}), 'dpt': TextInput(attrs={ 'class': 'form_input', 'placeholder': 'Département'}), 'adress': TextInput(attrs={ 'class': 'form_input', 'placeholder': 'Adresse'}), 'cplt_add': TextInput(attrs={ 'class': 'form_input', 'placeholder': "Complément d'adresse"}), 'phone': TextInput(attrs={ 'class': 'form_input', 'placeholder': 'Téléphone'}), } This code, sadly but without big surprise, returns : 'CustomerForm' object has no attribute 'fields' Any advice on how to do this with good practice methodology ? -
Django method exists() not working, error "referenced before assignment"
after long time passed at searched a solution, i not advanced for a reason. I try of make operate the functionality "if exists():" for "User.username" of the user, and so avoid the duplicate username in my webSite,but this is not work. this is my code in views.py : def edit_profil(request, pk=id): error_name = reverse_lazy('profil_edit') template_name="blog/edit_profil.html" if request.method == "POST": form = EditProfilForm(data=request.POST, instance=request.user) if form.is_valid(): usernameDatas = form.cleaned_data['username'] if User.objects.filter(username=usernameDatas).exists(): messages.error(request, 'This is Username already exists !') return redirect(error_name) else: user = form.save(commit=False) user.email = form.cleaned_data['email'] user.username=usernameDatas user.save() return redirect('/blog/profil') else: form = EditProfilForm(instance=request.user) return render(request, template_name, locals()) The error received this is : "local variable 'usernameDatas' referenced before assignment" Where is my error ? thanks all. -
Count every time an object if displayed/accessed
Sorry if my headline wasn't explicit enough. I'm trying to develop a marketing tool that track every single page of my project. So I'm using InfluxDB along PostgreSQL. I am able to track pages (or clicks) but not the "views". Let me explain: If I have a 10 items in the listing. I want to track which item has been displayed on which page. Example: Item B was displayed on page 2; Item C was displayed on page 1. I was planing on looping through the list but I don't like this solution because I have to loop twice: one for tracking, one for display the item. So I'm looking for a cleaner solution but I'm out of ideas. What would you do? Thank you in advance. -
Calling a function from HTML to Python file
I have a index.html page with a list of "cards", where each card have a "Click to Select" link. When user click in this link i'd like to call a function in python to select this item, see: def selectItem(request, item): #so something with this item so, in my html pagE: <div class="card-action"> <a href="{{ selectItem(myitem) }}">Selecionar</a> </div> This don't work. What is the right way to do it ? -
Navbar fixed left - Bootstrap
I am trying to make navbar in bootstrap to be fixed left, like on this link. Anyway, it is working, but when I add block content of the leaflet map, my navbar is still there, but I can't click on it. Also, I don't get pointer mouse when I cross over the link. Here is code which I changed: <!--NAVBAR--> <div class="navbar navbar-inverse navbar-fixed-left"> <a class="navbar-brand" href="#">Brand</a> <ul class="nav navbar-nav"> <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Sub Menu1</a></li> <li><a href="#">Sub Menu2</a></li> <li><a href="#">Sub Menu3</a></li> <li class="divider"></li> <li><a href="#">Sub Menu4</a></li> <li><a href="#">Sub Menu5</a></li> </ul> </li> <li><a href="#">Link2</a></li> <li><a href="#">Link3</a></li> <li><a href="#">Link4</a></li> <li><a href="#">Link5</a></li> </ul> </div> </div> <div class="container col-sm-12"> <div class="row"> {% block map_content %} replace me {% endblock map_content %} </div> </div> Before this, I tried more elegant solution. I used bootstrap4 and tried something like this: <nav class="navbar navbar-inverse fixed-left"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'index' %}"><p class="logo_name">page name</p></a> </div> <ul class="nav navbar-nav"> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> </ul> </div> </nav> But it doesn't work, in this case, my navbar is fixed top, and not left. -
Problem with deploying on gandi python instance?
Problem: I tried to deploy my django application on my gandi python instace and it is giving me the below mentioned error. Some details about project: project is in python 3 Django version is 2.0 The Django project works fine on my local machine. I have deployed the same project on the same gandi instance many times and haven't got any error. Please find the uswgi log file here The same code was working well on the same instance, all i did was redeploy the code again using ssh xxxxxx@git.xxx.gpaas.net deploy default.git The details of the error can be found in the log file. Sadly there is no way of reinstalling/uninstalling a package on gandi python instance. please help me!! ` -
Django: let user delete own User instance from default model User
I have a model Creator which is linked to the Django standard User model via a OneToOneField field. The Creator model is there to allow me more flexibility when adding/editing information of a Creator. Now for deleting a Creator I use the generic DeleteView. However, this does not delete the User instance and hence is not completely what I am looking to do (e.g. the username of the deleted Creator is "already taken"). Is there a way to use the default DeleteView to let a user delete his account? What is the best practice to do a "delete account" operation regarding deleting the User instance, logging out the user, and confirming the success of the operation? What I tried so far: models.py class Creator(models.Model): first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) street_and_number = models.CharField(max_length=200, null=True, blank=True) zip_code = models.CharField(max_length=30, null=True, blank=True) location = models.CharField(max_length=100, null=True, blank=True) state_province = models.CharField(max_length=100, null=True, blank=True) country = models.CharField(max_length=100, null=True, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.user) super(Creator, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('creator-detail', args=[str(self.slug)]) views.py class CreatorDelete(LoginRequiredMixin, DeleteView): #model = User # does not work model = Creator success_url = reverse_lazy('index') # these … -
Django FormView: Changes don't get updated
I'm using Django together wit Neo4j and the neomodel package, therefore I'm unable to use CreateView, UpdateView etc. I would like to implement a way to update data using Django forms. My problem is that once I use get_initial() to prefill my form, none of the changes are saved. If, however, I comment out the whole get_initial() function, everything works fine, except of course that the form doesn't have any pre-filled values. Where's the problem? Here's the code: class ProfileUpdate(FormView): template_name = 'registration/update_profile.html' form_class = ProfileCreationForm success_url = '/' person = Person.nodes.get(user_id=1) # set to 1 for testing # From https://stackoverflow.com/a/22083336/1384315 def get_initial(self): initial = super(ProfileUpdate, self).get_initial() try: initial['careerLevel'] = self.person.role initial['about_me'] = self.person.about_me initial['institution'] = self.person.affiliation initial['researchInterest'] = self.person.research_interest except Person.DoesNotExist: pass return initial def form_valid(self, form): # Neo4j "model" self.person.role = form.cleaned_data.get('careerLevel') self.person.about_me = form.cleaned_data.get('about_me') self.person.affiliation = form.cleaned_data.get('institution') self.person.research_interest = form.cleaned_data.get('researchInterest') self.person.save() #return redirect('home') return super().form_valid(form) -
Problem on calling save() for post in django rest framework
Calling save() on a serializer is returning below error: Original exception was: Traceback (most recent call last): File "C:\Users\aditya\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\rest_framework\serializers.py", line 940, in create instance = ModelClass.objects.create(**validated_data) File "C:\Users\aditya\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\aditya\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\query.py", line 417, in create obj.save(force_insert=True, using=self.db) TypeError: save() got an unexpected keyword argument 'force_insert' views.py def post(self,request): if request.method=='POST': serializer = invoiceSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) model.py class invoice(models.Model): customer = models.CharField(max_length=256, blank=False) date = models.DateField(default=now) invoice_number = models.IntegerField(editable=False,default=1) total_quantity = models.DecimalField(max_digits=10, decimal_places=2) total_amount = models.DecimalField(max_digits=10, decimal_places=2) total_tax = models.DecimalField(max_digits=10, decimal_places=2) def save(self): if self._state.adding: last_invoice=invoice.objects.all().aggregate(largest=models.Max('invoice_number'))['largest'] if last_invoice is not None: self.invoice_number=last_invoice+1 super(invoice,self).save() I am not able to understand why this is happening and how to fix this. Any help is appreciated. -
TypeError: __str__ returned non-string (type bytes)
I'm in a process of rewriting a Python 2.7 Django application into Python 3.6. During the process I've encountered a bug in my test files. I have this small piece of code in one of my files # Test allow access to dispatchers # Test url print(type(url)) print(url) self.client.force_login(self.dispatcher) response = self.client.get(url) self.assertContains(response, 'Are you sure') And this is the response from the test Creating test database for alias 'default'... System check identified no issues (0 silenced). ....<class 'str'> /reservations/eb4f8dee-e1ed-48dd-b476-6751feee1e33/delete/ EE....FF... ====================================================================== ERROR: test_only_allow_access_to_dispatcher_from_same_client (reservations.tests.views.test_delete_view.TestDeleteReserv ation) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Jure\Desktop\optilimo\reservations\tests\views\test_delete_view.py", line 41, in test_only_allow_access _to_dispatcher_from_same_client response = self.client.get(url) File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\test\client.py", line 527, in get response = super().get(path, data=data, secure=secure, **extra) File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\test\client.py", line 339, in get **extra, File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\test\client.py", line 414, in generic return self.request(**r) File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\test\client.py", line 495, in request raise exc_value File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\core\handlers\base.py", line 156, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\core\handlers\base.py", line 154, in _get_response response = response.render() File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\template\response.py", line 106, in render self.content = self.rendered_content File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content content = template.render(context, self._request) File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\Jure\Desktop\optilimo\venv\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) … -
How to use one nginx webserver to provide an angular frontend and a django backend using docker / docker-compose
I have a Django back-end with rest APIs, an Angular6cli frond-end and I'm using docker. The Angular front-end is available trough the nginx webserver and Django is provided locally using uWSGI. In order to make the django-apis available to the client nginx has to route those too. Here are my: project structure project |-- django-backend |-- folders |-- settings.py |-- back.Dockerfile |-- manage.py |-- requirements.txt |-- uwsgi.ini |-- angular-frontend |-- src/ |-- front.Dockerfile |-- nginx.conf |-- docker-compose.yml back.Dockerfile FROM python:3.6.5 RUN apt-get update && \ apt-get install -y && \ pip install uwsgi RUN mkdir /src WORKDIR /src COPY . /src/ RUN pip install -r requirements.txt uwsgi.ini [uwsgi] project = backend base = %d http-socket = :8000 chdir = %(base) module = %(backend).wsgi master = true processes = 2 threads = 2 front.Dockerfile # Stage 0, based on Node.js, to build and compile Angular FROM node:8.11.1 as node RUN mkdir /src WORKDIR /src COPY package.json /src/ RUN npm install COPY . /src/ RUN npm run build -- --configuration $CONFIG # Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx FROM nginx:1.15 COPY --from=node src/dist/web /var/www/miap COPY ./nginx.conf /etc/nginx/conf.d/default.conf nginx.conf upstream django { server … -
Action is sometimes None in Django REST framework
I have written a customized permission class in Django REST Framework version 3.8.2 that behaves differently depending on the action of the request. I found that sometimes view.action is None when using the Browsable API to debug. Below follows a piece of code that will throw an exception when used with the Browsable API. class AdminOnlyPermission(BasePermission): def has_permission(self, request, view): # Just to demonstrate that view.action can be None assert(view.action is not None) # Only allow admin to delete if view.action == 'delete' and not request.user.is_staff: return False return True What does it mean that view.action is None? Can I safely ignore it or is it possible for a malicious user to make a delete request with the action set to None? -
How do I debug enabling CORS on my Django REST api
I'm trying to enable CORS on a simple django rest server. I've followed the suggestions here How can I enable CORS on Django REST Framework. Specifically I have: 1) done pip install django-cors-headers 2) added corsheaders to my installed apps 3) added corsheaders.middleware.CorsMiddleware at the top of the MIDDLEWARE section of my Django settings file 4) added CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'localhost:3000/radioDestinations/', 'localhost:8080', ) but it's still not working. When I send the request to the server (using a javascript fetch request) I get an error in the browser (...blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present...), but I don't get any output in the serve console. How can I find out where the problem is? -
Method not allowed Post in django
when i try to add a post method in my app it shows this message : Method not allowed (Post): HTTP/1.1 405 0 Views.py: class AddTeamView(View): def get(self, request): form = TeamForm() context = {'form': form} return render(request, 'add_team.html', context) add_team.html : {% extends 'base.html' %} {% block title %} Add a Team {% endblock %} {% block content %} <form action="/add_team/" method="post"> {% csrf_token %} <!-- this form content is called from the view.py/context--> {{ form }} <input type="submit" value="اضافة "/> </form> {% endblock %} urls.py: urlpatterns =[ url(r'add_team/$', AddTeamView.as_view(), name='add-team-view'), ] can anyone help plz? -
How to change content_subtype to html in django email_user
I read about django email confirmation form this tutorial. Now I need to send html mail not a simple string. I read this answer on how to send html email in django. Is there a way to change content_subtype to html in this tutorial email sending approach? or any other way to send html mail in this approach? current_site = get_current_site(request) subject = 'Activate Your Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) -
Password hash using django-rest-framework?
I figured out that django-auth hashes passwords per default with random salt in the background: https://docs.djangoproject.com/en/2.1/topics/auth/passwords/ However, I am not quite sure yet, what's the difference between django-auth and django-rest-auth. And I could not find information whether django-rest-auth will also hash and salt passwords automatically. Could someone explain what exactly the differences are between django-auth and django-rest-auth, when to choose which and why there are two libraries for the same problem? It is quite confusing for me as a beginner. -
Submitting multiple django forms with one button
I am currently creating a review page that dynamically loads a number of forms based on the number of people in a 'Team'. The HTML file currently looks like this: {% for user in team_members %} <div> <form method="post" id="review_form_{{user.user_id}}"> <p>Reviewing: {{ user.first_name }} {{ user.last_name }}</p> {% csrf_token %} {{ form.as_p }} <button class="btn btn-outline-primary" type="submit">Save</button> </form> <script type="text/javascript"> $(document).ready(function(){ $("#review_form_{{user.user_id }}").children().children("#id_pk").val("{{user.user_id}}"); }); </script> </div> {% endfor %} <br> <a href="{% url 'review:openness_review' %}"> <button class="btn btn-primary">Next</button> </a> {% endblock %} The forms.py file class RangeInput(NumberInput): input_type = 'range' class ReviewForm(forms.Form): pk = forms.CharField( widget=forms.TextInput( attrs={ 'type': 'hidden', } ), label='' ) trait_score = forms.IntegerField( widget=RangeInput(attrs={'value': '0'}), label='', ) There is always at least one person in a team, so is there a way that I can submit all of the data from the forms using one button that collects all the forms on the page?