Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Email Token (URL with token for a specific task)
I am working on a Django Project for a Real Estate website. I am trying to find a mechanism so the user can delete a listing (Row in the Database) directly by clicking on a URL link sent to his email. In the normal cases to delete a listing you are required to sign-in, however I am looking to find a way to create a unqiue URL (tokenized) so the user can do it directly from the email. Something similar to how the password reset tokens work but this for a specific task. Any Advices? Thanks, -
How to handle multiple multiple user types?
I'm working on a RESTful Django app that requires two types of users: regular and privileged users. Both users will have different ways to authenticate into the app: 1) Regular users: will authenticate with phone number and password 2) Privileged users: will authenticate with email and password What is a good strategy to handle this type of authentication system? Is there any way to dynamically authenticate using different methods (phone number and email) based on the type of user logging in? -
Page not found 404 URL config
I keep getting the following error in my terminal (while running server) when I try to look at the home page. "GET / HTTP/1.1" 404 2028 here is the code that I have for mapping URLS: urls.py (main): from django.urls import path from django.contrib import admin from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path(r' ', include('learning_logs.urls', namespace='learning_logs')), ] urls.py(in learning_logs folder) """Define URL pattersn for learning_logs.""" from django.conf.urls import url from . import views app_name = 'learning_logs' urlpatterns = [ # Home page url(r'^$', views.index, name='index'), ] views.py: from django.shortcuts import render def index(request): """The home page for learning log""" return render(request, 'learning_logs/index.html') # Create your views here. index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p>Learning Log</p> <p>Learning log helps you keep track of your learning, for any topic you're learning about.</p> </body> </html> this is the error I'm getting on the home page: Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ Thanks for the help in advance. -
Using Delete request in Django outside of a form
I am trying to create a simple todo list app that uses POST to post data into the data base and a 'x' (\u00D7) to delete the todo. The code is as following: Views.py def delete(self, request, id): print(request.DELETE) self.model.objects.get(pk=request.delete['pk']).delete() return render(request, self.template_name, {'object_list':self.model.objects.all()}) Models.py class TodoDB(models.Model): todos = models.CharField(max_length=1000) day = models.CharField(max_length=10) def __str__(self): return str(self.todos) HTML and JS <ul class="list-group list-group-flush" id="list-group"> {%for item in object_list%} <li class="list-group-item">{{item.todos}}</li> {%endfor%} </ul> for (var i = 0; i < close.length; i++) { close[i].onclick = function() { var li = this.parentElement; li.style.display = "none"; $.ajax({ type: 'DELETE', url: "{%url 'todo_list'%}", data:{'pk':pk}, success: function(data){ alert("Success!"); }, error: function(){ alert("Error! Couldn't send delete request") } }); } Any help would be great. Thanks! -
How to Return Value of Radio Button
I realize this should be a simple question, but I can't seem to get it to work and I've been googling for about an hour. I have a set of radio buttons defined in my HTML code here: <h6>Axis Filter</h6> {% csrf_token %} {% for radio in form.axis_filter %} <div class="radio-inline"> {{radio}} </div> {% endfor %} And in my forms.py file here: TIME_FILTER = [ ('years','Years'), ('quarters','Quarters') ] axis_filter= forms.CharField(label = 'axis_filter',widget=forms.RadioSelect(choices=TIME_FILTER),initial = 'years') Now I'm trying to get the selected value in my views.py using this: request.GET.get('axis_filter',None) I've also tried: request.POST.get('axis_filter',None) Each time I go to print the value however I get a value of 'none'. Does anyone have any suggestions? -
supervisor exiting with ENOENT
I am attempting to deploy a Django web application for the first time using NGINIX, Gunicorn and Supervisor on Digital Ocean Ubuntu 16.04 server. I am following the this linked tutorial. I am having a trouble configuring Supervisor. When running this command... sudo supervisorctl status automatedre I get this error... automatedre FATAL Exited too quickly (process log may have details) The log file shows this... supervisor: couldn't exec /home/automatedre/gunicorn_start: ENOENT supervisor: child process was not spawned supervisor: couldn't exec /home/automatedre/gunicorn_start: ENOENT supervisor: child process was not spawned /home/automatedre/gunicorn_start #!/bin/bash NAME="django_automatedre" DIR=/home/automatedre/automatedre USER=automatedre GROUP=automatedre WORKERS=3 BIND=unix:/home/automatedre/run/gunicorn.sock DJANGO_SETTINGS_MODULE=automatedre.settings DJANGO_WSGI_MODULE=automatedre.wsgi LOG_LEVEL=error cd $DIR source ../venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- /etc/supervisor/conf.d/automatedre.conf [program:automatedre] command=/home/automatedre/gunicorn_start user=automatedre autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/automatedre/logs/gunicorn.log I'm not sure where to go from here. I don't believe it is a file permission issue since I previously changed permission on gunicorn_start with this... chmod u+x gunicorn_start Any ideas on where I'm going wrong? -
rest api - Abort object creation in serializer create method
I'm wondering whether serializer create method is a good place for aborting object(model) creation. Let consider following code: class TestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Test fields = ('url', ...) def create(self, validated_data): if everything_is_ok: return super().create(validated_data) else: #if something is wrong with data abort object creation and rise exception that will led to 400 or sth ??? From my perspective it looks ok, because I'm using many serializers and here I have code only related to that particular one. Nevertheless I'm not sure if this is correct way (maybe create method of ModelViewSet would be better?) If serializer create method is ok, how should I do it properly (raise exception or rather return 400 Response directly) Thank you in advance -
Safe to replace my domain name on my Django application?
Will I face any repercussions for replacing the domain name on my Django application? It's running on Ubuntu 16.04 with Nginx/Gunicorn. Apart from ALLOWED_HOSTS in my settings.py, the other locations I would replace the domain is my Nginx conf file and also my Digital Ocean nameservers. A possible concern I have is that I've secured my previous domain with certbot, so I'm not sure what will happen when I remove that domain and put in the new one, as there are certbot files configured only for that domain. -
Integrating React with Django in Visual Studio
How can I integrate Django with React in Visual Studio? Can anyone help me out with the steps in creating the folders and installing the package? -
Touch Feedback on custom video player in React
I am working on a React project which allows a user to tap on videos. While it didn't take too long to make it register the tap, creating animations for it is a lot trickier. As a place holder, when a part of the screen is tapped it creates a simple CSS circle appears with the center being the pixel that was tapped. Now, I want to make it look smoother, more like one of these: https://tympanus.net/Development/ClickEffects/ However, these seem to only work on static buttons. All the other solutions I've found had their own hitches; another that seemed interesting turned out to be a plain animation as a series of PNGs which seems pretty inefficient. I didn't try React's TouchableFeedbackNative because it only works on Android. This looked promising, but I don't understand if I'll be able to use it, and I don't want to pay $25 to find out. Does anyone have any suggestions for reusable and (ideally) modifiable animations for this kind of application? I'm happy with using plain CSS animations, but I really would love to avoid making a complicated one from scratch. -
url conflict in Django
I get the same page regardless of what url I use. I get the home.html page for all the ones I have listed. Any suggestions would be valuable. Thanks! urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^signup/', include('log.urls')), url(r'^login/', include('log.urls')), url(r'^logout/', include('log.urls')), url(r'^', include('log.urls')), ] and from from django.conf.urls import url from . import views # We are adding a URL called /home urlpatterns = [ url(r'^signup/', views.signup, name='signup'), url(r'^login/', views.login, name='login'), url(r'^logout/', views.logout, name = 'logout'), url(r'^', views.home, name='home'), ] -
Show python data on the web
So I'm an absolute beginner with python and want to make a website that's shows data from google spreadsheets in html. I'm using gspread and I'm able to get the data from the spreadsheet. The goal is to get working hours from people and display it to them. Ideally you could also input your name into the script so you can only see your own times. Currently I'm stuck on how to display the data and get the input from the user, preferably with html. My code: import gspread from oauth2client.service_account import ServiceAccountCredentials from datetime import date scope = ['https://spreadsheets.google.com/feeds'] creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope) gc = gspread.authorize(creds) sh = gc.open("rooster") weekNumber = date.today().isocalendar()[1] weekWorksheet = sh.get_worksheet(weekNumber-1) employee_name = input("naam:") cell = weekWorksheet.find(employee_name) row_number = cell.row count = 2 while count <= 8: date = weekWorksheet.cell(1, count).value value = weekWorksheet.cell(row_number, count).value print(date, ": ", value) count += 1 -
request.POST dict is empty in AngularJS/Django form
I'm trying to integrate AnularJS with a Django form. When I hit the submission button, nothing gets sent to the Django backend. My forms.py has this: class LoginForm(AuthenticationForm): ''' Form to log in a user ''' error_messages= { "invalid_login": _("Incorrect %(username)s/password combo") } title= "Sign in" username= forms.EmailField( label=_("Email"), widget=forms.TextInput( attrs={ "id":"id_login_username", "type":"email", "placeholder":"Email", "ng-model":"login.email" } ) ) password= forms.CharField( label=_("Password"), widget=forms.PasswordInput( attrs={ "placeholder":"Password", "ng-model":"login.pw", "ng-minlength":settings.MIN_PW_LENGTH } ) ) My urls.py has this: url("^login-register/$", views.login_register, name="login_register"), My views.py has this: def login_register(request, template="pages/login_register.html"): print request.POST My login_register.html has this: {% block extra_head %} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <script type="text/javascript"> var GLOBAL_loginRegURL= "{% url 'login_register' %}"; </script> {% compress js %} <script src="{% static "js/login-register.js" %}"></script> {% endcompress %} {% endblock %} <div id="wrapper" ng-app="app" ng-controller="Ctrl"> <form method="post" name="loginForm" ng-submit="login()"> {% csrf_token %} {% for field in login_form %} <p>{{ field }}</p> {% endfor %} <button type="submit" ng-disabled="!loginForm.username.$valid || !login.pw">Log in</button> </form> </div> My login-register.js looks like this: var app= angular.module("app",[]); app.config(function($interpolateProvider, $httpProvider){ $interpolateProvider.startSymbol("[[["); $interpolateProvider.endSymbol("]]]"); $httpProvider.defaults.xsrfCookieName= "csrftoken"; $httpProvider.defaults.xsrfHeaderName= "X-CSRFToken"; }); app.controller("Ctrl",function($scope, $http){ $scope.login= function(){ var formData= { "username": $scope.login.email, "password": $scope.login.pw }; console.log(formData); $http.post( GLOBAL_loginRegURL, JSON.stringify(formData) ).success(function(data){ }); }; }); When I fill out the login form's "email" and "password" fields and hit … -
Creating a file uploading system in Django
In my Django application I intend to create a file uploading system which puts the user uploaded files in a data folder. In order to do this I followed online tutorials Link 1 Link 2 and coded a below simple application. But it is producing error PermissionError: [Errno 13] Permission denied: '/data' Project Structure <project_name> |--data |--<app_name> |--<project_name> |--manage.py index.html <div class="custom-file"> <input type="file" class="custom-file-input" id="fileupload" name="fileupload" multiple required> <label class="custom-file-label" for="fileupload">Choose files</label> </div> view.py from django.core.files.storage import FileSystemStorage from django.views.decorators.csrf import csrf_exempt @csrf_exempt def upload(request): files = request.FILES.getlist('fileupload') fs = FileSystemStorage(location="/data/upload/") for fl in files: fs.save(fl.name, fl) settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'data') -
How to upload and deploy django cookiecutter project, with docker, to heroku?
I am developing an app with django cookiecutter (with docker and heroku setup) and have come so far as to deploying it. This is my first ever project, so no prior experience with django, docker or heroku. I've read up on it at cookiecutter docs, heroku and a little on the docker website but I still don't how to deploy. I have downloaded the heroki cli , have set up app on heroku with my own domain and a postgres db and I am planning on getting hobby tier to get the automated certificate. All environment variables are set in the .env file and are set in the heroku config vars in my app at heoku. So everything should be alright as far as code and settings. I am also using git as version control. Am I supposed to upload the whole project (code, settings, docker files etc) to heroku with git or by some other means? I saw there was an option to deploy the project with docker deploys aswell at herokus website. What option is the correct one? I was thinking initially that I would just upload the project through git and run docker-compose -f production.yml up (in … -
Django - Automatically filling user in form
I am trying to create a form in Django that when is submitted should save data in DB only for the registered user. Basically, student field should be field in by default with the logged in user The problem is that when I am submitting the form I get the following error message: Cannot assign "< SimpleLazyObject: < User: 123 >> " : "RegistrationRequest.student" must be a "Students" instance. Models.py: class Students(models.Model): Username = models.ForeignKey(User) FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) Group = models.CharField(max_length=4) def __str__(self): return str(self.Username) + ' ' + self.FirstName +' ' + self.LastName class RegistrationRequest(models.Model): date = models.CharField(max_length = 20) title = models.CharField(max_length = 150) description = models.CharField(max_length = 500) teacher = models.CharField(max_length = 50) student = models.ForeignKey(Students) def __str__(self): return str(self.date) + ' ' + str(self.title) + ' ' + str(self.description) + ' ' + str(self.teacher) forms.py class RegistrationRequestForm(forms.ModelForm): date = forms.CharField() title = forms.CharField() description = forms.CharField() teacher = forms.CharField() class Meta: model = RegistrationRequest exclude = ["student"] views.py def registrationRequest(request): form = RegistrationRequestForm(request.POST or None) if request.method == 'POST': if form.is_valid(): publish = form.save(commit=False) publish.student = request.user publish.save() return render(request, 'users/RegistrationRequest.html', {'form':form}) Can you please advise how to solve this problem Thank you! -
OAuth2: Resource owner workflow
The python-social-auth is a fantastic library for integrating oauth2 backend with web application (in my case it is django).So now it is possible to login into my django app with social oauth2 services. However, I'd like the application to act as a resource owner as well. If another application already having a token should be able to call into my django application (XHR Request). The django application should behave as a resource owner. It should use introspect (oauth2 token introspection) the token to validate the it and give access to its resource. How can I customize python-social-auth (social-auth-app-django to be specific) to allow this workflow? The backend should be aware of the token in the request supplied, and should be able to skip login by supplying the token directly to a stage where we can fetch user data from token. This can be achieved by doing the token validation in the application view and redirect to either social login or to resource view. However, my intention is to modify the social-auth pipeline to achieve this so that the User model implemented in social-auth can be effectively used to store user data to backend. -
Django channels 2.0.2 global group
Is there a way to access a group created in one consumer class from within another consumer class? Basically is it posible to have one route set up for a specific consumer which creates a group and the have another route connected to different consumer which would connect to the group created beforehand? -
PyCharm Unresolved reference error Django. Python not recognizing Django
I have just installed Django 2.0, python 3.6.4, and PyCharm 2017 on mac OSX 10.12.6, everything works fine except for the fact that PyCharm is not recognizing Django at all. With any reference to Django, I get an "unresolved reference 'django'" error. It's obviously something I have not set up in the IDE because project runs perfectly. I am new to Mac OS, so maybe there is a path variable I need to set somewhere? When I installed everything I just downloaded python3 and pip installed django IN A VIRTUALENV. I don't know if that will help. I also tried to set the package interpreter in file->default settings->project interpreter. I may have been doing it wrong. In the project interpreter, I tried to add new local and typed in the path of my environment/bin/python but no luck. I even tried installing Django in PyCharm from available packages...nothing. Thanks in advance. -
django joins with many to many relationship
I've looked at multiple answers to similar questions on how to do a join over django models with a many to many relationship but none seem to work, could someone please help. User -> your normal django user model Upload -> has a Model.FileField and a models.ForeignKey(User, on_delete=models.CASCADE) FriendshipRelation -> models.ForeignKey(User, on_delete=models.CASCADE, related_name='friended_fk') and a models.ForeignKey(User, on_delete=models.CASCADE, related_name='friending_fk') Now I'd like to select all Uploads from a given user's friends, how could I do that without hitting the storage system more than once? Many thanks -
Working With Multiple Settings
I try to add multiple settings for my django project. Separate settings for devserver and production. For this I removed my settings.py file and the new file structure would look like this: mysite/ |-- mysite/ | |-- __init__.py | |-- settings/ | | |-- __init__.py | | |-- base.py | | |-- development.py | | |-- production.py | |-- urls.py | +-- wsgi.py +-- manage.py I filled in base.py, development.py, production.py and replaced the path to the root of the project at base.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) to ==> BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) And it working good at my local server when I start python manage.py runserver --settings=mysite.settings.development but when I do the same settings in production I get Internal server error. My server works for Nginx and Uwsgi. -
Django REST-framework: Using serializer for simple ForeignKey-relationship
I'm using the django REST-framework and try to map a simple foreign-key relationship to provide related data for further use, similar to the following request: Using reverse relationships with django-rest-framework's serializer Instead of a result, I receive the following exception: Got AttributeError when attempting to get a value for field album_name on serializer AlbumSerializer. The serializer field might be named incorrectly and not match any attribute or key on the int instance. Original exception text was: 'int' object has no attribute 'album_name'. Models: class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): # album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together = ('album', 'order') ordering = ['order'] def __unicode__(self): return '%d: %s' % (self.order, self.title) Serializers: class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = ('id', 'album_name', 'artist' ) class TrackSerializer(serializers.ModelSerializer): album_id = AlbumSerializer(many=False, read_only=True) class Meta: model = Track fields = ('order', 'title', 'duration', 'album_id') View: class TrackView(viewsets.ModelViewSet): queryset = Track.objects.all().select_related('album') serializer_class = serializers.TrackSerializer What I have tried so far: Serializing Albums with related tracks as nested serializers, using a reverse relationship => works Doing the work just for the TrackSerializer without nested Album … -
If Statement - Django/Python
I am trying to run a basic if statement in Django. I want to say that if the number inputted into the 'waist' text box is less than 100 then to output small if not output medium. My code is as follow; {% block body %} <div class="container"> <h1> Input Details </h1> {% for detail in input_detail %} <br> <br> Waist {{ detail.waist }} <br> <br> {% endfor %} {% if detail.waist <= 100 %} <p> small </p> {% else %} <p> Medium </p> {% endif %} </div> {% endblock %} Any help is greatly appreciated. -
I can't make Django DeleteView to work
So I was trying to set up a DeleteView for my Lecture model. Each course from my Course model has its own slug page. And on that page lectures for a course appear. Thing is that I tried to add a delete button for lectures, but it was unsuccessfully. Here is what what I did: #courses.html {% regroup lectures by get_lecture_category_display as category_list %} <h3>Lectures</h3> <ul> {% for category in category_list %} <strong> <li>{{ category.grouper }}</li> </strong> <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% for file in c.files.all %} {% if file.files %} <li><a href='{{ MEDIA_URL }}{{ file.files.url }}'>download</a></li> {% endif %} {% endfor %} <a href="{% url 'courses:lecture_delete' c.slug %}">Delete</a> {% endfor %} </ul> {% endfor %} </ul> #lecture_confirm_delete.html <form method="post"> {% csrf_token %} Are you sure you want to delete? <input type="submit" value="Confirm"/> </form> #urls.py path('<slug:slug>/', views.courses, name='courses'), path('<slug:slug>/delete/', views.LectureDelete.as_view(), name='lecture_delete'), #models.py class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures', ) lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses', ) lecture_title = models.CharField(max_length=100, blank=True, null=True) content = models.TextField(blank=False, default=No class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = … -
Как подключить angularjs на django проект
Я не могу подключить angular на django Пробовал подключить через static и даже через сервера cdn. Но почему то django этого не видет. Версия django 1.11.3 Помогите пожалуйста