Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Security: bypassing login with URL entry
I’m looking to create a login system for my Django web application with is connected to a MySQL database with a table for managers that holds their name, email, and password. My login screen has a URL of localhost/login. I want to query the off-server database for the username and password for each manager that was entered when the user puts in the information. If the credentials match, then I want to redirect them to the manager page, which is localhost/manager. If they don’t match, then I want to keep them at that page, localhost/login. My question is what’s stopping the user from inputting the localhost/manager URL path into their browser and bypassing the login, getting access without getting authenticated? Is there a good way to store the user name and password in the database to make them more secure but also accessible and checkable again? -
how to populate data in formset from the model data where there is variable no. of added forms
i have formset where i want to populate the data from database at the time of edit details and i have multiple no. of forms there js script is embeded in template/app/skills.html at bottom. forms.py class skillform(forms.Form): name = forms.CharField( label='Skill', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Your Skill here' }) ) level = forms.ChoiceField(choices=(('Novice','Novice'),('Beginner','Beginner'),('Skillful','Skillful'),('Experienced','Experienced'),('Expert','Expert')),label="level",initial='Skillful',widget=forms.Select(),required=False) skillformset = formset_factory(skillform) models.py class userskills_model(models.Model): userid = models.ForeignKey(user_model, on_delete=models.PROTECT) skills =models.CharField(max_length=264, unique=False, blank=False,null=False) skills_level = models.CharField(max_length=264, unique=False, blank=False, null=False) def __str__(self): return str(self.userid) templates/app/skills.html {% extends 'app/base.html' %} {% load staticfiles%} {% block head %} <link href="{% static "/css/skills.css" %}" rel="stylesheet" type="text/css"/> {% endblock %} {% block content %} <div class="heading_text">SKILLS</div> <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer"> <div class="col-5"> <label>{{form.name.label}}</label> <div class="input-group"> {{form.name}} </div> </div> <div class="col-5"> <label>{{form.level.label}}</label> <div class="input-group"> {{form.level}} <!-- <div class="input-group-append"> <button class="btn btn-success add-form-row">+</button> </div> --> </div> </div> <div class="input-group-append"> <button class="btn btn-success add-form-row">+</button> </div> </div> {% endfor %} <div class="row spacer"> <div class="col-3 button1"> <button type="submit" class="btn3">Save and Continue</button> </div> </div> </form> {% endblock %} {% block custom_js %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script type="text/javascript"> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + … -
Display thumbnail from image without creating or modifying file, based off of url?
I have a database with rows, with one of the fields being image_url. The images specified by these urls are high resolution and have different aspect ratios. I need to use some of these images to display thumbnails. I am thinking of running them through an image program to automatically create thumbnails, and then add a new image_thumbnail_url field of the like. Alternatively, I have seen some software which leads me to believe it may be possible for django to take these images, resize them in memory and then serve them to the client, without having to create new resize images. Is such a method possible, and if it is possible, is it efficient, or frowned upon? -
How to have a local instance or React hit a local instance of Django
I have a django api (djangorestframekwork, django2.1, python 3.6) that I run locally - http://127.0.0.1:8000/api/cards/b361d7e2-6873-4890-8f87-702d9c89c5ad. This api seems to work well. I can hit it via the web api or use curl/requests to add to or view the database. Now, I want to be able to have my React project hit this api. I can have my react project hit a different api and it returns the data, but when I replace that URI with my own URI it breaks. App.js - there is one line commented out. Switch that out with the other to switch between the public and private api. import React from 'react' import keyforge from '../api/keyforge' import localhost from '../api/localhost' import SearchBar from './SearchBar' class App extends React.Component { onSearchSubmit = async (term) => { const response = await localhost.get("api/cards/" + term) //const response = await keyforge.get("api/decks/" + term) console.log(response) } render () { return (<div className='ui container'> <SearchBar onSubmit={this.onSearchSubmit} /> </div>) } } export default App keyforge.js - this one works! import axios from 'axios' const proxyurl = 'https://cors-anywhere.herokuapp.com/' const url = 'https://www.keyforgegame.com/' export default axios.create({ // baseURL: 'https://www.keyforgegame.com/api/decks/' baseURL: proxyurl + url }) localhost.js - this one does not work import axios from 'axios' … -
Accessing dictionaries given django template's attributes?
So my problem is that I need to iterate over a dictionary given an attribute, which is the value of the for loop. For example, I have a dictionary called my_dictionary which is being iterated by a for loop in a django template, with an attribute called q. What I need is to access to that dictionary by using the q attribute. I tried with {{my_dictionary.q}}, {{my_dictionary.{{q}} }} but none of them did work. What can I do? I guess it should be similar as in Python my_dictionary[q]. Thank you. -
User Profile 'Syntax Erro'r in Django
I am trying to create the user profile in Django. t is a new User model that inherits from AbstractUser. It requires special care and to update some references through the settings.py. Ideally, it should be done at the beginning of the project, since it will dramatically impact the database schema. Extra care while implementing it. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/user/anaconda3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/user/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/user/anaconda3/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/user/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 674, in exec_module File "<frozen importlib._bootstrap_external>", line 781, in get_code File "<frozen importlib._bootstrap_external>", line 741, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/user/Desktop/vmail/vm/models.py", line 21 user = models.OneToOneField(User, on_delete=models, CASCADE) ^ SyntaxError: positional argument follows keyword argument how to solve this syntax error? my models.py # -*- coding: utf-8 -*- … -
What are dependancies and why should I care about them?
I am a beginner to web development, and am currently engaged in creating a Django web application to interface with a MySQL database. Through the time I've spent reading the documentation for Django, it constantly talks about isolating dependancies using virtual environments like virtualenv. I don't really understand what a dependency is and why creating a virtual environment would help 'isolate' them from each other. What is a virtual environment? Is it like another machine running on your machine? Any input for these conceptual questions would be much appreciated. -
WHY connect MySQL database to Django?
I am creating my first ever Django web application, which is essentially a portal for managers to view the current status of a MySQL database. I’m having trouble understanding why I should connect MySQL to Django instead of just writing Python scripts to connect directly to the database using the pymysql library. Plus, if I decide to go forward with connecting Django and MySQL, what would interfacing them look like? I'm currently hosting both the Django web app and the MySQL database on my computer, but will eventually host them on external servers. I'm a webdev beginner and any input would be much appreciated. -
migrate failure (django 1.7) need some
Hi I have a problem in migrate I want to help I looked at all the models I could not figure out the solution Applying accounts.0013_add_primary_interests...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards self.code(from_state.apps, schema_editor) File "/Users/mumirahibrahim/Desktop/mo/Fudulbank/accounts/migrations/0013_add_primary_interests.py", line 14, in add_primary_interests exam_content_type = ContentType.objects.get(app_label='exams', model='exam') File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. please help me -
Sending SMTP email with Django and Sendgrid on Heroku
I'm trying to send email using SMTP and sendgrid for a Django app. I'm able to send emails on my local server, but on my heroku app I get an "SMTPServerDisconnected" error saying "connection unexpectedly closed. Is there a way to send SMTP email with sendgrid once deployed to Heroku? I can't seem to find any documentation on this. Here are my settings for email in settings.py: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'EMAIL_HOST_USER' EMAIL_HOST_PASSWORD = 'EMAIL_HOST_PASSWORD' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'email@email.com' SENDGRID_API_KEY='SENDGRID_API_KEY' SENDGRID_PASSWORD='SENDGRID_PASSWORD' SENDGRID_USERNAME='SENDGRID_USERNAME' Please let me know what settings you use to send SMTP email. Thanks. -
403 Forbidden response on a django app deployed using nginx, supervisor and gunicorn
I have been trying to solve this for the past few days. So any help is much appreciated. I have a VPS installed with ubuntu server 18.04 and am trying to deploy a django app using supervisor, gunicorn and nginx. I am a newbie to this platform and so following this tutorials. https://jee-appy.blogspot.com/2017/01/deply-django-with-nginx.html My setup on the server is as the only user 'root'. Django: 2.1.4 nginx: nginx/1.14.0 (Ubuntu) gunicorn: (version 19.9.0) geteat.conf (/etc/nginx/sites-available) upstream geteatapp_server { server unix:/root/djangoproject/geteat_dir/geteat_venv/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name 26.208.54.108; client_max_body_size 4G; access_log /root/djangoproject/logs/nginx-access.log; error_log /root/djangoproject/logs/nginx-error.log; location /static/ { root /root/djangoproject/geteat_dir/geteat/; } location /media/ { root /root/djangoproject/geteat_dir/geteat/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # proxy_set_header Host $http_host; proxy_set_header Host $host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://geteatapp_server; break; } } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /root/djangoproject/geteat_dir/geteat/static/; } } gunicorn_start.bash (at the project root) #!/bin/bash NAME="geteatapp" # Name of the application DJANGODIR=~/djangoproject/geteat_dir/geteat/ # Django project directory SOCKFILE=~/djangoproject/geteat_dir/geteat_venv/run/gunicorn.sock # we will communicte using this unix socket USER=root # the user to run as GROUP=root # the group to run as … -
Auto fill Django form fields with Javascript/Jquery. Like HTML forms
How do I add id's to my Django form input fields so I can auto fill them using jquery. If I had to do it for a regular HTML form I would do it like below HTMl Form: <form method="post" action="{% url 'accounts:edit_location' %}" style="display: none"> {% csrf_token %} <input id="Alpha" type="text" > <input id="Beta" type="text" > <button>Locate Me</button> <!----When user presses this button the Jquery auto fills the Alpha and Beta fields with a value----> <button type="submit" id="submit">Submit</button> </form> But since I am doing it with Django forms, I tried the below approach but it did not work Django Form: class EventForm(forms.ModelForm): price = forms.DecimalField(decimal_places=2, max_digits=5) stock = forms.IntegerField() class Meta: model = Tasting fields = ('price', 'stock', 'date', 'time_from', 'time_to', 'note', 'served_in', 'lat', 'lon') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['lat'].id = "tasting_lat" self.fields['lon'].id = "tasting_lon" Below is a image of the form The Question: I need to move the locate me button above the lat, lon fields I need to add id=something to the input field in my Django Form Can anyone suggest how I can do the above? -
Django - Forms: 'module' object is not callable error
I am trying to update several rows in my table. Same with this question. I modified codes for my project and trying to solve it since a few days but it doesn't work for me. Firstly, i am show all existing rows in html page in a form. And if it is POST request then trying to save into db. I have 2 error here. 1. If i use return render_to_response('module.html',{'modules' : modules}) it is showing data in html page like i want but when click to save button, it give below error: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. If i use return render(request, 'module.html',{'modules' : modules}), it is not even showing data and just give below error : 'module' object is not callable Could you please help me find problem with my code? models.py class ModuleNames(models.Model): ModuleName = models.CharField(max_length = 50) ModuleDesc = models.CharField(max_length = 256) ModuleSort = models.SmallIntegerField() isActive = models.BooleanField() ModuleType = models.ForeignKey(ModuleTypes, on_delete=models.CASCADE, null = True) slug = models.SlugField(('ModuleName'), max_length=50, blank=True) class Meta: app_label = 'zz' def __unicode__(self): return self.status views.py @cache_page(60 * 15) @csrf_protect def addmodule(request,moduletype): modules='' if request.method == 'POST': data = request.POST.dict() … -
Django PIL unexpected image rotation
I have a Django project with a model with ImageField fields, I use Pillow to manage images, but I find that Images are rotated and are always saved in portrait orientation, in despite of its original orientation. Is there any way to instruct PIL not to change image orientation, but to keep the original one? -
Viewflow - start process with Django model post_save signal
Is there a way to start a Viewflow process with Django model post_save signal. I managed to do this: //start viewflow process start = ( flow.StartSignal(post_save, create_dest_flow) .Next(this.approve) ) //create flow function def create_dest_flow(**kwargs): print("Test") pass The "Test" string is printed for every save on any model. If I add activation to the create flow function parameteres I get an error: missing 1 required positional argument: 'activation'. How to start the flow only on specific model post_save signal? -
I get this error when i run python manage.py
So i am working with django. after setting up my urls in both applications, i get this error "file "C:\Users\Eric\Anaconda3\envs\myDjangoEnv\lib\site packages\django\urls\resolvers.py", line 542, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'alerts.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import". when i run python manage.py migrate.However, when i comment out include in my alerts.urls file it works fineenter image description here how can i fix this? i have attached my urls.py files this is my accouts.urls file from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/',auth_views.LoginView.as_view(template_name='accounts/login.html'), name ='login'), path('logout/', auth_views.LogoutView.as_view(), name ='logout'), path('signup/', views.SignUp.as_view(), name ='signup'), ] this is my main project url file from django.contrib import admin from django.urls import include,path from django.urls import path,include from . import views urlpatterns = [ path('', views.HomePage.as_view(), name="home"), path('admin/', admin.site.urls), path('test/', views.TestPage.as_view(), name="test"), path('thanks/', views.ThanksPage.as_view(), name="thanks"), path('accounts/', include("accounts.urls", namespace="accounts")), path('accounts/', include("django.contrib.auth.urls")), -
Is there any way to change username field label in user authentication login page?
Right now login page looked like this I want to change label of username field to Team Name Note: I'm using builtin LoginView -
View function is not working properly after including bootstrap
I am writing an HTML page that takes input from user via html form and "POST" method and submits it to a link. the link is attatched to a view which accesses a data base entry based on the info passed by the user. But, when i include bootstrap code for navbar header in that HTML page it is not able to access the database. my view function is def favorite(request,album_id): album = get_object_or_404(Album,id = album_id) try: selecte d_song = album.song_set.get(id = request.POST['song']) except: return render(request,'music/detail.html',{'album':album,'error_message':'No song selected!!'}) else: selected_song.isFavorite = True selected_song.save() return render(request,'music/detail.html',{'album':album}) the HTML page is - {% extends 'music/base.html' %} {% block body %} {% if error_message %} <p><strong>{{error_message}}</strong></p> {% endif %} <img src = "{{album.album_logo}}"> <h1>The album is {{album}} </h1> <h2>Artist - {{album.artist}}</h2> <h3>The songs in this album are: </h3> <form action = "{%url 'music:favorite' album.id %}" method = "post"> {% csrf_token %} {% for song in album.song_set.all %} <input type = "radio" id = "song{{forloop.counter}}" name = "song" value = "{{song.id}}"> <label for = "song{{forloop.counter}}"> {{song.song_title}} {% if song.isFavorite == True %} ' fav ' {% endif %} </label><br> {% endfor %} <input type = 'submit' value = "Favorite"> </form> </body> </html> while the … -
How do I login with with the user credentials in Django?
I'm working on a simple login and logout app in Django. I wrote two views one for login and another for register. Register view is working as expected. But login view is causing issues. I'm using form.is_valid() in login view. That is where the issue is arising. If I print the form in else block, it is saying A user with that username already exists. This is happening even before trying to authenticate the user. Some one help me with this. from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.http.response import HttpResponse from django.shortcuts import render from notes.forms import UserForm def login(request): if request.method == 'GET': return render(request, 'login.html') elif request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user: login(request, user) return HttpResponse("Logged in") else: return HttpResponse("Wrong creds") else: print(form) return HttpResponse("else of is_valid()") def register(request): if request.method == 'GET': return render(request, 'register.html') elif request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] existing = User.objects.filter(username=username) if existing: return HttpResponse('Username is already taken') else: User.objects.create(username=username, password = password, email=email) return HttpResponse("User created with "+ username +" username") else: return HttpResponse("Hi") -
Reverse for 'user' with arguments '('',)' not found. 1 pattern(s) tried: ['rubies/users/(?P<user_id>[0-9]+)/$']
NoReverseMatch at /project/users/1/stories/1/ Reverse for 'user' with arguments '('',)' not found. 1 pattern(s) tried: ['project/users/(?P[0-9]+)/$'] Does anyone have any idea why I face this error when I press "python manage.py runserver"? It used to work just fine and now it just doesn't. I've seen that the problem might be with user_id or user.id, but I can't really see it! Here is my code: project/views.py def story(request, user_id, story_id): if story_id is not None: story = get_object_or_404(Story, pk=story_id) else: story = Story() story.user_id = user_id if request.method == 'POST': story.title = request.POST['title'] story.story = request.POST['story'] story.date = timezone.now() story.save() return HttpResponseRedirect(reverse('rubies:story', args=(user_id,))) else: context = { 'user_id': user_id, 'story_id': story_id, 'title': story.title, 'story': story.story, 'likes': story.likes, 'comments': story.comments } return render(request, 'rubies/story.html', context) project/urls.py urlpatterns = [ path('', views.index, name='index'), path('register/<int:user_id>/', views.register, name='register'), path('login/<int:user_id>/', views.login, name='login'), path('users/<int:user_id>/', views.user, name='user'), path('users/<int:user_id>/stories/<int:story_id>/', views.story, name='story'), ] project/templates/project/story.html {% extends "rubies/base.html" %} {% block content %} {% if story_id %} <div class="post-preview"> <h2 class="post-title"> {{ story.title }}</h2> <p class="post-subtitle"> {{ story.story }} </p> <p class="post-meta">Posted by <a href="{% url 'rubies:user' story.author.id %}">{{ story.author.username }}</a> on {{ story.date }} <i class="fas fa-thumbs-up"> {{ story.likes }}</i> <i class="fas fa-comment"> {{ story.comments }}</i> </p> </div> <div class="post-preview"> <h2> … -
How to overwite django password_reset_confirm page?
I am a new Django developer. I am trying to overwrite django password_reset_confirm.html page with the below HTML file(change_pwd.html). <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="{% static "icon/tab_logo.png"%}"> <!-- Bootstrap --> <link href="{% static "web/vendors/bootstrap/dist/css/bootstrap.min.css" %}" rel="stylesheet"> <!-- Custom Theme Style --> <link href="{% static "web/src/css/login.css" %}" rel="stylesheet"> <!-- jQuery --> <script src="{% static "web/vendors/jquery/dist/jquery.min.js" %}"></script> </head> <body > <div class="vertical-center"> <div class="container"> <div class="row"> <div class=" col-md-4 col-md-offset-4"> <div id="loginbox" > <h1 class="text-center title">Change Password</h1> </br></br> <form id="passwordform" role="form" method="post" action="."> {% csrf_token %} <div style="margin-bottom: 25px" > <input type="password" class="pwd" name="new_password1" placeholder="password" autocomplete="off"> </div> <div style="margin-bottom: 25px" > <input type="password" class="pwd" name="new_password2" placeholder="repeat password" autocomplete="off"> </div> <div style="margin-top:10px" > <!-- Button --> <input id="btn-change-pwd" class="btn btn-primary btn_extend " type="submit" value="Submit"> </div> </form> </div> </div> </div> </div> </div> </body> </html> I have also overwritten the project's Urls.py as below: path(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, {'template_name' : 'change_pwd.html'}, name='password_reset_confirm'), When I reset password, the page is redirected to admin/templates/registration/password_reset_confirm.html page and then displays below message: The password reset link was invalid, possibly because it has already been used. Please request a new password reset. Based … -
Django template if choice field
im currently trying to figure out how i can check if a status does apply to a users request or not. models.py class CategoryRequests(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) status = StatusField() STATUS = Choices('Waiting', 'Rejected', 'Accepted') views.py def view_profile_categoy_requests_accepted(request, pk=None): if pk: user = get_user_model.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'myproject/category_request_accepted.html', args) But at the template this seems to be wrong. template.html {% if user.categoryrequests.status == 'Waiting' %} Thanks in advance -
Javascript Python Communication
I am currently working on a web app project in a django frame. This app let users take a picture through webcam(code written in javasript inside a html file), and I hope to transmit this image to a .py python file, is there a way I can make it? -
Channels server development cannot migrate
I'm following the tutorial to create a CHAT to learn using Channels. In this way I'm following this tutorial : https://channels.readthedocs.io/en/latest/tutorial/part_2.html I have done everything. When I apply the command: python manage.py migrate I get : Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: No migrations to apply. Whereas what is expected : Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying sessions.0001_initial... OK And when I run my Channels server developement (ASGI), I go on the url http://127.0.0.1:8000/chat/lobby/ and I still get on my browser's Javascript console the message error : WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/lobby/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET I don't know why it is not working. In my settings.py file of the project : INSTALLED_APPS = [ 'channels', 'chat', 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Last thing : I have not been able to install Docker because I'm on Windows 10 HOME. Could it be the … -
Why can't I use Jinja syntax in Javascript for a django site?
So for those of us who use Python and Django framework to develop a website, there is this awesome tool known as jinja which can be used as a template engine. For example: Instead of hard-coding an import like this: <script src="assets/js/onebutton.js"></script> We can do this: <script src="{% static 'assets/js/onebutton.js' %}"></script> In this case, it automatically searches for a folder named static and goes inside to look for the needed code. But why isn't it possible to use jinja template in Javascript. For example: homepage.html <script src='whatever.js'></script> <p>Another example</p> <button id="clickme"> click me </button> whatever.js $(function() { $('#clickme').click(function(){ $.ajax({ headers : {'X-CSRFToken': getCookie('csrftoken')}, type: "POST", url: '{% url "func" %}', //<--Problem arise here datatype:"json", data: {}, success: function(data){ var new_template = '<h1> %firstmsg% </h1>'; var new_frontend = new_template.replace('%firstmsg%',data.message); console.log(new_frontend); document.getElementById('wor').innerHTML+=new_frontend; } }); } } Django would recognize the url in the AJAX request as /'{% url "func" %}' instead of /func The only way to solve this is to move the entire code from whatever.js into the homepage.html under <script></script> brackets. Perhaps we need to import something for Jinja templating to work?